Best JavaScript code snippet using wpt
00_webidl.js
Source:00_webidl.js
1// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.2// Adapted from https://github.com/jsdom/webidl-conversions.3// Copyright Domenic Denicola. Licensed under BSD-2-Clause License.4// Original license at https://github.com/jsdom/webidl-conversions/blob/master/LICENSE.md.5/// <reference path="../../core/internal.d.ts" />6"use strict";7((window) => {8 const {9 ArrayBuffer,10 ArrayBufferIsView,11 ArrayPrototypeForEach,12 ArrayPrototypePush,13 ArrayPrototypeSort,14 ArrayIteratorPrototype,15 BigInt,16 BigIntAsIntN,17 BigIntAsUintN,18 DataView,19 Float32Array,20 Float64Array,21 FunctionPrototypeBind,22 Int16Array,23 Int32Array,24 Int8Array,25 isNaN,26 MathFloor,27 MathFround,28 MathMax,29 MathMin,30 MathPow,31 MathRound,32 MathTrunc,33 Number,34 NumberIsFinite,35 NumberIsNaN,36 // deno-lint-ignore camelcase37 NumberMAX_SAFE_INTEGER,38 // deno-lint-ignore camelcase39 NumberMIN_SAFE_INTEGER,40 ObjectCreate,41 ObjectDefineProperties,42 ObjectDefineProperty,43 ObjectGetOwnPropertyDescriptor,44 ObjectGetOwnPropertyDescriptors,45 ObjectGetPrototypeOf,46 ObjectIs,47 PromisePrototypeThen,48 PromiseReject,49 PromiseResolve,50 ReflectApply,51 ReflectDefineProperty,52 ReflectGetOwnPropertyDescriptor,53 ReflectOwnKeys,54 RegExpPrototypeTest,55 Set,56 // TODO(lucacasonato): add SharedArrayBuffer to primordials57 // SharedArrayBuffer,58 String,59 StringFromCodePoint,60 StringPrototypeCharCodeAt,61 StringPrototypeCodePointAt,62 Symbol,63 SymbolIterator,64 SymbolToStringTag,65 TypeError,66 Uint16Array,67 Uint32Array,68 Uint8Array,69 Uint8ClampedArray,70 } = window.__bootstrap.primordials;71 function makeException(ErrorType, message, opts = {}) {72 return new ErrorType(73 `${opts.prefix ? opts.prefix + ": " : ""}${74 opts.context ? opts.context : "Value"75 } ${message}`,76 );77 }78 function toNumber(value) {79 if (typeof value === "bigint") {80 throw TypeError("Cannot convert a BigInt value to a number");81 }82 return Number(value);83 }84 function type(V) {85 if (V === null) {86 return "Null";87 }88 switch (typeof V) {89 case "undefined":90 return "Undefined";91 case "boolean":92 return "Boolean";93 case "number":94 return "Number";95 case "string":96 return "String";97 case "symbol":98 return "Symbol";99 case "bigint":100 return "BigInt";101 case "object":102 // Falls through103 case "function":104 // Falls through105 default:106 // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for107 // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for108 // such cases. So treat the default case as an object.109 return "Object";110 }111 }112 // Round x to the nearest integer, choosing the even integer if it lies halfway between two.113 function evenRound(x) {114 // There are four cases for numbers with fractional part being .5:115 //116 // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example117 // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0118 // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2119 // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0120 // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2121 // (where n is a non-negative integer)122 //123 // Branch here for cases 1 and 4124 if (125 (x > 0 && x % 1 === +0.5 && (x & 1) === 0) ||126 (x < 0 && x % 1 === -0.5 && (x & 1) === 1)127 ) {128 return censorNegativeZero(MathFloor(x));129 }130 return censorNegativeZero(MathRound(x));131 }132 function integerPart(n) {133 return censorNegativeZero(MathTrunc(n));134 }135 function sign(x) {136 return x < 0 ? -1 : 1;137 }138 function modulo(x, y) {139 // https://tc39.github.io/ecma262/#eqn-modulo140 // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos141 const signMightNotMatch = x % y;142 if (sign(y) !== sign(signMightNotMatch)) {143 return signMightNotMatch + y;144 }145 return signMightNotMatch;146 }147 function censorNegativeZero(x) {148 return x === 0 ? 0 : x;149 }150 function createIntegerConversion(bitLength, typeOpts) {151 const isSigned = !typeOpts.unsigned;152 let lowerBound;153 let upperBound;154 if (bitLength === 64) {155 upperBound = NumberMAX_SAFE_INTEGER;156 lowerBound = !isSigned ? 0 : NumberMIN_SAFE_INTEGER;157 } else if (!isSigned) {158 lowerBound = 0;159 upperBound = MathPow(2, bitLength) - 1;160 } else {161 lowerBound = -MathPow(2, bitLength - 1);162 upperBound = MathPow(2, bitLength - 1) - 1;163 }164 const twoToTheBitLength = MathPow(2, bitLength);165 const twoToOneLessThanTheBitLength = MathPow(2, bitLength - 1);166 return (V, opts = {}) => {167 let x = toNumber(V, opts);168 x = censorNegativeZero(x);169 if (opts.enforceRange) {170 if (!NumberIsFinite(x)) {171 throw makeException(TypeError, "is not a finite number", opts);172 }173 x = integerPart(x);174 if (x < lowerBound || x > upperBound) {175 throw makeException(176 TypeError,177 `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,178 opts,179 );180 }181 return x;182 }183 if (!NumberIsNaN(x) && opts.clamp) {184 x = MathMin(MathMax(x, lowerBound), upperBound);185 x = evenRound(x);186 return x;187 }188 if (!NumberIsFinite(x) || x === 0) {189 return 0;190 }191 x = integerPart(x);192 // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if193 // possible. Hopefully it's an optimization for the non-64-bitLength cases too.194 if (x >= lowerBound && x <= upperBound) {195 return x;196 }197 // These will not work great for bitLength of 64, but oh well. See the README for more details.198 x = modulo(x, twoToTheBitLength);199 if (isSigned && x >= twoToOneLessThanTheBitLength) {200 return x - twoToTheBitLength;201 }202 return x;203 };204 }205 function createLongLongConversion(bitLength, { unsigned }) {206 const upperBound = NumberMAX_SAFE_INTEGER;207 const lowerBound = unsigned ? 0 : NumberMIN_SAFE_INTEGER;208 const asBigIntN = unsigned ? BigIntAsUintN : BigIntAsIntN;209 return (V, opts = {}) => {210 let x = toNumber(V, opts);211 x = censorNegativeZero(x);212 if (opts.enforceRange) {213 if (!NumberIsFinite(x)) {214 throw makeException(TypeError, "is not a finite number", opts);215 }216 x = integerPart(x);217 if (x < lowerBound || x > upperBound) {218 throw makeException(219 TypeError,220 `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,221 opts,222 );223 }224 return x;225 }226 if (!NumberIsNaN(x) && opts.clamp) {227 x = MathMin(MathMax(x, lowerBound), upperBound);228 x = evenRound(x);229 return x;230 }231 if (!NumberIsFinite(x) || x === 0) {232 return 0;233 }234 let xBigInt = BigInt(integerPart(x));235 xBigInt = asBigIntN(bitLength, xBigInt);236 return Number(xBigInt);237 };238 }239 const converters = [];240 converters.any = (V) => {241 return V;242 };243 converters.boolean = function (val) {244 return !!val;245 };246 converters.byte = createIntegerConversion(8, { unsigned: false });247 converters.octet = createIntegerConversion(8, { unsigned: true });248 converters.short = createIntegerConversion(16, { unsigned: false });249 converters["unsigned short"] = createIntegerConversion(16, {250 unsigned: true,251 });252 converters.long = createIntegerConversion(32, { unsigned: false });253 converters["unsigned long"] = createIntegerConversion(32, { unsigned: true });254 converters["long long"] = createLongLongConversion(64, { unsigned: false });255 converters["unsigned long long"] = createLongLongConversion(64, {256 unsigned: true,257 });258 converters.float = (V, opts) => {259 const x = toNumber(V, opts);260 if (!NumberIsFinite(x)) {261 throw makeException(262 TypeError,263 "is not a finite floating-point value",264 opts,265 );266 }267 if (ObjectIs(x, -0)) {268 return x;269 }270 const y = MathFround(x);271 if (!NumberIsFinite(y)) {272 throw makeException(273 TypeError,274 "is outside the range of a single-precision floating-point value",275 opts,276 );277 }278 return y;279 };280 converters["unrestricted float"] = (V, opts) => {281 const x = toNumber(V, opts);282 if (isNaN(x)) {283 return x;284 }285 if (ObjectIs(x, -0)) {286 return x;287 }288 return MathFround(x);289 };290 converters.double = (V, opts) => {291 const x = toNumber(V, opts);292 if (!NumberIsFinite(x)) {293 throw makeException(294 TypeError,295 "is not a finite floating-point value",296 opts,297 );298 }299 return x;300 };301 converters["unrestricted double"] = (V, opts) => {302 const x = toNumber(V, opts);303 return x;304 };305 converters.DOMString = function (V, opts = {}) {306 if (opts.treatNullAsEmptyString && V === null) {307 return "";308 }309 if (typeof V === "symbol") {310 throw makeException(311 TypeError,312 "is a symbol, which cannot be converted to a string",313 opts,314 );315 }316 return String(V);317 };318 converters.ByteString = (V, opts) => {319 const x = converters.DOMString(V, opts);320 let c;321 for (let i = 0; (c = StringPrototypeCodePointAt(x, i)) !== undefined; ++i) {322 if (c > 255) {323 throw makeException(TypeError, "is not a valid ByteString", opts);324 }325 }326 return x;327 };328 converters.USVString = (V, opts) => {329 const S = converters.DOMString(V, opts);330 const n = S.length;331 let U = "";332 for (let i = 0; i < n; ++i) {333 const c = StringPrototypeCharCodeAt(S, i);334 if (c < 0xd800 || c > 0xdfff) {335 U += StringFromCodePoint(c);336 } else if (0xdc00 <= c && c <= 0xdfff) {337 U += StringFromCodePoint(0xfffd);338 } else if (i === n - 1) {339 U += StringFromCodePoint(0xfffd);340 } else {341 const d = StringPrototypeCharCodeAt(S, i + 1);342 if (0xdc00 <= d && d <= 0xdfff) {343 const a = c & 0x3ff;344 const b = d & 0x3ff;345 U += StringFromCodePoint((2 << 15) + (2 << 9) * a + b);346 ++i;347 } else {348 U += StringFromCodePoint(0xfffd);349 }350 }351 }352 return U;353 };354 converters.object = (V, opts) => {355 if (type(V) !== "Object") {356 throw makeException(TypeError, "is not an object", opts);357 }358 return V;359 };360 // Not exported, but used in Function and VoidFunction.361 // Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so362 // handling for that is omitted.363 function convertCallbackFunction(V, opts) {364 if (typeof V !== "function") {365 throw makeException(TypeError, "is not a function", opts);366 }367 return V;368 }369 function isNonSharedArrayBuffer(V) {370 return V instanceof ArrayBuffer;371 }372 function isSharedArrayBuffer(V) {373 return V instanceof SharedArrayBuffer;374 }375 function isArrayBufferDetached(V) {376 try {377 new Uint8Array(V);378 return false;379 } catch {380 return true;381 }382 }383 converters.ArrayBuffer = (V, opts = {}) => {384 if (!isNonSharedArrayBuffer(V)) {385 if (opts.allowShared && !isSharedArrayBuffer(V)) {386 throw makeException(387 TypeError,388 "is not an ArrayBuffer or SharedArrayBuffer",389 opts,390 );391 }392 throw makeException(TypeError, "is not an ArrayBuffer", opts);393 }394 if (isArrayBufferDetached(V)) {395 throw makeException(TypeError, "is a detached ArrayBuffer", opts);396 }397 return V;398 };399 converters.DataView = (V, opts = {}) => {400 if (!(V instanceof DataView)) {401 throw makeException(TypeError, "is not a DataView", opts);402 }403 if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {404 throw makeException(405 TypeError,406 "is backed by a SharedArrayBuffer, which is not allowed",407 opts,408 );409 }410 if (isArrayBufferDetached(V.buffer)) {411 throw makeException(412 TypeError,413 "is backed by a detached ArrayBuffer",414 opts,415 );416 }417 return V;418 };419 // Returns the unforgeable `TypedArray` constructor name or `undefined`,420 // if the `this` value isn't a valid `TypedArray` object.421 //422 // https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag423 const typedArrayNameGetter = ObjectGetOwnPropertyDescriptor(424 ObjectGetPrototypeOf(Uint8Array).prototype,425 SymbolToStringTag,426 ).get;427 ArrayPrototypeForEach(428 [429 Int8Array,430 Int16Array,431 Int32Array,432 Uint8Array,433 Uint16Array,434 Uint32Array,435 Uint8ClampedArray,436 Float32Array,437 Float64Array,438 ],439 (func) => {440 const name = func.name;441 const article = RegExpPrototypeTest(/^[AEIOU]/, name) ? "an" : "a";442 converters[name] = (V, opts = {}) => {443 if (!ArrayBufferIsView(V) || typedArrayNameGetter.call(V) !== name) {444 throw makeException(445 TypeError,446 `is not ${article} ${name} object`,447 opts,448 );449 }450 if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {451 throw makeException(452 TypeError,453 "is a view on a SharedArrayBuffer, which is not allowed",454 opts,455 );456 }457 if (isArrayBufferDetached(V.buffer)) {458 throw makeException(459 TypeError,460 "is a view on a detached ArrayBuffer",461 opts,462 );463 }464 return V;465 };466 },467 );468 // Common definitions469 converters.ArrayBufferView = (V, opts = {}) => {470 if (!ArrayBufferIsView(V)) {471 throw makeException(472 TypeError,473 "is not a view on an ArrayBuffer or SharedArrayBuffer",474 opts,475 );476 }477 if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {478 throw makeException(479 TypeError,480 "is a view on a SharedArrayBuffer, which is not allowed",481 opts,482 );483 }484 if (isArrayBufferDetached(V.buffer)) {485 throw makeException(486 TypeError,487 "is a view on a detached ArrayBuffer",488 opts,489 );490 }491 return V;492 };493 converters.BufferSource = (V, opts = {}) => {494 if (ArrayBufferIsView(V)) {495 if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {496 throw makeException(497 TypeError,498 "is a view on a SharedArrayBuffer, which is not allowed",499 opts,500 );501 }502 if (isArrayBufferDetached(V.buffer)) {503 throw makeException(504 TypeError,505 "is a view on a detached ArrayBuffer",506 opts,507 );508 }509 return V;510 }511 if (!opts.allowShared && !isNonSharedArrayBuffer(V)) {512 throw makeException(513 TypeError,514 "is not an ArrayBuffer or a view on one",515 opts,516 );517 }518 if (519 opts.allowShared &&520 !isSharedArrayBuffer(V) &&521 !isNonSharedArrayBuffer(V)522 ) {523 throw makeException(524 TypeError,525 "is not an ArrayBuffer, SharedArrayBuffer, or a view on one",526 opts,527 );528 }529 if (isArrayBufferDetached(V)) {530 throw makeException(TypeError, "is a detached ArrayBuffer", opts);531 }532 return V;533 };534 converters.DOMTimeStamp = converters["unsigned long long"];535 converters.DOMHighResTimeStamp = converters["double"];536 converters.Function = convertCallbackFunction;537 converters.VoidFunction = convertCallbackFunction;538 converters["UVString?"] = createNullableConverter(539 converters.USVString,540 );541 converters["sequence<double>"] = createSequenceConverter(542 converters.double,543 );544 converters["sequence<object>"] = createSequenceConverter(545 converters.object,546 );547 converters["Promise<undefined>"] = createPromiseConverter(() => undefined);548 converters["sequence<ByteString>"] = createSequenceConverter(549 converters.ByteString,550 );551 converters["sequence<sequence<ByteString>>"] = createSequenceConverter(552 converters["sequence<ByteString>"],553 );554 converters["record<ByteString, ByteString>"] = createRecordConverter(555 converters.ByteString,556 converters.ByteString,557 );558 converters["sequence<USVString>"] = createSequenceConverter(559 converters.USVString,560 );561 converters["sequence<sequence<USVString>>"] = createSequenceConverter(562 converters["sequence<USVString>"],563 );564 converters["record<USVString, USVString>"] = createRecordConverter(565 converters.USVString,566 converters.USVString,567 );568 converters["sequence<DOMString>"] = createSequenceConverter(569 converters.DOMString,570 );571 function requiredArguments(length, required, opts = {}) {572 if (length < required) {573 const errMsg = `${574 opts.prefix ? opts.prefix + ": " : ""575 }${required} argument${576 required === 1 ? "" : "s"577 } required, but only ${length} present.`;578 throw new TypeError(errMsg);579 }580 }581 function createDictionaryConverter(name, ...dictionaries) {582 let hasRequiredKey = false;583 const allMembers = [];584 for (const members of dictionaries) {585 for (const member of members) {586 if (member.required) {587 hasRequiredKey = true;588 }589 ArrayPrototypePush(allMembers, member);590 }591 }592 ArrayPrototypeSort(allMembers, (a, b) => {593 if (a.key == b.key) {594 return 0;595 }596 return a.key < b.key ? -1 : 1;597 });598 const defaultValues = {};599 for (const member of allMembers) {600 if ("defaultValue" in member) {601 const idlMemberValue = member.defaultValue;602 const imvType = typeof idlMemberValue;603 // Copy by value types can be directly assigned, copy by reference types604 // need to be re-created for each allocation.605 if (606 imvType === "number" || imvType === "boolean" ||607 imvType === "string" || imvType === "bigint" ||608 imvType === "undefined"609 ) {610 defaultValues[member.key] = idlMemberValue;611 } else {612 ObjectDefineProperty(defaultValues, member.key, {613 get() {614 return member.defaultValue;615 },616 enumerable: true,617 });618 }619 }620 }621 return function (V, opts = {}) {622 const typeV = type(V);623 switch (typeV) {624 case "Undefined":625 case "Null":626 case "Object":627 break;628 default:629 throw makeException(630 TypeError,631 "can not be converted to a dictionary",632 opts,633 );634 }635 const esDict = V;636 const idlDict = { ...defaultValues };637 // NOTE: fast path Null and Undefined.638 if ((V === undefined || V === null) && !hasRequiredKey) {639 return idlDict;640 }641 for (const member of allMembers) {642 const key = member.key;643 let esMemberValue;644 if (typeV === "Undefined" || typeV === "Null") {645 esMemberValue = undefined;646 } else {647 esMemberValue = esDict[key];648 }649 if (esMemberValue !== undefined) {650 const context = `'${key}' of '${name}'${651 opts.context ? ` (${opts.context})` : ""652 }`;653 const converter = member.converter;654 const idlMemberValue = converter(esMemberValue, { ...opts, context });655 idlDict[key] = idlMemberValue;656 } else if (member.required) {657 throw makeException(658 TypeError,659 `can not be converted to '${name}' because '${key}' is required in '${name}'.`,660 { ...opts },661 );662 }663 }664 return idlDict;665 };666 }667 // https://heycam.github.io/webidl/#es-enumeration668 function createEnumConverter(name, values) {669 const E = new Set(values);670 return function (V, opts = {}) {671 const S = String(V);672 if (!E.has(S)) {673 throw new TypeError(674 `${675 opts.prefix ? opts.prefix + ": " : ""676 }The provided value '${S}' is not a valid enum value of type ${name}.`,677 );678 }679 return S;680 };681 }682 function createNullableConverter(converter) {683 return (V, opts = {}) => {684 // FIXME: If Type(V) is not Object, and the conversion to an IDL value is685 // being performed due to V being assigned to an attribute whose type is a686 // nullable callback function that is annotated with687 // [LegacyTreatNonObjectAsNull], then return the IDL nullable type T?688 // value null.689 if (V === null || V === undefined) return null;690 return converter(V, opts);691 };692 }693 // https://heycam.github.io/webidl/#es-sequence694 function createSequenceConverter(converter) {695 return function (V, opts = {}) {696 if (type(V) !== "Object") {697 throw makeException(698 TypeError,699 "can not be converted to sequence.",700 opts,701 );702 }703 const iter = V?.[SymbolIterator]?.();704 if (iter === undefined) {705 throw makeException(706 TypeError,707 "can not be converted to sequence.",708 opts,709 );710 }711 const array = [];712 while (true) {713 const res = iter?.next?.();714 if (res === undefined) {715 throw makeException(716 TypeError,717 "can not be converted to sequence.",718 opts,719 );720 }721 if (res.done === true) break;722 const val = converter(res.value, {723 ...opts,724 context: `${opts.context}, index ${array.length}`,725 });726 ArrayPrototypePush(array, val);727 }728 return array;729 };730 }731 function createRecordConverter(keyConverter, valueConverter) {732 return (V, opts) => {733 if (type(V) !== "Object") {734 throw makeException(735 TypeError,736 "can not be converted to dictionary.",737 opts,738 );739 }740 const keys = ReflectOwnKeys(V);741 const result = {};742 for (const key of keys) {743 const desc = ObjectGetOwnPropertyDescriptor(V, key);744 if (desc !== undefined && desc.enumerable === true) {745 const typedKey = keyConverter(key, opts);746 const value = V[key];747 const typedValue = valueConverter(value, opts);748 result[typedKey] = typedValue;749 }750 }751 return result;752 };753 }754 function createPromiseConverter(converter) {755 return (V, opts) =>756 PromisePrototypeThen(PromiseResolve(V), (V) => converter(V, opts));757 }758 function invokeCallbackFunction(759 callable,760 args,761 thisArg,762 returnValueConverter,763 opts,764 ) {765 try {766 const rv = ReflectApply(callable, thisArg, args);767 return returnValueConverter(rv, {768 prefix: opts.prefix,769 context: "return value",770 });771 } catch (err) {772 if (opts.returnsPromise === true) {773 return PromiseReject(err);774 }775 throw err;776 }777 }778 const brand = Symbol("[[webidl.brand]]");779 function createInterfaceConverter(name, prototype) {780 return (V, opts) => {781 if (!(V instanceof prototype) || V[brand] !== brand) {782 throw makeException(TypeError, `is not of type ${name}.`, opts);783 }784 return V;785 };786 }787 // TODO(lucacasonato): have the user pass in the prototype, and not the type.788 function createBranded(Type) {789 const t = ObjectCreate(Type.prototype);790 t[brand] = brand;791 return t;792 }793 function assertBranded(self, prototype) {794 if (!(self instanceof prototype) || self[brand] !== brand) {795 throw new TypeError("Illegal invocation");796 }797 }798 function illegalConstructor() {799 throw new TypeError("Illegal constructor");800 }801 function define(target, source) {802 for (const key of ReflectOwnKeys(source)) {803 const descriptor = ReflectGetOwnPropertyDescriptor(source, key);804 if (descriptor && !ReflectDefineProperty(target, key, descriptor)) {805 throw new TypeError(`Cannot redefine property: ${String(key)}`);806 }807 }808 }809 const _iteratorInternal = Symbol("iterator internal");810 const globalIteratorPrototype = ObjectGetPrototypeOf(ArrayIteratorPrototype);811 function mixinPairIterable(name, prototype, dataSymbol, keyKey, valueKey) {812 const iteratorPrototype = ObjectCreate(globalIteratorPrototype, {813 [SymbolToStringTag]: { configurable: true, value: `${name} Iterator` },814 });815 define(iteratorPrototype, {816 next() {817 const internal = this && this[_iteratorInternal];818 if (!internal) {819 throw new TypeError(820 `next() called on a value that is not a ${name} iterator object`,821 );822 }823 const { target, kind, index } = internal;824 const values = target[dataSymbol];825 const len = values.length;826 if (index >= len) {827 return { value: undefined, done: true };828 }829 const pair = values[index];830 internal.index = index + 1;831 let result;832 switch (kind) {833 case "key":834 result = pair[keyKey];835 break;836 case "value":837 result = pair[valueKey];838 break;839 case "key+value":840 result = [pair[keyKey], pair[valueKey]];841 break;842 }843 return { value: result, done: false };844 },845 });846 function createDefaultIterator(target, kind) {847 const iterator = ObjectCreate(iteratorPrototype);848 ObjectDefineProperty(iterator, _iteratorInternal, {849 value: { target, kind, index: 0 },850 configurable: true,851 });852 return iterator;853 }854 function entries() {855 assertBranded(this, prototype);856 return createDefaultIterator(this, "key+value");857 }858 const properties = {859 entries: {860 value: entries,861 writable: true,862 enumerable: true,863 configurable: true,864 },865 [SymbolIterator]: {866 value: entries,867 writable: true,868 enumerable: false,869 configurable: true,870 },871 keys: {872 value: function keys() {873 assertBranded(this, prototype);874 return createDefaultIterator(this, "key");875 },876 writable: true,877 enumerable: true,878 configurable: true,879 },880 values: {881 value: function values() {882 assertBranded(this, prototype);883 return createDefaultIterator(this, "value");884 },885 writable: true,886 enumerable: true,887 configurable: true,888 },889 forEach: {890 value: function forEach(idlCallback, thisArg = undefined) {891 assertBranded(this, prototype);892 const prefix = `Failed to execute 'forEach' on '${name}'`;893 requiredArguments(arguments.length, 1, { prefix });894 idlCallback = converters["Function"](idlCallback, {895 prefix,896 context: "Argument 1",897 });898 idlCallback = FunctionPrototypeBind(899 idlCallback,900 thisArg ?? globalThis,901 );902 const pairs = this[dataSymbol];903 for (let i = 0; i < pairs.length; i++) {904 const entry = pairs[i];905 idlCallback(entry[valueKey], entry[keyKey], this);906 }907 },908 writable: true,909 enumerable: true,910 configurable: true,911 },912 };913 return ObjectDefineProperties(prototype.prototype, properties);914 }915 function configurePrototype(prototype) {916 const descriptors = ObjectGetOwnPropertyDescriptors(prototype.prototype);917 for (const key in descriptors) {918 if (key === "constructor") continue;919 const descriptor = descriptors[key];920 if ("value" in descriptor && typeof descriptor.value === "function") {921 ObjectDefineProperty(prototype.prototype, key, {922 enumerable: true,923 writable: true,924 configurable: true,925 });926 } else if ("get" in descriptor) {927 ObjectDefineProperty(prototype.prototype, key, {928 enumerable: true,929 configurable: true,930 });931 }932 }933 }934 window.__bootstrap ??= {};935 window.__bootstrap.webidl = {936 type,937 makeException,938 converters,939 requiredArguments,940 createDictionaryConverter,941 createEnumConverter,942 createNullableConverter,943 createSequenceConverter,944 createRecordConverter,945 createPromiseConverter,946 invokeCallbackFunction,947 createInterfaceConverter,948 brand,949 createBranded,950 assertBranded,951 illegalConstructor,952 mixinPairIterable,953 configurePrototype,954 };...
Using AI Code Generation
1function testIdlCallback(obj) {2 return obj;3}4function testIdlInterface(obj) {5 return obj;6}7function testIdlArray(obj) {8 return obj;9}10function testIdlObject(obj) {11 return obj;12}13function testIdlAny(obj) {14 return obj;15}16function testIdlUnion(obj) {17 return obj;18}19function testIdlEnum(obj) {20 return obj;21}22function testIdlTypedef(obj) {23 return obj;24}25function testIdlDictionary(obj) {26 return obj;27}28function testIdlInterfaceWithMembers(obj) {29 return obj;30}31function testIdlInterfaceWithConstants(obj) {32 return obj;33}34function testIdlInterfaceWithStaticMethods(obj) {35 return obj;36}37function testIdlInterfaceWithStaticAttributes(obj) {38 return obj;39}40function testIdlInterfaceWithAttributes(obj) {41 return obj;42}43function testIdlInterfaceWithMethods(obj) {44 return obj;45}46function testIdlInterfaceWithInheritedAttributes(obj) {47 return obj;48}49function testIdlInterfaceWithInheritedMethods(obj) {50 return obj;51}
Using AI Code Generation
1function IdlCallback() {2 return {3 "response": {4 "headers": {5 },6 }7 };8}9function IdlCallbackWithProperties() {10 return {11 "response": {12 "headers": {13 },14 }15 };16}17function IdlCallbackWithPropertiesAndCallback() {18 return {19 "response": {20 "headers": {21 },22 }23 };24}25function IdlCallbackWithPropertiesAndCallbackAndException() {26 return {27 "response": {28 "headers": {29 },30 }31 };32}33function IdlCallbackWithPropertiesAndCallbackAndExceptionAndException() {34 return {35 "response": {36 "headers": {37 },38 }39 };40}41function IdlCallbackWithPropertiesAndCallbackAndExceptionAndExceptionAndException() {
Using AI Code Generation
1function run_test() {2 var idl_array = new IdlArray();3 idl_array.add_objects({4 HTMLIFrameElement: ["document.createElement('iframe')"],5 HTMLAnchorElement: ["document.createElement('a')"],6 HTMLAreaElement: ["document.createElement('area')"],7 HTMLAudioElement: ["document.createElement('audio')"],8 HTMLVideoElement: ["document.createElement('video')"],9 HTMLButtonElement: ["document.createElement('button')"],10 HTMLCanvasElement: ["document.createElement('canvas')"],11 HTMLDataListElement: ["document.createElement('datalist')"],12 HTMLDetailsElement: ["document.createElement('details')"],13 HTMLDialogElement: ["document.createElement('dialog')"],14 HTMLDivElement: ["document.createElement('div')"],15 HTMLFieldSetElement: ["document.createElement('fieldset')"],16 HTMLFormElement: ["document.createElement('form')"],17 HTMLHRElement: ["document.createElement('hr')"],18 HTMLHeadElement: ["document.createElement('head')"],19 HTMLHeadingElement: ["document.createElement('h1')"],20 HTMLHtmlElement: ["document.createElement('html')"],21 HTMLImageElement: ["document.createElement('img')"],22 HTMLInputElement: ["document.createElement('input')"],23 HTMLLabelElement: ["document.createElement('label')"],24 HTMLLegendElement: ["document.createElement('legend')"],25 HTMLLIElement: ["document.createElement('li')"],26 HTMLLinkElement: ["document.createElement('link')"],27 HTMLMapElement: ["document.createElement('map')"],28 HTMLMetaElement: ["document.createElement('meta')"],29 HTMLMeterElement: ["document.createElement('meter')"],30 HTMLModElement: ["document.createElement('del')"],31 HTMLOListElement: ["document.createElement('ol')"],32 HTMLObjectElement: ["document.createElement('object')"],33 HTMLOptGroupElement: ["document.createElement('optgroup')"],34 HTMLOptionElement: ["document.createElement('option')"],35 HTMLOutputElement: ["document.createElement('output')"],36 HTMLParagraphElement: ["document.createElement('p')"],37 HTMLParamElement: ["document.createElement('param')"],38 HTMLPreElement: ["document.createElement('pre')"],39 HTMLProgressElement: ["document.createElement('progress')"],40 HTMLQuoteElement: ["document.createElement('
Using AI Code Generation
1function IdlCallback() {2 return {3 {4 interface Test {5 string foo();6 };7 },8 };9}10function IdlCallback() {11 return {12 {13 interface Test2 {14 string foo();15 };16 },17 };18}19function IdlCallback() {20 return {21 {22 interface Test2 {23 string foo();24 };25 },26 };27}28function IdlCallback() {29 return {30 {31 interface Test3 {32 string foo();33 };34 },35 };36}37function IdlCallback() {38 return {39 {40 interface Test4 {41 string foo();42 };43 },44 };45}46function IdlCallback() {47 return {48 {49 interface Test5 {50 string foo();51 };52 },53 };54}55function IdlCallback() {56 return {57 {58 interface Test6 {59 string foo();60 };61 },62 };63}64function IdlCallback() {65 return {66 {67 interface Test7 {68 string foo();69 };70 },71 };72}
Using AI Code Generation
1var wptserve = require('wptserve');2function handleRequest(request, response) {3 response.setHeader('Access-Control-Allow-Origin', '*');4 response.setHeader('Access-Control-Allow-Credentials', 'true');5 response.setHeader('Content-Type', 'text/plain');6 response.setHeader('Access-Control-Allow-Methods', 'GET');7 response.setHeader('Access-Control-Allow-Headers', 'content-type');8 response.setHeader('Access-Control-Max-Age', '86400');9 response.setHeader('Access-Control-Expose-Headers', 'X-Custom-Header');10 response.setHeader('X-Custom-Header', '42');11 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header');12 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-2');13 response.setHeader('X-Custom-Header-2', '42');14 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-3');15 response.setHeader('X-Custom-Header-3', '42');16 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-4');17 response.setHeader('X-Custom-Header-4', '42');18 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-5');19 response.setHeader('X-Custom-Header-5', '42');20 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-6');21 response.setHeader('X-Custom-Header-6', '42');22 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-7');23 response.setHeader('X-Custom-Header-7', '42');24 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-8');25 response.setHeader('X-Custom-Header-8', '42');26 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-9');27 response.setHeader('X-Custom-Header-9', '42');28 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-10');29 response.setHeader('X-Custom-Header-10', '42');30 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header-11');31 response.setHeader('X-Custom-Header-11', '42');32 response.setHeader('Access-Control-Allow-Headers', 'X-Custom-Header
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!!