Web IDL Type Conversions

8.0.1 · active · verified Sun Apr 19

webidl-conversions is a JavaScript library that rigorously implements the Web IDL specification's algorithms for converting JavaScript values to and from Web IDL types. It ensures strict adherence to the Web IDL type conversion rules, including handling edge cases, type coercion, and error conditions, to provide consistent behavior as if the operations were natively defined in Web IDL. The current stable version is 8.0.1, with major version updates typically occurring annually to align with Node.js version requirements and Web IDL specification changes. Key differentiators include its meticulous adherence to the spec, support for multiple JavaScript realms, and options for customizing conversion behavior like clamping integers or allowing shared/resizable buffers, making it a critical component for libraries implementing Web APIs in JavaScript.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and use the `webidl-conversions` library to emulate Web IDL type conversions for function arguments, showcasing common types like `DOMString`, `unsigned long`, `float`, and `object`, along with options like `treatNullAsEmptyString` and `clamp`.

import conversions from 'webidl-conversions';

// Example: Implementing a function that mirrors a Web IDL operation
function doWebIDLStuff(name, count) {
  try {
    // Convert 'name' to DOMString, treating null as empty string
    const domName = conversions.DOMString(name, { treatNullAsEmptyString: true });
    // Convert 'count' to unsigned long, clamping if out of range
    const ulCount = conversions['unsigned long'](count, { enforceRange: true, clamp: true });

    console.log(`Processing item: "${domName}" with count: ${ulCount}`);

    // Demonstrate another conversion: float
    const floatValue = conversions.float(Math.PI / 2);
    console.log(`Float value of PI/2: ${floatValue}`);

    // Demonstrate object conversion
    const obj = conversions.object({ a: 1, b: 'hello' });
    console.log('Object conversion successful:', obj);

    return `Processed ${domName} ${ulCount} times.`;
  } catch (error) {
    if (error instanceof TypeError) {
      console.error(`Web IDL Conversion Error: ${error.message}`);
      return `Failed to process: ${error.message}`;
    } else {
      throw error;
    }
  }
}

// Run some examples
console.log(doWebIDLStuff('Widget A', 10));
console.log(doWebIDLStuff(null, -5)); // treatNullAsEmptyString and clamp will handle this
console.log(doWebIDLStuff('Item C', '100')); // String '100' converts to number 100
console.log(doWebIDLStuff('Invalid Float', NaN)); // float(NaN) will throw a TypeError
console.log(doWebIDLStuff('Large Number', 999999999999));

// To run this: save as .mjs and run with Node.js >= 20

view raw JSON →