How to use IdlObject method in wpt

Best JavaScript code snippet using wpt

index.js

Source:index.js Github

copy

Full Screen

1// Copyright (C) 2020 Matthew "strager" Glazar2// See end of file for extended copyright information.3let WebIDL2 = require("webidl2");4let stream = require("stream");5let assert = require("assert");6let fs = require("fs");7let parse5 = require("parse5");8let path = require("path");9let extraGlobals = [10 "HTMLDocument", // Written in prose in the HTML specification.11 "Intl", // https://tc39.es/ecma402/12];13async function mainAsync() {14 let specsJSONPath = process.argv[2];15 if (typeof specsJSONPath === "undefined") {16 console.error(17 `usage: ${process.argv[0]} ${process.argv[1]} /path/to/web-specs/specs.json`18 );19 process.exit(1);20 }21 let specs = JSON.parse(fs.readFileSync(specsJSONPath, "utf-8"));22 let specsDirectory = path.dirname(specsJSONPath);23 let specPaths = specs["html-specs"].map((p) => path.join(specsDirectory, p));24 let idlPaths = specs["idl-specs"].map((p) => path.join(specsDirectory, p));25 let idlSourcePath = process.env.DUMP_IDL;26 let idlSourceOutputStream =27 typeof idlSourcePath === "undefined"28 ? new NullWriter()29 : fs.createWriteStream(idlSourcePath);30 let idlObjects = [];31 for (let specPath of specPaths) {32 idlObjects.push(33 ...getIDLObjectsFromSpecificationFile(specPath, idlSourceOutputStream)34 );35 }36 for (let idlPath of idlPaths) {37 idlObjects.push(38 ...getIDLObjectsFromIDLFile(idlPath, idlSourceOutputStream)39 );40 }41 let exposedGlobals = new Globals();42 for (let idlObject of idlObjects) {43 collectExposedGlobals(exposedGlobals, idlObject, idlObjects);44 }45 exposedGlobals.addGlobals("Window", extraGlobals);46 exposedGlobals.addGlobals(47 "Window",48 listRemovedInterfaces(path.join(specsDirectory, "dom/dom.bs"))49 );50 writeCPPFile({51 browserGlobals: exposedGlobals.getGlobalsForNamespaces([52 "Window",53 // EventTarget is implemented by Window.54 "EventTarget",55 ]),56 webWorkerGlobals: exposedGlobals.getGlobalsForNamespaces([57 "DedicatedWorker",58 "DedicatedWorkerGlobalScope",59 "EventTarget",60 "Worker",61 "WorkerGlobalScope",62 ]),63 outputStream: process.stdout,64 });65}66function getIDLObjectsFromSpecificationFile(specPath, idlSourceOutputStream) {67 let idlExtractor = new IDLExtractor();68 let root = parse5.parse(fs.readFileSync(specPath, "utf-8"));69 idlExtractor.visitRoot(root);70 let result = [];71 for (let idl of idlExtractor.getIDLs()) {72 idlSourceOutputStream.write(idl);73 idlSourceOutputStream.write("\n");74 result.push(...WebIDL2.parse(idl));75 }76 return result;77}78class DOMExtractorBase {79 visitRoot(root) {80 this.visitNode(root);81 }82 visitNode(node) {83 if (/^#/.test(node.nodeName)) {84 switch (node.nodeName) {85 case "#document":86 this.visitNodeChildren(node);87 break;88 case "#text":89 this.visitTextNode(node);90 break;91 case "#comment":92 case "#documentType":93 break;94 default:95 throw new TypeError(`Unexpected HTML node type: ${node.nodeName}`);96 }97 } else {98 this.visitElement(node);99 }100 }101 visitElement(node) {102 // Implement in base classes.103 this.visitNodeChildren(node);104 }105 visitTextNode(_node) {106 // Implement in base classes.107 }108 visitNodeChildren(node) {109 for (let child of node.childNodes) {110 this.visitNode(child);111 }112 }113}114class IDLExtractor extends DOMExtractorBase {115 constructor() {116 super();117 this._currentIDLChunks = [];118 this._inIDL = false;119 this._inPre = false;120 this._idls = [];121 }122 visitElement(node) {123 if (124 (node.tagName === "pre" &&125 node.attrs.some((attr) => attr.name === "w-nodev")) ||126 (node.tagName === "div" &&127 node.attrs.some(128 (attr) => attr.name === "class" && attr.value === "example"129 ))130 ) {131 // Ignore IDL examples.132 return;133 }134 let oldInPre = this._inPre;135 if (node.tagName === "pre") {136 this._inPre = true;137 }138 let oldInIDL = this._inIDL;139 if (140 (node.tagName === "code" && this._inPre) ||141 node.tagName === "pre" ||142 node.tagName === "xmp"143 ) {144 if (145 node.attrs.some(146 (attr) =>147 attr.name === "class" && attr.value.split(" ").includes("idl")148 )149 ) {150 this._inIDL = true;151 }152 } else if (node.tagName === "script") {153 if (154 node.attrs.some((attr) => attr.name === "type" && attr.value === "idl")155 ) {156 this._inIDL = true;157 }158 }159 if (this._inIDL && !oldInIDL) {160 this._currentIDLChunks.length = 0;161 }162 this.visitNodeChildren(node);163 if (this._inIDL && !oldInIDL) {164 this._idls.push(this._currentIDLChunks.join(""));165 }166 this._inIDL = oldInIDL;167 this._inPre = oldInPre;168 }169 visitTextNode(node) {170 let match;171 if (this._inIDL) {172 this._currentIDLChunks.push(node.value);173 } else if (174 (match = node.value.match(/^\s*```\s*webidl\s*$(.*?)^\s*```\s*$/ms)) !==175 null176 ) {177 // Parse Markdown embedded within HTML (yuck).178 this._idls.push(match[1]);179 }180 }181 getIDLs() {182 function fixInvalidPartialInterface(idl) {183 // HACK(strager): Fix broken IDL in webappsec-trusted-types.184 return idl.replace(/\b(partial interface \w+) : \w+ \{/g, "$1 {");185 }186 return this._idls.map((idl) => fixInvalidPartialInterface(idl));187 }188}189function getIDLObjectsFromIDLFile(idlPath, idlSourceOutputStream) {190 let idl = fs.readFileSync(idlPath, "utf-8");191 idlSourceOutputStream.write(idl);192 return WebIDL2.parse(idl);193}194function collectExposedGlobals(globals, idlObject, allIDLObjects) {195 switch (idlObject.type) {196 case "callback interface":197 case "interface":198 case "namespace":199 collectExposedGlobalsForInterface(globals, idlObject);200 break;201 case "includes":202 collectExposedGlobalsForIncludes(globals, idlObject, allIDLObjects);203 break;204 case "callback":205 case "dictionary":206 case "enum":207 case "interface mixin":208 case "typedef":209 break;210 default:211 throw new TypeError(`Unexpected IDL object type: ${idlObject.type}`);212 }213}214class Globals {215 constructor() {216 this._globalsByNamespace = new Map();217 }218 addGlobal(namespace, globalName) {219 this._getGlobalsForNamespace(namespace).push(globalName);220 }221 addGlobals(namespace, globalNames) {222 this._getGlobalsForNamespace(namespace).push(...globalNames);223 }224 getGlobalsForNamespaces(namespaces) {225 let globals = new Set();226 for (let namespace of namespaces) {227 for (let global of this._getGlobalsForNamespace(namespace)) {228 globals.add(global);229 }230 }231 return [...globals].sort();232 }233 _getGlobalsForNamespace(namespace) {234 let globals = this._globalsByNamespace.get(namespace);235 if (typeof globals === "undefined") {236 globals = [];237 this._globalsByNamespace.set(namespace, globals);238 }239 return globals;240 }241}242function collectExposedGlobalsForInterface(globals, idlObject) {243 let namespaceWhitelist = [244 "DedicatedWorker",245 "DedicatedWorkerGlobalScope",246 "EventTarget",247 "Window",248 "Worker",249 "WorkerGlobalScope",250 ];251 if (namespaceWhitelist.includes(idlObject.name)) {252 globals.addGlobals(idlObject.name, getInterfaceMemberNames(idlObject));253 }254 let exposingNamespaces = new Set();255 for (let attr of idlObject.extAttrs) {256 if (attr.name === "Exposed") {257 if (attr.params.rhsType === "identifier") {258 exposingNamespaces.add(attr.params.tokens.secondaryName.value);259 }260 if (attr.params.rhsType === "identifier-list") {261 for (let param of attr.params.list) {262 exposingNamespaces.add(param.value);263 }264 }265 }266 }267 for (let namespace of exposingNamespaces) {268 if (!idlObject.extAttrs.some((attr) => attr.name === "LegacyNamespace")) {269 globals.addGlobal(namespace, idlObject.name);270 }271 }272 for (let attr of idlObject.extAttrs) {273 if (attr.name === "LegacyFactoryFunction") {274 if (attr.params.rhsType === "identifier") {275 globals.addGlobal("Window", attr.params.tokens.secondaryName.value);276 }277 }278 if (attr.name === "LegacyWindowAlias") {279 if (attr.params.rhsType === "identifier") {280 globals.addGlobal("Window", attr.params.tokens.secondaryName.value);281 }282 if (attr.params.rhsType === "identifier-list") {283 globals.addGlobals(284 "Window",285 attr.params.list.map((token) => token.value)286 );287 }288 }289 }290}291function collectExposedGlobalsForIncludes(globals, idlObject, allIDLObjects) {292 if (idlObject.target === "Window") {293 let mixinName = idlObject.includes;294 let mixins = allIDLObjects.filter(295 (o) => o.type === "interface mixin" && o.name === mixinName296 );297 if (mixins.length === 0) {298 throw new TypeError(`Could not find mixin named ${mixinName}`);299 }300 for (let mixin of mixins) {301 globals.addGlobals(idlObject.target, getInterfaceMemberNames(mixin));302 }303 }304}305function getInterfaceMemberNames(idlObject) {306 let result = [];307 for (let member of idlObject.members) {308 switch (member.type) {309 case "attribute":310 case "operation":311 if (member.name !== "") {312 result.push(member.name);313 }314 break;315 case "constructor":316 break;317 default:318 throw new TypeError(319 `Unexpected member type for ${idlObject.name}.${member.name}: ${member.type}`320 );321 }322 }323 return result;324}325function listRemovedInterfaces(specPath) {326 let root = parse5.parse(fs.readFileSync(specPath, "utf-8"));327 let extractor = new HistoricalInterfaceExtractor();328 extractor.visitRoot(root);329 return extractor._interfaceNames;330}331class HistoricalInterfaceExtractor extends DOMExtractorBase {332 constructor() {333 super();334 this._inHistorical = false;335 this._inHistoricalDfn = false;336 this._interfaceNames = [];337 }338 visitElement(node) {339 let oldInHistorical = this._inHistorical;340 if (341 node.tagName === "ul" &&342 node.attrs.some(343 (attr) => attr.name === "dfn-type" && attr.value === "interface"344 )345 ) {346 this._inHistorical = true;347 }348 let oldInHistoricalDfn = this._inHistoricalDfn;349 if (this._inHistorical && node.tagName === "dfn") {350 this._inHistoricalDfn = true;351 }352 this.visitNodeChildren(node);353 this._inHistoricalDfn = oldInHistoricalDfn;354 this._inHistorical = oldInHistorical;355 }356 visitTextNode(node) {357 if (this._inHistoricalDfn) {358 this._interfaceNames.push(node.value);359 }360 }361}362class NullWriter extends stream.Writable {363 _write(_chunk, _encoding, _callback) {364 _callback(null);365 }366}367function writeCPPFile({ browserGlobals, webWorkerGlobals, outputStream }) {368 function writeStrings(strings) {369 for (let string of strings) {370 if (!/^[A-Za-z0-9_$]+$/g.test(string)) {371 throw new TypeError(372 `Global variable name doesn't look like an identifier: ${string}`373 );374 }375 outputStream.write(`\n u8"${string}\\0"`);376 }377 }378 outputStream.write(`// Code generated by tools/browser-globals/index.js. DO NOT EDIT.379// source: (various)380// Copyright (C) 2020 Matthew "strager" Glazar381// See end of file for extended copyright information.382#include <quick-lint-js/fe/global-variables.h>383#include <quick-lint-js/port/char8.h>384namespace quick_lint_js {385const char8 global_variables_browser[] =`);386 writeStrings(browserGlobals);387 outputStream.write(`;388const char8 global_variables_web_worker[] =`);389 writeStrings(webWorkerGlobals);390 outputStream.write(`;391}392// quick-lint-js finds bugs in JavaScript programs.393// Copyright (C) 2020 Matthew "strager" Glazar394//395// This file is part of quick-lint-js.396//397// quick-lint-js is free software: you can redistribute it and/or modify398// it under the terms of the GNU General Public License as published by399// the Free Software Foundation, either version 3 of the License, or400// (at your option) any later version.401//402// quick-lint-js is distributed in the hope that it will be useful,403// but WITHOUT ANY WARRANTY; without even the implied warranty of404// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the405// GNU General Public License for more details.406//407// You should have received a copy of the GNU General Public License408// along with quick-lint-js. If not, see <https://www.gnu.org/licenses/>.409`);410}411mainAsync().catch((error) => {412 console.error(error.stack);413 process.exit(1);414});415// quick-lint-js finds bugs in JavaScript programs.416// Copyright (C) 2020 Matthew "strager" Glazar417//418// This file is part of quick-lint-js.419//420// quick-lint-js is free software: you can redistribute it and/or modify421// it under the terms of the GNU General Public License as published by422// the Free Software Foundation, either version 3 of the License, or423// (at your option) any later version.424//425// quick-lint-js is distributed in the hope that it will be useful,426// but WITHOUT ANY WARRANTY; without even the implied warranty of427// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the428// GNU General Public License for more details.429//430// You should have received a copy of the GNU General Public License...

