{"id":12662,"library":"webidl-conversions","title":"Web IDL Type Conversions","description":"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.","status":"active","version":"8.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/jsdom/webidl-conversions","tags":["javascript","webidl","web","types"],"install":[{"cmd":"npm install webidl-conversions","lang":"bash","label":"npm"},{"cmd":"yarn add webidl-conversions","lang":"bash","label":"yarn"},{"cmd":"pnpm add webidl-conversions","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package's main module exports an object containing all conversion methods for CommonJS environments.","symbol":"conversions","correct":"const conversions = require('webidl-conversions');"},{"note":"For ES Modules, the default export is the 'conversions' object. Individual conversion functions are properties of this object, not named exports.","wrong":"import { boolean, unsignedLong } from 'webidl-conversions';","symbol":"conversions","correct":"import conversions from 'webidl-conversions';"},{"note":"Individual Web IDL type conversion functions (e.g., 'boolean', 'unsigned long') are accessed as properties of the main 'conversions' object.","wrong":"import { boolean } from 'webidl-conversions';","symbol":"booleanConversion","correct":"const booleanConversion = conversions.boolean;"}],"quickstart":{"code":"import conversions from 'webidl-conversions';\n\n// Example: Implementing a function that mirrors a Web IDL operation\nfunction doWebIDLStuff(name, count) {\n  try {\n    // Convert 'name' to DOMString, treating null as empty string\n    const domName = conversions.DOMString(name, { treatNullAsEmptyString: true });\n    // Convert 'count' to unsigned long, clamping if out of range\n    const ulCount = conversions['unsigned long'](count, { enforceRange: true, clamp: true });\n\n    console.log(`Processing item: \"${domName}\" with count: ${ulCount}`);\n\n    // Demonstrate another conversion: float\n    const floatValue = conversions.float(Math.PI / 2);\n    console.log(`Float value of PI/2: ${floatValue}`);\n\n    // Demonstrate object conversion\n    const obj = conversions.object({ a: 1, b: 'hello' });\n    console.log('Object conversion successful:', obj);\n\n    return `Processed ${domName} ${ulCount} times.`;\n  } catch (error) {\n    if (error instanceof TypeError) {\n      console.error(`Web IDL Conversion Error: ${error.message}`);\n      return `Failed to process: ${error.message}`;\n    } else {\n      throw error;\n    }\n  }\n}\n\n// Run some examples\nconsole.log(doWebIDLStuff('Widget A', 10));\nconsole.log(doWebIDLStuff(null, -5)); // treatNullAsEmptyString and clamp will handle this\nconsole.log(doWebIDLStuff('Item C', '100')); // String '100' converts to number 100\nconsole.log(doWebIDLStuff('Invalid Float', NaN)); // float(NaN) will throw a TypeError\nconsole.log(doWebIDLStuff('Large Number', 999999999999));\n\n// To run this: save as .mjs and run with Node.js >= 20","lang":"javascript","description":"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`."},"warnings":[{"fix":"Upgrade your Node.js environment to version 20 or higher, or use an older version of `webidl-conversions` compatible with your Node.js runtime (e.g., v7.x for Node.js >=12, v6.x for Node.js >=10.4).","message":"Version 8.0.0 and newer require Node.js version 20 or greater. Attempting to use it with older Node.js versions will result in errors.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"If you rely on SharedArrayBuffer conversion logic, ensure your environment supports it. For `ArrayBuffer` conversions, remove the `allowShared` option. Use the new `SharedArrayBuffer` export for explicit conversions.","message":"In v8.0.0, support for environments without SharedArrayBuffer was removed. The `allowShared` option was removed from the `ArrayBuffer` export, and a new `SharedArrayBuffer` export was added, aligning with Web IDL spec updates.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Remove direct calls to `conversions.Function` or `conversions.VoidFunction`. If you need to convert JavaScript functions according to Web IDL rules, consider using `webidl2js`.","message":"Version 7.0.0 removed the `Function` and `VoidFunction` exports. These types are now recommended to be handled by `webidl2js`.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Update any code that references `conversions.void` to use `conversions.undefined` instead.","message":"In version 7.0.0, the `void` export was renamed to `undefined` to reflect updates in the Web IDL specification.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Remove any code that uses `conversions.Error`. Handle JavaScript error objects directly or use appropriate Web IDL types for error-like scenarios.","message":"Version 5.0.0 removed the `Error` export, as the `Error` type was removed from the Web IDL specification.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Discontinue use of `conversions.Date` and `conversions.RegExp`. Convert these types using standard JavaScript methods if needed.","message":"Version 4.0.0 removed the `Date` and `RegExp` exports because these types were also removed from the Web IDL specification.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Always ensure inputs to `conversions.float` or `conversions['unrestricted float']` are finite numbers. Perform a `Number.isFinite()` check before conversion or wrap the conversion in a `try-catch` block.","message":"Conversions for `float` and `unrestricted float` will throw a `TypeError` if the input value is `NaN`, as per the Web IDL specification (float values must be finite).","severity":"gotcha","affected_versions":">=4.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Before converting to `float`, ensure the value is finite using `Number.isFinite(value)`. If it's not finite, handle the condition gracefully or provide a finite default.","cause":"Attempting to convert a non-finite number (like `NaN` or `Infinity`) using `conversions.float` or `conversions['unrestricted float']`, which, according to Web IDL, must be finite.","error":"TypeError: Argument X of Y is not a finite floating-point value."},{"fix":"Use the ES module import syntax: `import conversions from 'webidl-conversions';`.","cause":"Attempting to use `require('webidl-conversions')` inside an ES module (e.g., in a `.mjs` file or when `type: 'module'` is set in `package.json`).","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Remove usage of `conversions.Function` and `conversions.VoidFunction`. These are no longer part of the library and typically handled by `webidl2js` for interface binding.","cause":"Calling `conversions.Function` or `conversions.VoidFunction` after upgrading to version 7.0.0 or later, where these exports were removed.","error":"TypeError: conversions.Function is not a function"},{"fix":"Ensure your Node.js environment meets the minimum version requirement (>=20 for v8.x) and that your module resolution is correctly configured. `webidl-conversions` is distributed as plain JavaScript; this error typically suggests a problem external to the library itself, possibly with how your project is trying to import or transpile modules.","cause":"This package is not published as TypeScript source files that need transpilation by the consumer, but rather compiled JavaScript. This error might indicate a misconfiguration in a build system or an incorrect environment.","error":"TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension \".ts\" for .../node_modules/webidl-conversions/index.ts"},{"fix":"The library's default export is an object containing all conversion functions as properties. Import the entire object and then access the functions: `import conversions from 'webidl-conversions'; const booleanValue = conversions.boolean(input);`","cause":"Attempting to destructure individual conversion functions like `boolean` or `unsignedLong` directly from the `webidl-conversions` package in an ES module import statement.","error":"SyntaxError: The requested module 'webidl-conversions' does not provide an export named 'boolean'"}],"ecosystem":"npm"}