### Install webidl2.js via NPM Source: https://github.com/w3c/webidl2.js/blob/main/README.md The standard method for installing the webidl2.js library in a Node.js environment using the Node Package Manager. ```Bash npm install webidl2 ``` -------------------------------- ### Customize WebIDL2.js Write Function Templates Source: https://github.com/w3c/webidl2.js/blob/main/README.md Provides an example of how to customize the output of the `write` function in WebIDL2.js by providing a `templates` object with various callback functions to control the formatting of different WebIDL constructs. ```javascript var result = WebIDL2.write(tree, { templates: { /** * A function that receives syntax strings plus anything the templates returned. * The items are guaranteed to be ordered. * The returned value may be again passed to any template functions, * or it may also be the final return value of `write()`. * @param {any[]} items */ wrap: items => items.join(""), /** * @param {string} t A trivia string, which includes whitespaces and comments. */ trivia: t => t, /** * The identifier for a container type. For example, the `Foo` part of `interface Foo {};`. * @param {string} escaped The escaped raw name of the definition. * @param data The definition with the name * @param parent The parent of the definition, undefined if absent */ name: (escaped, { data, parent }) => escaped, /** * Called for each type referece, e.g. `Window`, `DOMString`, or `unsigned long`. * @param escaped The referenced name. Typically string, but may also be the return * value of `wrap()` if the name contains whitespace. * @param unescaped Unescaped reference. */ reference: (escaped, unescaped) => escaped, /** * Called for each generic-form syntax, e.g. `sequence`, `Promise`, or `maplike`. * @param {string} name The keyword for syntax */ generic: name => name, /** * Called for each nameless members, e.g. `stringifier` for `stringifier;` and `constructor` for `constructor();` * @param {string} name The keyword for syntax */ nameless: (keyword, { data, parent }) => keyword, /** * Called only once for each types, e.g. `Document`, `Promise`, or `sequence`. * @param type The `wrap()`ed result of references and syntatic bracket strings. */ type: type => type, /** * Receives the return value of `reference()`. String if it's absent. */ inheritance: inh => inh, /** * Called for each IDL type definition, e.g. an interface, an operation, or a typedef. * @param content The wrapped value of everything the definition contains. * @param data The original definition object * @param parent The parent of the definition, undefined if absent */ definition: (content, { data, parent }) => content, /** * Called for each extended attribute annotation. * @param content The wrapped value of everything the annotation contains. */ extendedAttribute: content => content, /** * The `Foo` part of `[Foo=Whatever]`. * @param ref The name of the referenced extended attribute name. */ extendedAttributeReference: ref => ref } }); ``` -------------------------------- ### Invalid Callback Syntax in WebIDL Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/callback-noparen.txt This snippet demonstrates an invalid WebIDL callback definition. The parser expects parentheses for arguments even if the argument list is empty, which is missing in the provided example. ```webidl callback YourCall = void; ``` -------------------------------- ### WebIDL Syntax Error: Empty Promise Subtype Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/promise-empty.txt This snippet illustrates a syntax error in a WebIDL file where the Promise type is declared without a subtype. The webidl2.js parser correctly identifies this as an error, indicating that a subtype is required for the Promise. ```webidl typedef Promise<> empty; ^ Missing Promise subtype ``` -------------------------------- ### WebIDL Union Type Syntax Error Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/union-dangling-or.txt This snippet illustrates a syntax error in a WebIDL file. The error occurs in a union type definition where 'or' is followed by an unexpected token, indicating an incomplete union type. The webidl2.js parser will report this as an error. ```webidl Syntax error at line 1 in union-dangling-or.webidl: (One or Two or) UnionOr; ^ No type after open parenthesis or 'or' in union type ``` -------------------------------- ### Invalid WebIDL Syntax Example Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/no-semicolon.txt This snippet demonstrates a malformed WebIDL structure where a partial interface is missing a required semicolon. The parser throws a syntax error at the subsequent enum definition due to the incomplete preceding statement. ```webidl partial interface NoSemicolon enum YouNeedOne { "value" }; ``` -------------------------------- ### WebIDL Enum Syntax Error: Missing Comma Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/enum-wo-comma.txt This WebIDL snippet demonstrates an incorrect enum definition where a comma is missing between enum values. The webidl2.js parser will flag this as a syntax error at the specified location. ```webidl enum NoComma {"value1" "value2"}; ^ No comma between enum values ``` -------------------------------- ### WebIDL Syntax Error: Invalid Extended Attribute Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/extattr-invalid-rhs.txt This snippet illustrates a syntax error in a WebIDL file where an extended attribute list is not properly closed. The webidl2.js parser identifies the issue at line 1, indicating an expected closing token for the extended attribute list. ```webidl [Exposed=*/] ^ Expected a closing token for the extended attribute list ``` -------------------------------- ### Invalid WebIDL Attribute Type Declarations Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/invalid-attribute.txt Examples of invalid WebIDL attribute definitions that violate type constraints. These snippets demonstrate the use of forbidden types such as sequences, records, and dictionaries within interface attributes. ```webidl attribute sequence invalid; attribute record invalid; attribute Dict dict; attribute (Dict or boolean) dictUnion; ``` -------------------------------- ### WebIDL Union Type Syntax Error Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/union-one.txt This snippet illustrates a WebIDL syntax error where a union type is defined with only one member. The webidl2.js parser correctly identifies this as an error, expecting at least two types within the parentheses for a union. This is a common mistake when defining interfaces that can accept multiple data types. ```webidl typedef (OnlyOne) UnionOne; ^ At least two types are expected in a union type but found less ``` -------------------------------- ### WebIDL Syntax Error: Missing Extended Attribute Value Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/extattr-no-rhs.txt This snippet illustrates a common syntax error in WebIDL files where an extended attribute is declared without a corresponding right-hand side value. The webidl2.js parser correctly identifies this as an error, preventing invalid IDL definitions. This error typically occurs when attempting to define attributes like '[Exposed=]' without specifying the target environment. ```webidl [Exposed=] ^ No right hand side to extended attribute assignment ``` -------------------------------- ### POST /write Source: https://github.com/w3c/webidl2.js/blob/main/README.md Converts a WebIDL syntax tree back into a formatted WebIDL string. ```APIDOC ## POST /write ### Description Serializes a syntax tree into a WebIDL string. Accepts a templates object to customize output formatting. ### Method POST ### Endpoint /write ### Parameters #### Request Body - **tree** (object) - Required - The AST to serialize. - **templates** (object) - Optional - Functions to customize serialization of specific nodes (e.g., wrap, trivia, name, type). ### Request Example { "tree": { "type": "interface", "name": "Foo" }, "templates": { "wrap": "items => items.join('')" } } ### Response #### Success Response (200) - **idl** (string) - The serialized WebIDL string. #### Response Example { "idl": "interface Foo {};" } ``` -------------------------------- ### Configure custom productions in webidl2.js Source: https://github.com/w3c/webidl2.js/blob/main/docs/custom-productions.md Demonstrates how to pass an array of custom production functions to the webidl2.write method to extend parsing capabilities. ```javascript webidl2.write(ast, { productions: [...] // An array with custom production functions }); ``` -------------------------------- ### Parse and Write WebIDL with WebIDL2 (Browser) Source: https://github.com/w3c/webidl2.js/blob/main/README.md Illustrates how to use the WebIDL2 library in a web browser using script tags. It shows the usage of `parse`, `write`, and `validate` functions globally available as `WebIDL2`. ```html ``` -------------------------------- ### Parse and Write WebIDL with webidl2.js (Browser Module) Source: https://github.com/w3c/webidl2.js/blob/main/README.md Shows how to import and use the `parse`, `write`, and `validate` functions from the webidl2 library in a browser environment when module support is enabled. ```html ``` -------------------------------- ### Parse and Write WebIDL with webidl2.js (Node.js) Source: https://github.com/w3c/webidl2.js/blob/main/README.md Demonstrates how to use the `parse` and `write` functions from the webidl2 library in a Node.js environment to convert WebIDL strings to syntax trees and back. It also shows the `validate` function. ```javascript const { parse, write, validate } = require("webidl2"); const tree = parse("string of WebIDL"); const text = write(tree); const validation = validate(tree); ``` -------------------------------- ### POST /parse Source: https://github.com/w3c/webidl2.js/blob/main/README.md Converts a raw WebIDL string into a structured syntax tree (AST). ```APIDOC ## POST /parse ### Description Parses a WebIDL string into an AST. Supports optional configuration for source tracking and custom productions. ### Method POST ### Endpoint /parse ### Parameters #### Request Body - **idlString** (string) - Required - The WebIDL content to parse. - **options** (object) - Optional - Configuration object. - **concrete** (boolean) - Include EOF node. - **productions** (array) - Custom production functions. - **sourceName** (string) - Filename or source identifier for error reporting. ### Request Example { "idlString": "interface Foo {};", "options": { "sourceName": "test.idl" } } ### Response #### Success Response (200) - **ast** (object) - The resulting syntax tree. #### Response Example { "type": "interface", "name": "Foo", "members": [] } ``` -------------------------------- ### Use autoParenter for parent tracking Source: https://github.com/w3c/webidl2.js/blob/main/docs/custom-productions.md Shows how to use the autoParenter helper to automatically assign parent references to parsed objects within custom productions. ```javascript const ret = autoParenter(this); ret.default = Default.parse(tokeniser); default.parent // this ``` -------------------------------- ### Include webidl2.js in Browser Source: https://github.com/w3c/webidl2.js/blob/main/README.md How to include the webidl2.js library in a browser environment that does not support ES modules by using a standard script tag. ```HTML ``` -------------------------------- ### Validate WebIDL AST with webidl2.js Source: https://github.com/w3c/webidl2.js/blob/main/README.md Demonstrates how to use the `validate` function from the webidl2 library to check a WebIDL syntax tree for semantic errors and warnings. It shows how to iterate through the validation results and access error messages. ```javascript const validations = validate(tree); for (const validation of validations) { console.log(validation.message); } // Validation error on line X: ... // Validation error on line Y: ... ``` -------------------------------- ### WebIDL AST: Callbacks, Interfaces, and Enums in JavaScript Source: https://context7.com/w3c/webidl2.js/llms.txt Demonstrates parsing WebIDL definitions for callbacks, callback interfaces, and enums into an AST. It shows how to access properties like type, name, return type, arguments, members, and enum values. ```javascript import { parse } from "webidl2"; const idl = ` callback EventCallback = undefined (Event event, boolean bubbles); callback interface EventListener { undefined handleEvent(Event event); }; enum ReadyState { "loading", "interactive", "complete" }; `; const [callback, callbackInterface, readyState] = parse(idl); // Callback function structure console.log({ type: callback.type, // "callback" name: callback.name, // "EventCallback" idlType: callback.idlType, // Return type (undefined) arguments: callback.arguments // Array of argument definitions }); callback.arguments.forEach(arg => { console.log(` ${arg.idlType.idlType} ${arg.name}${arg.optional ? "?" : ""}`); }); // Callback interface (has members like regular interface) console.log({ type: callbackInterface.type, // "callback interface" name: callbackInterface.name, // "EventListener" members: callbackInterface.members.length }); // Enum structure console.log({ type: readyState.type, // "enum" name: readyState.name, // "ReadyState" values: readyState.values.map(v => v.value) // ["loading", "interactive", "complete"] }); ``` -------------------------------- ### Write AST to WebIDL with webidl2.js Source: https://context7.com/w3c/webidl2.js/llms.txt Converts an Abstract Syntax Tree (AST) back into a WebIDL string using the `write` function. Requires the AST to be parsed with `concrete: true` for exact formatting preservation. Optional templates can customize the output, such as generating HTML or syntax highlighting. ```javascript import { parse, write } from "webidl2"; // Basic round-trip: parse and write back const idl = `[Exposed=Window] interface Calculator { attribute long value; undefined add(long num); };`; const ast = parse(idl, { concrete: true }); const output = write(ast); console.log(output === idl); // true // Using templates for custom formatting (e.g., HTML output) const htmlOutput = write(ast, { templates: { // Wrap type names in spans for styling reference: (escaped, unescaped, context) => `${escaped}`, // Wrap definition names name: (name, { data, parent }) => `${name}`, // Wrap entire definitions definition: (content, { data, parent }) => `
${content}
`, // Handle generic types like Promise or sequence generic: (keyword) => `${keyword}`, // Wrap extended attributes extendedAttribute: (content) => `${content}` } }); ``` -------------------------------- ### WebIDL AST: IDL Types and Generics in JavaScript Source: https://context7.com/w3c/webidl2.js/llms.txt Illustrates parsing WebIDL with various type constructs like Promises, sequences, records, union types, and nullable types. It shows how to inspect the AST nodes for these types, including their base type, generic nature, nullability, and union members. ```javascript import { parse } from "webidl2"; const idl = ` [Exposed=Window] interface TypeExamples { attribute Promise asyncName; attribute sequence numbers; attribute record metadata; attribute FrozenArray immutableList; attribute (DOMString or long) mixed; attribute DOMString? nullableName; Promise> fetchNumbers(); }; `; const [iface] = parse(idl); // Examine different type structures iface.members.forEach(member => { const t = member.idlType; console.log(`${member.name}:`); console.log(` base type: ${t.idlType}`); console.log(` generic: ${t.generic || "none"}`); console.log(` nullable: ${t.nullable}`); console.log(` union: ${t.union}`); if (t.union) { console.log(` union members: ${t.idlType.map(u => u.idlType).join(" | ")}`); } if (t.generic) { console.log(` generic args: ${JSON.stringify(t.idlType)}`); } }); // Type structure example for Promise>: // { // type: "return-type", // generic: "Promise", // nullable: false, // union: false, // idlType: [{ // generic: "sequence", // idlType: [{ idlType: "long", generic: "", nullable: false }] // }] // } ``` -------------------------------- ### POST /validate Source: https://github.com/w3c/webidl2.js/blob/main/README.md Validates a WebIDL syntax tree for semantic errors and warnings. ```APIDOC ## POST /validate ### Description Checks the provided AST for semantic issues. Returns an array of error/warning objects. ### Method POST ### Endpoint /validate ### Parameters #### Request Body - **tree** (object) - Required - The AST to validate. ### Request Example { "tree": { ... } } ### Response #### Success Response (200) - **validations** (array) - List of validation objects containing message, line, and level (error/warning). #### Response Example [ { "message": "Invalid interface definition", "line": 1, "level": "error" } ] ``` -------------------------------- ### Replace [AllowShared] BufferSource with AllowSharedBufferSource in WebIDL Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/invalid-allowshared.txt This snippet demonstrates the correct syntax for specifying a shared buffer source in WebIDL. The older `[AllowShared] BufferSource` syntax is deprecated and should be replaced with `AllowSharedBufferSource` to ensure compatibility with newer specifications and tools like webidl2.js. ```webidl foo([AllowShared] BufferSource source); ^ `[AllowShared] BufferSource` is now replaced with AllowSharedBufferSource. ``` -------------------------------- ### Parse WebIDL Interface AST Structure with webidl2.js Source: https://context7.com/w3c/webidl2.js/llms.txt Illustrates how to parse WebIDL interface definitions using `webidl2.parse` and inspect the resulting Abstract Syntax Tree (AST). It covers accessing interface properties like name, inheritance, extended attributes, and members (attributes, operations, constructors). ```javascript import { parse } from "webidl2"; const idl = ` [Exposed=Window, SecureContext] interface Animal { readonly attribute DOMString species; attribute unsigned long age; constructor(DOMString species); DOMString speak(); static Animal create(DOMString species); }; [Exposed=Window] interface Dog : Animal { attribute DOMString breed; undefined bark(); }; `; const [animal, dog] = parse(idl); // Interface structure console.log({ type: animal.type, name: animal.name, partial: animal.partial, inheritance: animal.inheritance, extAttrs: animal.extAttrs }); // Extended attributes animal.extAttrs.forEach(attr => { console.log(`${attr.name} = ${attr.rhs?.value || "(no value)"}`); }); // Members include attributes, operations, constructors animal.members.forEach(member => { switch (member.type) { case "attribute": console.log(`attr ${member.readonly ? "readonly " : ""}${member.idlType.idlType} ${member.name}`); break; case "operation": console.log(`op ${member.special || ""} ${member.idlType.idlType} ${member.name}()`); break; case "constructor": console.log(`constructor(${member.arguments.map(a => a.name).join(", ")})`); break; } }); // Inheritance console.log(`Dog inherits from: ${dog.inheritance}`); ``` -------------------------------- ### WebIDL Custom Productions: Defining and Using in JavaScript Source: https://context7.com/w3c/webidl2.js/llms.txt Shows how to extend the webidl2.js parser with custom syntax, like a 'native attribute' type. It details defining a custom AST node class with `parse` and `write` methods and integrating it into the parser configuration. ```javascript import { parse, write } from "webidl2"; import { Base, autoParenter, type_with_extended_attributes } from "webidl2/productions"; // Define a custom "native" attribute type class NativeAttribute extends Base { static parse(tokeniser) { const startPos = tokeniser.position; const tokens = {}; const ret = autoParenter(new NativeAttribute({ source: tokeniser.source, tokens })); // Look for "native" keyword tokens.native = tokeniser.consumeIdentifier("native"); if (!tokens.native) { tokeniser.unconsume(startPos); return; } // Parse the type ret.idlType = type_with_extended_attributes(tokeniser, "attribute-type") || tokeniser.error("Native attribute lacks a type"); // Parse the name tokens.name = tokeniser.consumeKind("identifier") || tokeniser.error("Native attribute lacks a name"); // Expect semicolon tokens.termination = tokeniser.consume(";") || tokeniser.error("Unterminated attribute"); return ret.this; } get type() { return "native attribute"; } get name() { return this.tokens.name.value; } write(w) { return w.ts.wrap([ this.extAttrs.write(w), w.token(this.tokens.native), w.ts.type(this.idlType.write(w)), w.name_token(this.tokens.name, { data: this, parent: this.parent }), w.token(this.tokens.termination) ]); } } // Use custom production const customIdl = `native long timestamp;`; const ast = parse(customIdl, { productions: [NativeAttribute.parse], concrete: true }); console.log(ast[0].type); // "native attribute" console.log(ast[0].name); // "timestamp" // Round-trip back to text console.log(write(ast)); // "native long timestamp;" ``` -------------------------------- ### Handle WebIDL Parsing Errors with webidl2.js Source: https://context7.com/w3c/webidl2.js/llms.txt Demonstrates how to catch and inspect `WebIDLParseError` exceptions thrown by the `webidl2.parse` function. It shows how to access detailed error information like line number, source name, context, and the input near the error. ```javascript import { parse, WebIDLParseError } from "webidl2"; const invalidIdl = ` interface Broken { attribute string name // missing semicolon attribute long age; }; `; try { parse(invalidIdl, { sourceName: "broken.webidl" }); } catch (error) { if (error instanceof WebIDLParseError) { console.log("Parse Error:"); console.log(` Message: ${error.bareMessage}`); console.log(` Line: ${error.line}`); console.log(` Source: ${error.sourceName}`); console.log(` Context: ${error.context}`); console.log(` Input near error: ${error.input}`); console.log(` Full message:\n${error.message}`); } } ``` -------------------------------- ### Parse WebIDL Dictionary AST Structure with webidl2.js Source: https://context7.com/w3c/webidl2.js/llms.txt Explains how to parse WebIDL dictionary definitions using `webidl2.parse` and examine the AST. It details how to access dictionary properties, including its members (fields), their types, whether they are required, and their default values, as well as inheritance. ```javascript import { parse } from "webidl2"; const idl = ` dictionary Options { DOMString? title = "Untitled"; required DOMString id; sequence values = []; boolean enabled = true; }; dictionary ExtendedOptions : Options { DOMString description; }; `; const [options, extended] = parse(idl); // Dictionary structure console.log({ type: options.type, name: options.name, inheritance: options.inheritance }); // Fields options.members.forEach(field => { console.log({ type: field.type, name: field.name, required: field.required, idlType: field.idlType, default: field.default }); }); // Default values const titleField = options.members[0]; console.log({ defaultType: titleField.default.type, defaultValue: titleField.default.value }); // Inheritance chain console.log(`Extended inherits: ${extended.inheritance}`); ``` -------------------------------- ### Extend WebIDL Parser with Custom Members Source: https://context7.com/w3c/webidl2.js/llms.txt Demonstrates how to define a custom member class by extending the Base production class. This allows the parser to recognize non-standard IDL syntax by providing a custom parse method and registration via the extensions option. ```javascript import { parse, write } from "webidl2"; import { Base, autoParenter, type_with_extended_attributes } from "webidl2/productions"; class CustomMember extends Base { static parse(tokeniser) { const startPos = tokeniser.position; const tokens = {}; const ret = autoParenter(new CustomMember({ source: tokeniser.source, tokens })); tokens.custom = tokeniser.consumeIdentifier("custom"); if (!tokens.custom) { tokeniser.unconsume(startPos); return; } ret.idlType = type_with_extended_attributes(tokeniser, "attribute-type"); tokens.name = tokeniser.consumeKind("identifier"); tokens.termination = tokeniser.consume(";"); return ret.this; } get type() { return "custom member"; } get name() { return this.tokens.name.value; } write(w) { return w.ts.wrap([ this.extAttrs.write(w), w.token(this.tokens.custom), w.ts.type(this.idlType.write(w)), w.name_token(this.tokens.name, { data: this, parent: this.parent }), w.token(this.tokens.termination) ]); } } const idl = `[Exposed=Window] interface Extended { custom long customField; attribute DOMString normalAttr; };`; const ast = parse(idl, { concrete: true, extensions: { interface: { extMembers: [[CustomMember.parse]] } } }); ``` -------------------------------- ### Parse WebIDL to AST with webidl2.js Source: https://context7.com/w3c/webidl2.js/llms.txt Parses a WebIDL string into an Abstract Syntax Tree (AST) using the `parse` function. Options can configure source names, enable concrete mode for whitespace preservation, and support custom syntax. The AST represents the structure of the IDL definitions. ```javascript import { parse } from "webidl2"; // Basic parsing const idl = ` [Exposed=Window] interface Person { attribute DOMString name; attribute unsigned long age; undefined greet(DOMString message); }; `; const ast = parse(idl); console.log(ast[0].type); // "interface" console.log(ast[0].name); // "Person" console.log(ast[0].members[0]); // { type: "attribute", name: "name", idlType: {...} } // Parsing with source name for better error messages const astWithSource = parse(idl, { sourceName: "person.webidl" }); // Concrete mode preserves whitespace/comments for round-trip writing const astConcrete = parse(idl, { concrete: true }); // Access member details const interface_ = ast[0]; interface_.members.forEach(member => { if (member.type === "attribute") { console.log(`Attribute: ${member.name}, Type: ${member.idlType.idlType}`); } else if (member.type === "operation") { console.log(`Operation: ${member.name}, Returns: ${member.idlType.idlType}`); } }); ``` -------------------------------- ### Namespace Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Illustrates the JavaScript object structure for representing namespaces in IDL. It includes fields for type, name, inheritance, partial status, members, and extended attributes. ```javascript { "type": "namespace", "name": "console", "inheritance": null, "partial": false, "members": [...], "extAttrs": [...] } ``` -------------------------------- ### Callback Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Details the JavaScript representation of a callback function in IDL. Key fields include type, name, the return IDL type, arguments, and extended attributes. ```javascript { "type": "callback", "name": "AsyncOperationCallback", "idlType": { "type": "return-type", "generic": "", "nullable": false, "union": false, "idlType": "undefined", "extAttrs": [] }, "arguments": [...], "extAttrs": [] } ``` -------------------------------- ### Dictionary Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Shows the JavaScript object structure for an IDL dictionary, including its name, partial status, members (fields), inheritance, and extended attributes. Also details the structure of a dictionary field. ```javascript { "type": "dictionary", "name": "PaintOptions", "partial": false, "members": [{ "type": "field", "name": "fillPattern", "required": false, "idlType": { "type": "dictionary-type", "generic": "", "nullable": true, "union": false, "idlType": "DOMString", "extAttrs": [] }, "extAttrs": [], "default": { "type": "string", "value": "black" } }], "inheritance": null, "extAttrs": [] } ``` -------------------------------- ### Define Interface Structure Source: https://github.com/w3c/webidl2.js/blob/main/README.md Represents an interface definition in the AST, capturing inheritance, members, and metadata. ```javascript { "type": "interface", "name": "Animal", "partial": false, "members": [], "inheritance": null, "extAttrs": [] } ``` -------------------------------- ### Iterable, Async Iterable, Maplike, Setlike Declarations in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Defines the structure for 'iterable<>', 'async_iterable<>', 'maplike<>', and 'setlike<>' declarations as parsed by webidl2.js. It includes properties for type, IDL types, read-only status, async nature, arguments, and extended attributes. ```javascript { "type": "maplike", // or "iterable" / "setlike" "idlType": /* One or two types */ , "readonly": false, // only for maplike and setlike "async": false, // iterable can be async "arguments": [], // only for async_iterable "extAttrs": [], "parent": { ... } } ``` -------------------------------- ### Typedef Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Illustrates the JavaScript representation of an IDL typedef (type definition). It includes the typedef's name and its associated IDL type, along with extended attributes. ```javascript { "type": "typedef", "idlType": { "type": "typedef-type", "generic": "sequence", "nullable": false, "union": false, "idlType": [ { "type": "typedef-type", "generic": "", "nullable": false, "union": false, "idlType": "Point", "extAttrs": [...] } ], "extAttrs": [...] }, "name": "PointSequence", "extAttrs": [] } ``` -------------------------------- ### Validate WebIDL AST with webidl2.js Source: https://context7.com/w3c/webidl2.js/llms.txt Validates an Abstract Syntax Tree (AST) or an array of ASTs using the `validate` function, returning an array of error objects. Errors include messages, line numbers, rule names, and severity. Optional `autofix` functions can correct issues automatically. ```javascript import { parse, validate, write } from "webidl2"; // Validate for common issues const idl = ` interface MissingExposed { attribute DOMString name; }; dictionary MyDict { long value; }; interface UsesDict { undefined process(MyDict options); }; `; const ast = parse(idl, { concrete: true }); const errors = validate(ast); errors.forEach(error => { console.log(`[${error.level}] ${error.ruleName}: ${error.bareMessage}`); console.log(` Line: ${error.line}`); // Apply autofix if available if (error.autofix) { error.autofix(); console.log(" Applied autofix"); } }); // After autofixes, write back the corrected IDL const fixed = write(ast); console.log(fixed); // Output will have [Exposed=Window] added and dictionary args made optional with defaults // Validation rules include: // - require-exposed: Interfaces must have [Exposed] attribute // - dict-arg-default: Optional dictionary args need default {} // - dict-arg-optional: Dictionary args must be optional // - no-duplicate: No duplicate type names // - constructor-member: Use constructor() syntax, not [Constructor] // - replace-void: Use 'undefined' instead of deprecated 'void' ``` -------------------------------- ### WebIDL Syntax Error: Promise Nullability Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/promise-nullable.txt This snippet illustrates a common syntax error in WebIDL when attempting to make a Promise type nullable. The webidl2.js parser flags this as an invalid declaration, as Promise types themselves cannot be directly suffixed with '?'. The error occurs at the specified line and character position within the WebIDL file. ```webidl interface X { attribute Promise? ^ Promise type cannot be nullable ``` -------------------------------- ### Extended Attributes Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Illustrates the structure of extended attributes within the webidl2.js parser output. It shows the 'extAttrs' array containing attribute objects with properties like 'name', 'arguments', 'type', and 'rhs'. ```javascript { "extAttrs": [{ "name": "PutForwards", "arguments": [...], "type": "extended-attribute", "rhs": { "type": "identifier", "value": "foo" }, "parent": { ... } }] } ``` -------------------------------- ### Define negative infinity constant in WebIDL Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/spaced-negative-infinity.txt This snippet demonstrates the invalid syntax that triggers a parser error in webidl2.js. The parser expects a direct numeric value or a literal, but fails to associate the unary negative operator with the Infinity keyword. ```webidl interface X { const float infinity = - Infinity; }; ``` -------------------------------- ### Argument Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Defines the structure for an argument in an operation or constructor. It includes details like the argument's name, its IDL type, whether it's optional or variadic, and any default value. ```javascript { "arguments": [{ "type": "argument", "default": null, "optional": false, "variadic": true, "extAttrs": [], "idlType": { "type": "argument-type", "generic": "", "nullable": false, "union": false, "idlType": "float", "extAttrs": [...] }, "name": "ints", "parent": { ... } }] } ``` -------------------------------- ### Legacy Iterable Syntax Error in WebIDL Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/legacyiterable.txt This snippet demonstrates the invalid syntax encountered in WebIDL files when using generic types with the legacyiterable keyword. The parser currently fails to process this structure, requiring a revision to standard WebIDL compliance or parser updates. ```webidl interface LegacyIterable { legacyiterable; }; ``` -------------------------------- ### Includes Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Defines the JavaScript structure for an IDL 'includes' statement, specifying which interface (target) includes which interface mixin (includes), along with any extended attributes. ```javascript { "type": "includes", "target": "Node", "includes": "EventTarget", "extAttrs": [] } ``` -------------------------------- ### Analyze WebIDL Syntax Error Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/unknown-generic.txt This snippet represents the problematic WebIDL syntax that triggers a parsing error in the WebIDL2.js library. It demonstrates the use of an unsupported generic type 'ResponsePromise' inside an interface definition. ```webidl interface FetchEvent { ResponsePromise default(); }; ``` -------------------------------- ### Tokeniser API interface Source: https://github.com/w3c/webidl2.js/blob/main/docs/custom-productions.md Describes the Tokeniser interface used by custom productions to inspect and consume tokens from the IDL input stream. ```typescript type TokenType = "decimal" | "integer" | "identifier" | "string" | "whitespace" | "comment" | "other"; interface Tokeniser { position: number; constructor(idl: string); error(message: string): never; probeKind(type: TokenType): boolean; probe(value): boolean; consumeKind(...candidates: TokenType[]); consume(...candidates: string[]); consumeIdentifier(value: string); unconsume(position: number); } ``` -------------------------------- ### Identify WebIDL Syntax Error Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/async-iterable-readonly.txt This snippet demonstrates the invalid syntax encountered in a WebIDL file. The error occurs because the 'async_iterable' declaration lacks a return type, which is mandatory according to the WebIDL specification. ```webidl interface AsyncIterable { readonly async_iterable any; // required only for webidl2.write() }; ``` -------------------------------- ### Define IDL Type Structure Source: https://github.com/w3c/webidl2.js/blob/main/README.md Represents the standard structure of an IDL type within the AST, including generic information, nullability, and extended attributes. ```javascript { "type": "attribute-type", "generic": "", "idlType": "unsigned short", "nullable": false, "union": false, "extAttrs": [] } ``` -------------------------------- ### Correcting Optional Dictionary Arguments in WebIDL Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/argument-dict-default.txt Optional dictionary arguments in WebIDL must be initialized with a default value of '{}'. This snippet demonstrates the correct syntax to resolve validation errors in interface constructors and operations. ```webidl interface X { constructor(optional Dict dict = {}); undefined operation(optional Dict dict = {}); }; ``` -------------------------------- ### WebIDL Syntax Error: Missing Semicolon in Callback Interface Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/no-semicolon-callback.txt This snippet illustrates a common syntax error in WebIDL where a semicolon is omitted after a callback interface definition. The webidl2.js parser correctly identifies this as an error, indicating the expected location of the missing semicolon. Ensure all callback interface declarations are properly terminated. ```webidl enum YouNeedOne { // ... enum members }; callback interface NoSemicolon { // ... interface members } ^ Missing semicolon after callback interface ``` -------------------------------- ### Malformed WebIDL setlike declaration Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/setlike-2types.txt This snippet demonstrates the invalid syntax causing a parsing error in webidl2.js. The setlike declaration is missing the closing greater-than sign, which violates the WebIDL specification. ```webidl interface SetLikeTwoTypes { setlike; }; ``` -------------------------------- ### Operation Member Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Defines the structure for an operation member in WebIDL. It includes details like the operation's name, return type, arguments, and any special modifiers or extended attributes. The 'type' field is always 'operation'. ```javascript { "type": "operation", "special": "", "idlType": { "type": "return-type", "generic": "", "nullable": false, "union": false, "idlType": "undefined", "extAttrs": [] }, "name": "intersection", "arguments": [{ "default": null, "optional": false, "variadic": true, "extAttrs": [], "idlType": { "type": "argument-type", "generic": "", "nullable": false, "union": false, "idlType": "long", "extAttrs": [...] }, "name": "ints" }], "extAttrs": [], "parent": { ... } } ``` -------------------------------- ### Define Exposed Namespace in WebIDL Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/exposed.txt Namespaces require the [Exposed] extended attribute to define where they are available. Failing to include this attribute results in a validation error. ```webidl [Exposed=Window] namespace MyNamespace { // Namespace members }; ``` -------------------------------- ### Invalid WebIDL Operation Syntax Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/no-semicolon-operation.txt This snippet demonstrates the invalid syntax causing a parsing error in webidl2.js. The operation 'eve()' lacks a terminating semicolon, which is required by the WebIDL specification. ```webidl interface Waka { void eve() }; ``` -------------------------------- ### Validate WebIDL Enum Syntax Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/enum-empty.txt Demonstrates an invalid empty enum definition in WebIDL. This code triggers a syntax error because the WebIDL specification requires enums to contain at least one identifier. ```webidl enum Empty {}; ``` -------------------------------- ### End of File (EOF) Marker in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Represents the end-of-file marker generated by the webidl2.js parser when the 'concrete' option is true. This marker is essential for writers to preserve trailing comments and whitespace. ```javascript { "type": "eof", "value": "" } ``` -------------------------------- ### Invalid WebIDL Interface Inheritance Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/inheritance-typeless.txt This snippet demonstrates the invalid WebIDL syntax that triggers a parser error. The interface 'X' attempts to inherit from an empty base, which violates the WebIDL specification requiring a valid identifier for inheritance. ```webidl interface X: {}; ``` -------------------------------- ### Parse and Validate WebIDL Input Source: https://github.com/w3c/webidl2.js/blob/main/checker/index.html This function processes raw WebIDL text by invoking the library's parse and validate methods. It updates the UI with validation messages and optionally applies autofixes if requested by the user. ```javascript function checkWebIDL(textToCheck) { const validation = document.getElementById("webidl-checker-validation"); const autofix = document.getElementById("webidl-checker-autofix"); let parserResult = null; try { parserResult = parse(textToCheck); const validationResult = validate(parserResult); validation.value = validationResult.map(v => v.message).join("\n\n") || "WebIDL parsed successfully!"; if (autofix.checked) { for (const v of validationResult) { if (v.autofix) { v.autofix(); } } return write(parserResult); } } catch (e) { validation.value = "Exception while parsing WebIDL. See JavaScript console for more details.\n\n" + e.toString(); throw e; } finally { formatParserOutput(parserResult); } } ``` -------------------------------- ### WebIDL Syntax Error: Missing Return Type in Interface Operation Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/operation-too-special.txt This snippet illustrates a common WebIDL syntax error where an operation within an interface is defined without specifying its return type. The webidl2.js parser flags this issue, indicating that a return type is expected before the operation name and its parameters. This error prevents the correct parsing and generation of WebIDL definitions. ```webidl interface Ako { getter setter void maki() ^ Missing return type ``` -------------------------------- ### Invalid WebIDL Union Type Syntax Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/union-zero.txt This snippet demonstrates the invalid syntax found in 'union-zero.webidl'. The parser expects at least one type within the parentheses of a union definition, but found an empty set. ```webidl typedef () UnionZero; ``` -------------------------------- ### Constructor Operation Member Structure in JS Source: https://github.com/w3c/webidl2.js/blob/main/README.md Represents a constructor operation member. This structure is used for defining constructors within an interface. It includes the 'type' field set to 'constructor' and an array of arguments. ```javascript { "type": "constructor", "arguments": [{ "default": null, "optional": false, "variadic": true, "extAttrs": [], "idlType": { "type": "argument-type", "generic": "", "nullable": false, "union": false, "idlType": "long", "extAttrs": [...] }, "name": "ints" }], "extAttrs": [], "parent": { ... } } ``` -------------------------------- ### WebIDL Syntax Error: Nullable Constant Type Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/const-nullable.txt This snippet illustrates a WebIDL syntax error where a constant is declared with a nullable type. WebIDL does not allow constants to be nullable. The webidl2.js parser correctly identifies this as an error. ```webidl interface MyConstants { const boolean? ARE_WE_THERE_YET = false; }; ``` -------------------------------- ### WebIDL Record Key Type Validation Source: https://github.com/w3c/webidl2.js/blob/main/test/invalid/baseline/record-key.txt This snippet illustrates the WebIDL syntax error when a record's key type is not one of the allowed types (ByteString, DOMString, USVString). The parser correctly identifies the invalid type and provides an informative error message. ```webidl interface Foo { void foo(record param ^ Record key must be one of: ByteString, DOMString, USVString ```