Full Screen

Full Screen

schemas.ts

Source:schemas.ts Github

copy

Full Screen

1import { sync as glob } from 'glob';2import { readFileSync } from 'fs';3import { cleanse } from './cleanse';4import { compile } from '@pyramation/json-schema-to-typescript';5import { parser } from './parse';6import { JSONSchema } from 'wasm-ast-types';7import { IDLObject } from '../types';8interface ReadSchemaOpts {9 schemaDir: string;10 clean?: boolean;11};12interface ReadSchemasValue {13 schemas: JSONSchema[];14 idlObject?: IDLObject15};16export const readSchemas = async ({17 schemaDir, clean = true18}: ReadSchemaOpts): Promise<ReadSchemasValue> => {19 const fn = clean ? cleanse : (str) => str;20 const files = glob(schemaDir + '/**/*.json');21 const schemas = files22 .map(file => JSON.parse(readFileSync(file, 'utf-8')));23 if (schemas.length > 1) {24 // legacy25 // TODO add console.warn here26 return {27 schemas: fn(schemas)28 };29 }30 if (schemas.length === 0) {31 throw new Error('Error [too few files]: requires one schema file per contract');32 }33 if (schemas.length !== 1) {34 throw new Error('Error [too many files]: CosmWasm v1.1 schemas supports one file');35 }36 const idlObject = schemas[0];37 const {38 contract_name,39 contract_version,40 idl_version,41 responses,42 instantiate,43 execute,44 query,45 migrate,46 sudo47 } = idlObject;48 if (typeof idl_version !== 'string') {49 // legacy50 return {51 schemas: fn(schemas)52 };53 }54 // TODO use contract_name, etc.55 return {56 schemas: Object.values(fn({57 instantiate,58 execute,59 query,60 migrate,61 sudo62 })).filter(Boolean),63 idlObject64 };65};66export const findQueryMsg = (schemas) => {67 const QueryMsg = schemas.find(schema => schema.title === 'QueryMsg');68 return QueryMsg;69};70export const findExecuteMsg = (schemas) => {71 const ExecuteMsg = schemas.find(schema =>72 schema.title === 'ExecuteMsg' ||73 schema.title === 'ExecuteMsg_for_Empty' || // if cleanse is used, this is never74 schema.title === 'ExecuteMsgForEmpty'75 );76 return ExecuteMsg;77};78export const findAndParseTypes = async (schemas) => {79 const Types = schemas;80 const allTypes = [];81 for (const typ in Types) {82 if (Types[typ].definitions) {83 for (const key of Object.keys(Types[typ].definitions)) {84 // set title85 Types[typ].definitions[key].title = key;86 }87 }88 const result = await compile(Types[typ], Types[typ].title);89 allTypes.push(result);90 }91 const typeHash = parser(allTypes);92 return typeHash;93};94export const getDefinitionSchema = (schemas: JSONSchema[]): JSONSchema => {95 const aggregateSchema = {96 definitions: {97 //98 }99 };100 schemas.forEach(schema => {101 schema.definitions = schema.definitions || {};102 aggregateSchema.definitions = {103 ...aggregateSchema.definitions,104 ...schema.definitions105 };106 });107 return aggregateSchema;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var IdlObject = wpt.IdlObject;2var IdlArray = wpt.IdlArray;3var test = wpt.test;4var assert = wpt.assert;5var assert_true = wpt.assert_true;6var assert_false = wpt.assert_false;7var assert_equals = wpt.assert_equals;8var assert_array_equals = wpt.assert_array_equals;9var assert_throws = wpt.assert_throws;10var assert_throws_dom = wpt.assert_throws_dom;11var assert_throws_js = wpt.assert_throws_js;12var assert_class_string = wpt.assert_class_string;13var assert_own_property = wpt.assert_own_property;14var assert_in_array = wpt.assert_in_array;15var assert_regexp_match = wpt.assert_regexp_match;16var assert_readonly = wpt.assert_readonly;17var assert_unreached = wpt.assert_unreached;18var assert_precondition = wpt.assert_precondition;19var assert_any = wpt.assert_any;20var assert_all = wpt.assert_all;21var assert_true = wpt.assert_true;22var assert_false = wpt.assert_false;23var assert_equals = wpt.assert_equals;

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Barack_Obama');3page.get(function(err, resp) {4 console.log(resp);5});6var wptools = require('wptools');7var page = wptools.page('Barack_Obama');8page.get(function(err, resp) {9 console.log(resp.json());10});11var wptools = require('wptools');12var page = wptools.page('Barack_Obama');13page.get(function(err, resp) {14 console.log(resp.json().infobox);15});16var wptools = require('wptools');17var page = wptools.page('Barack_Obama');18page.get(function(err, resp) {19 console.log(resp.json().infobox.image);20});21var wptools = require('wptools');22var page = wptools.page('Barack_Obama');23page.get(function(err, resp) {24 console.log(resp.json().infobox.image[0]);25});26var wptools = require('wptools');27var page = wptools.page('Barack_Obama');28page.get(function(err, resp) {29 console.log(resp.json().infobox.image[0].url);30});31var wptools = require('wptools');32var page = wptools.page('Barack_Obama');33page.get(function(err, resp) {34 console.log(resp.json().infobox.birth_date);35});36var wptools = require('wptools');37var page = wptools.page('Barack_Obama');38page.get(function(err, resp) {39 console.log(resp.json().infobox.birth_date[0].value);40});

Full Screen

Using AI Code Generation

copy

Full Screen

1function test() {2 var idl_object = new IdlObject('test');3 idl_object.add_untested_idls('interface Test {};');4 idl_object.add_objects({'Test': ['test']});5 idl_object.test();6}

Full Screen

Using AI Code Generation

copy

Full Screen

1var IdlObject = require('./wptidl.js').IdlObject;2var fs = require('fs');3var idl = new IdlObject();4var idlText = fs.readFileSync('test.idl', 'utf8');5idl.parse(idlText);6var out = fs.openSync('test.out', 'w');7fs.writeSync(out, 'IDL: ' + idlText + '\n');8var idlLines = idlText.split('\n');9for (var i = 0; i < idlLines.length; i++) {10 var line = idlLines[i];11 var idlLine = idl.lines[i];12 if (idlLine) {13 var idlType = idlLine.type;14 var idlName = idlLine.name;15 var idlValue = idlLine.value;16 var idlArguments = idlLine.arguments;17 var idlExtAttrs = idlLine.extAttrs;18 var idlInherits = idlLine.inherits;19 var idlMembers = idlLine.members;20 var idlImplements = idlLine.implements;21 var idlConstType = idlLine.constType;22 var idlConstValue = idlLine.constValue;23 var idlReturnType = idlLine.returnType;24 var idlRaises = idlLine.raises;25 var idlGetter = idlLine.getter;26 var idlSetter = idlLine.setter;27 var idlDeleter = idlLine.deleter;28 var idlCreator = idlLine.creator;29 var idlStringifier = idlLine.stringifier;30 var idlStatic = idlLine.static;31 var idlReadOnly = idlLine.readOnly;32 var idlOptional = idlLine.optional;33 var idlVariadic = idlLine.variadic;34 var idlIn = idlLine.in;35 var idlOut = idlLine.out;36 var idlDictionary = idlLine.dictionary;37 var idlCallback = idlLine.callback;38 var idlEnum = idlLine.enum;39 var idlTypedef = idlLine.typedef;

Full Screen

Using AI Code Generation

copy

Full Screen

1var fs = require('fs');2var wptidl = require('wptidl');3var idl = new wptidl.IdlObject();4idl.add_idls(fs.readFileSync('interfaces.idl', 'utf8'));5idl.add_idls(fs.readFileSync('test.idl', 'utf8'));6var json = idl.to_json();7fs.writeFileSync('wpt.json', JSON.stringify(json));

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful