Best JavaScript code snippet using wpt
webidl2ts.js
Source:webidl2ts.js
1// adapted from https://github.com/markandrus/webidl2.js/blob/3d489b89f191f6ea7bda4388419c51b3d82bd169/scripts/typescript.js2import { parse } from "webidl2";3/**4 * @param {string} filepath5 * @returns {string}6 * @throws {Error}7 */8export function webidl2ts(unparsed /* : string */) /* : void */ {9 const idlDefinitions = parse(unparsed);10 const typescript = `${printIDLDefinitions(idlDefinitions)}`;11 return typescript;12}13/**14 * @param {IDLArgument} arg15 * @returns {string}16 */17function printIDLArgument(arg /* : IDLArgument */) /* : string */ {18 return `${arg.name}${arg.optional ? "?" : ""}: ${printIDLType(arg.idlType)}`;19}20/**21 * @param {Array<IDLArgument>} args22 * @returns {string}23 */24function printIDLArguments(args /* : Array<IDLArgument> */) /* : string */ {25 return args.map(printIDLArgument).join(", ");26}27/**28 * @param {IDLAttributeMember} idlAttributeMember29 * @returns {string}30 */31function printIDLAttributeMember(32 idlAttributeMember /* : IDLAttributeMember */33) /* : string */ {34 return ` ${idlAttributeMember.name}: ${printIDLType(35 idlAttributeMember.idlType36 )};`;37}38function printIDLOperationMember(idlMember) {39 let prefix =40 idlMember.special && idlMember.special.value41 ? { getter: "get", setter: "set" }[idlMember.special.value] || ""42 : "";43 return ` ${prefix} ${44 idlMember.body.name ? idlMember.body.name.value : ""45 }(${printIDLArguments(idlMember.body.arguments)}): ${printIDLType(46 idlMember.body.idlType47 )}`;48}49/**50 * @param {IDLDefinition} idlDefinition51 * @returns {?string}52 * @throws {Error}53 */54function printIDLDefinition(55 idlDefinition /* : IDLDefinition */56) /* : ?string */ {57 switch (idlDefinition.type) {58 case "dictionary":59 return printIDLDictionary(idlDefinition);60 case "enum":61 return printIDLEnum(idlDefinition);62 case "interface":63 return printIDLInterface(idlDefinition);64 case "typedef":65 // NOTE(mroberts): WebIDL cannot represent a type which is an empty Array,66 // nor can it represent "pairs" (e.g., an Array of length two); so we67 // special case these here.68 if (69 idlDefinition.name === "EmptyArray" ||70 idlDefinition.name === "PairOfIDLTypes"71 ) {72 return null;73 }74 return printIDLTypedef(idlDefinition);75 case "eof":76 return "";77 default:78 throw new Error(`I don't know how to print ${idlDefinition.type}s`);79 }80}81/**82 * @param {Array<IDLDefinition>} idlDefinitions83 * @returns {string}84 * @throws {Error}85 */86function printIDLDefinitions(87 idlDefinitions /* : Array<IDLDefinition> */88) /* : string */ {89 const typeScriptDefinitions = [];90 for (let idlDefinition of idlDefinitions) {91 const typeScriptDefinition = printIDLDefinition(idlDefinition);92 if (typeScriptDefinition) {93 typeScriptDefinitions.push(typeScriptDefinition);94 }95 }96 return typeScriptDefinitions.join("\n");97}98/**99 * @param {IDLDictionary} idlDictionary100 * @returns {string}101 */102function printIDLDictionary(103 idlDictionary /* : IDLDictionary */104) /* : string */ {105 const n = idlDictionary.members.length;106 return `export type ${idlDictionary.name} = {107${idlDictionary.members108 .map((member, i) => {109 return ` ${member.name}${member.required ? "" : "?"}: ${printIDLType(110 member.idlType111 )}${i === n - 1 ? "" : ","}`;112 })113 .join("\n")}114};115`;116}117/**118 * @param {IDLEnum} idlEnum119 * @returns {string}120 */121function printIDLEnum(idlEnum /* : IDLEnum */) /* : string */ {122 const n = idlEnum.values.length;123 return `export type ${idlEnum.name}124${idlEnum.values125 .map((value, i) => {126 return ` ${i ? "|" : "="} ${JSON.stringify(value)}${127 i === n - 1 ? ";" : ""128 }`;129 })130 .join("\n")}131`;132}133/**134 * @param {IDLInterface} idlInterface135 * @returns {string}136 * @throws {Error}137 */138function printIDLInterface(idlInterface /* : IDLInterface */) /* : string */ {139 const constructor = idlInterface.extAttrs.items.find(extAttr => {140 return extAttr.name === "Constructor";141 });142 let out = `export ${constructor ? "class" : "interface"} ${143 idlInterface.name144 }${145 idlInterface.inheritance ? ` extends ${idlInterface.inheritance}` : ""146 } {\n`;147 if (constructor) {148 out += ` constructor(${printIDLArguments(149 constructor.arguments || []150 )});\n`;151 }152 if (idlInterface.members.length) {153 out += printIDLMembers(idlInterface.members);154 }155 return out + "\n}\n";156}157/**158 * @param {IDLMember} idlMember159 * @returns {string}160 * @throws {Error}161 */162function printIDLMember(idlMember /* : IDLMember */) /* : string */ {163 switch (idlMember.type) {164 case "attribute":165 return printIDLAttributeMember(idlMember);166 case "operation":167 return printIDLOperationMember(idlMember);168 default:169 throw new Error(`I don't know how to print member type: ${idlMember}`);170 }171}172/**173 * @param {IDLMember} idlMembers174 * @returns {string}175 * @throws {Error}176 */177function printIDLMembers(idlMembers /* : Array<IDLMember> */) /* : string */ {178 return idlMembers.map(printIDLMember).join("\n");179}180/**181 * @param {IDLType} idlType182 * @returns {string}183 */184function printIDLType(idlType /* : IDLType */) /* : string */ {185 let before = "";186 let after = "";187 if (idlType.generic) {188 before = `${idlType.generic.value}<` + before;189 after += ">";190 }191 if (idlType.nullable) {192 after += "|null";193 }194 if (typeof idlType.idlType === "string") {195 let type = nativeTypes[idlType.idlType] || idlType.idlType;196 return `${before}${type}${after}`;197 } else if (Array.isArray(idlType.idlType)) {198 return `${before}${idlType.idlType.map(printIDLType).join("|")}${after}`;199 }200 return `${before}${printIDLType(idlType.idlType)}${after}`;201}202const nativeTypes = {203 // NOTE(mroberts): WebIDL cannot represent a type which is an empty Array,204 // nor can it represent "pairs" (e.g., an Array of length two); so we205 // special case these here.206 EmptyArray: "[]",207 PairOfIDLTypes: "[IDLType, IDLType]",208 sequence: "Array"209};210/**211 * @param {IDLTypedef} idlTypedef212 * @returns {string}213 * @throws {Error}214 */215function printIDLTypedef(idlTypedef /* : IDLTypedef */) /* : string */ {216 if (Array.isArray(idlTypedef.idlType.idlType)) {217 const n = idlTypedef.idlType.idlType.length;218 return `export type ${idlTypedef.name}219${idlTypedef.idlType.idlType220 .map((idlType, i) => {221 return ` ${i ? "|" : "="} ${printIDLType(idlType)}${222 i === n - 1 ? ";" : ""223 }`;224 })225 .join("\n")}226`;227 } else if (typeof idlTypedef.idlType.idlType === "string") {228 return `export type ${idlTypedef.name} = ${idlTypedef.idlType.idlType}229`;230 }231 throw new Error(`I only know how to print typedefs for unions`);...
IdlCoder.ts
Source:IdlCoder.ts
1/**2 * This file is copy-pasted from the anchor codebase,3 * because it's a private API which we should either ask to make public4 * or we can replace this with beet and our custom defined types.5 *6 * @module7 */8import camelCase from "camelcase";9// @ts-ignore10import { Layout } from "buffer-layout";11import * as borsh from "@project-serum/borsh";12import {13 IdlEnumVariant,14 IdlField,15 IdlType,16 IdlTypeDef,17} from "@project-serum/anchor/src/idl";18import { IdlError } from "@project-serum/anchor";19export class IdlCoder {20 public static fieldLayout(21 field: { name?: string } & Pick<IdlField, "type">,22 types?: IdlTypeDef[]23 ): Layout {24 const fieldName =25 field.name !== undefined ? camelCase(field.name) : undefined;26 switch (field.type) {27 case "bool": {28 return borsh.bool(fieldName);29 }30 case "u8": {31 return borsh.u8(fieldName);32 }33 case "i8": {34 return borsh.i8(fieldName);35 }36 case "u16": {37 return borsh.u16(fieldName);38 }39 case "i16": {40 return borsh.i16(fieldName);41 }42 case "u32": {43 return borsh.u32(fieldName);44 }45 case "i32": {46 return borsh.i32(fieldName);47 }48 case "f32": {49 return borsh.f32(fieldName);50 }51 case "u64": {52 return borsh.u64(fieldName);53 }54 case "i64": {55 return borsh.i64(fieldName);56 }57 case "f64": {58 return borsh.f64(fieldName);59 }60 case "u128": {61 return borsh.u128(fieldName);62 }63 case "i128": {64 return borsh.i128(fieldName);65 }66 case "bytes": {67 return borsh.vecU8(fieldName);68 }69 case "string": {70 return borsh.str(fieldName);71 }72 case "publicKey": {73 return borsh.publicKey(fieldName);74 }75 default: {76 if ("vec" in field.type) {77 return borsh.vec(78 IdlCoder.fieldLayout(79 {80 name: undefined,81 type: field.type.vec,82 },83 types84 ),85 fieldName86 );87 } else if ("option" in field.type) {88 return borsh.option(89 IdlCoder.fieldLayout(90 {91 name: undefined,92 type: field.type.option,93 },94 types95 ),96 fieldName97 );98 } else if ("defined" in field.type) {99 const defined = field.type.defined;100 // User defined type.101 if (types === undefined) {102 throw new IdlError("User defined types not provided");103 }104 const filtered = types.filter((t) => t.name === defined);105 if (filtered.length !== 1) {106 throw new IdlError(`Type not found: ${JSON.stringify(field)}`);107 }108 return IdlCoder.typeDefLayout(filtered[0], types, fieldName);109 } else if ("array" in field.type) {110 const arrayTy = field.type.array[0];111 const arrayLen = field.type.array[1];112 const innerLayout = IdlCoder.fieldLayout(113 {114 name: undefined,115 type: arrayTy,116 },117 types118 );119 return borsh.array(innerLayout, arrayLen, fieldName);120 } else {121 throw new Error(`Not yet implemented: ${field}`);122 }123 }124 }125 }126 public static typeDefLayout(127 typeDef: IdlTypeDef,128 types: IdlTypeDef[] = [],129 name?: string130 ): Layout {131 if (typeDef.type.kind === "struct") {132 const fieldLayouts = typeDef.type.fields.map((field) => {133 const x = IdlCoder.fieldLayout(field, types);134 return x;135 });136 return borsh.struct(fieldLayouts, name);137 } else if (typeDef.type.kind === "enum") {138 const variants = typeDef.type.variants.map((variant: IdlEnumVariant) => {139 const name = camelCase(variant.name);140 if (variant.fields === undefined) {141 return borsh.struct([], name);142 }143 const fieldLayouts = variant.fields.map((f: IdlField | IdlType) => {144 if (!f.hasOwnProperty("name")) {145 throw new Error("Tuple enum variants not yet implemented.");146 }147 // this typescript conversion is ok148 // because if f were of type IdlType149 // (that does not have a name property)150 // the check before would've errored151 return IdlCoder.fieldLayout(f as IdlField, types);152 });153 return borsh.struct(fieldLayouts, name);154 });155 if (name !== undefined) {156 // Buffer-layout lib requires the name to be null (on construction)157 // when used as a field.158 return borsh.rustEnum(variants).replicate(name);159 }160 return borsh.rustEnum(variants, name);161 } else {162 throw new Error(`Unknown type kint: ${typeDef}`);163 }164 }...
Using AI Code Generation
1function runTest()2{3 var success;4 if(checkInitialization(builder, "IdlTypedef") != null) return;5 var testNode = builder.getElementById("typedef");6 if(testNode != null)7 {8 var vtypedef;9 var vtypedefName;10 var vtypedefType;11 var vtypedefExtAttrs;12 var vtypedefExtAttr;13 var vtypedefExtAttrName;14 var vtypedefExtAttrValue;15 var vtypedefExtAttrType;16 var vtypedefExtAttrRetType;17 var vtypedefExtAttrArgs;18 var vtypedefExtAttrArgsType;19 var vtypedefExtAttrArgsName;20 var vtypedefExtAttrArgsVarArgs;21 var vtypedefExtAttrArgsOptional;22 var vtypedefExtAttrArgsVarArgsOptional;23 var vtypedefExtAttrArgsFixedArgs;24 var vtypedefExtAttrArgsArg;25 var vtypedefExtAttrArgsArgType;26 var vtypedefExtAttrArgsArgName;27 var vtypedefExtAttrArgsArgVarArgs;28 var vtypedefExtAttrArgsArgOptional;29 var vtypedefExtAttrArgsArgVarArgsOptional;30 var vtypedefExtAttrArgsArgFixedArgs;31 var vtypedefExtAttrArgsArgArg;32 var vtypedefExtAttrArgsArgArgType;33 var vtypedefExtAttrArgsArgArgName;34 var vtypedefExtAttrArgsArgArgVarArgs;35 var vtypedefExtAttrArgsArgArgOptional;36 var vtypedefExtAttrArgsArgArgVarArgsOptional;37 var vtypedefExtAttrArgsArgArgFixedArgs;38 var vtypedefExtAttrArgsArgArgArg;39 var vtypedefExtAttrArgsArgArgArgType;40 var vtypedefExtAttrArgsArgArgArgName;41 var vtypedefExtAttrArgsArgArgArgVarArgs;42 var vtypedefExtAttrArgsArgArgArgOptional;43 var vtypedefExtAttrArgsArgArgArgVarArgsOptional;44 var vtypedefExtAttrArgsArgArgArgFixedArgs;45 var vtypedefExtAttrArgsArgArgArgArg;46 var vtypedefExtAttrArgsArgArgArgArgType;47 var vtypedefExtAttrArgsArgArgArgArgName;48 var vtypedefExtAttrArgsArgArgArgArgVarArgs;49 var vtypedefExtAttrArgsArgArgArgArgOptional;
Using AI Code Generation
1var wptidl = require('./wptidl');2var fs = require('fs');3var idl = fs.readFileSync('test.idl').toString();4var idlInterface = new wptidl.IdlInterface(idl);5var idlTypedef = idlInterface.getTypedef('TestTypedef');6console.log(idlTypedef.idlType);7console.log(idlTypedef.name);8console.log(idlTypedef.idlType.idlType);9console.log(idlTypedef.idlType.array);10console.log(idlTypedef.idlType.generic);11console.log(idlTypedef.idlType.nullable);12console.log(idlTypedef.idlType.union);13console.log(idlTypedef.idlType.unionMemberTypes);14console.log(idlTypedef.idlType.unionMemberTypes[0].idlType);15console.log(idlTypedef.idlType.unionMemberTypes[0].array);16console.log(idlTypedef.idlType.unionMemberTypes[0].generic);17console.log(idlTypedef.idlType.unionMemberTypes[0].nullable);18console.log(idlTypedef.idlType.unionMemberTypes[0].union);19typedef (DOMString or long) TestTypedef;
Using AI Code Generation
1const wptools = require('wptools');2const wikiIdlTypedef = new wptools.idlTypedef();3 console.log(res);4}).catch(function(err){5 console.log(err);6});
Using AI Code Generation
1wptext = require('wptext');2wptext.IdlTypedef('typedef short unsigned int my_short;');3wptext = require('wptext');4wptext.IdlTypedef('typedef short unsigned int my_short;');5wptext = require('wptext');6wptext.IdlTypedef('typedef short unsigned int my_short;');7wptext = require('wptext');8wptext.IdlTypedef('typedef short unsigned int my_short;');9wptext = require('wptext');10wptext.IdlTypedef('typedef short unsigned int my_short;
Using AI Code Generation
1var wptext = require('wptext');2var idl = "typedef DOMString DOMTimeStamp;";3var idl2 = "typedef (DOMString or unsigned long) DOMTimeStamp;";4var idl3 = "typedef (DOMString or unsigned long or DOMTimeStamp) DOMTimeStamp;";5var idl4 = "typedef (DOMString or unsigned long or DOMTimeStamp) DOMTimeStamp;";6var idl5 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";7var idl6 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";8var idl7 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";9var idl8 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";10var idl9 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";11var idl10 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";12var idl11 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";13var idl12 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";14var idl13 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp) DOMTimeStamp;";15var idl14 = "typedef (DOMString or unsigned long or DOMTimeStamp or DOMTimeStamp or DOMTimeStamp or DOMT
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!