// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// Adapted from https://github.com/jsdom/webidl-conversions.
// Copyright Domenic Denicola. Licensed under BSD-2-Clause License.
// Original license at https://github.com/jsdom/webidl-conversions/blob/master/LICENSE.md.
///
const core = globalThis.Deno.core;
const primordials = globalThis.__bootstrap.primordials;
const {
ArrayBufferPrototype,
ArrayBufferIsView,
ArrayPrototypeForEach,
ArrayPrototypePush,
ArrayPrototypeSort,
ArrayIteratorPrototype,
BigInt,
BigIntAsIntN,
BigIntAsUintN,
DataViewPrototypeGetBuffer,
Float32Array,
Float64Array,
FunctionPrototypeBind,
Int16Array,
Int32Array,
Int8Array,
isNaN,
MathFloor,
MathFround,
MathMax,
MathMin,
MathPow,
MathRound,
MathTrunc,
Number,
NumberIsFinite,
NumberIsNaN,
// deno-lint-ignore camelcase
NumberMAX_SAFE_INTEGER,
// deno-lint-ignore camelcase
NumberMIN_SAFE_INTEGER,
ObjectAssign,
ObjectCreate,
ObjectDefineProperties,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
ObjectGetOwnPropertyDescriptors,
ObjectGetPrototypeOf,
ObjectPrototypeHasOwnProperty,
ObjectPrototypeIsPrototypeOf,
ObjectIs,
PromisePrototypeThen,
PromiseReject,
PromiseResolve,
ReflectApply,
ReflectDefineProperty,
ReflectGetOwnPropertyDescriptor,
ReflectHas,
ReflectOwnKeys,
RegExpPrototypeTest,
SafeRegExp,
SafeSet,
SetPrototypeEntries,
SetPrototypeForEach,
SetPrototypeKeys,
SetPrototypeValues,
SetPrototypeHas,
SetPrototypeClear,
SetPrototypeDelete,
SetPrototypeAdd,
// TODO(lucacasonato): add SharedArrayBuffer to primordials
// SharedArrayBufferPrototype
String,
StringFromCodePoint,
StringPrototypeCharCodeAt,
Symbol,
SymbolIterator,
SymbolToStringTag,
TypedArrayPrototypeGetBuffer,
TypedArrayPrototypeGetSymbolToStringTag,
TypeError,
Uint16Array,
Uint32Array,
Uint8Array,
Uint8ClampedArray,
} = primordials;
function makeException(ErrorType, message, prefix, context) {
return new ErrorType(
`${prefix ? prefix + ": " : ""}${context ? context : "Value"} ${message}`,
);
}
function toNumber(value) {
if (typeof value === "bigint") {
throw TypeError("Cannot convert a BigInt value to a number");
}
return Number(value);
}
function type(V) {
if (V === null) {
return "Null";
}
switch (typeof V) {
case "undefined":
return "Undefined";
case "boolean":
return "Boolean";
case "number":
return "Number";
case "string":
return "String";
case "symbol":
return "Symbol";
case "bigint":
return "BigInt";
case "object":
// Falls through
case "function":
// Falls through
default:
// Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for
// uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for
// such cases. So treat the default case as an object.
return "Object";
}
}
// Round x to the nearest integer, choosing the even integer if it lies halfway between two.
function evenRound(x) {
// There are four cases for numbers with fractional part being .5:
//
// case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example
// 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0
// 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2
// 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0
// 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2
// (where n is a non-negative integer)
//
// Branch here for cases 1 and 4
if (
(x > 0 && x % 1 === +0.5 && (x & 1) === 0) ||
(x < 0 && x % 1 === -0.5 && (x & 1) === 1)
) {
return censorNegativeZero(MathFloor(x));
}
return censorNegativeZero(MathRound(x));
}
function integerPart(n) {
return censorNegativeZero(MathTrunc(n));
}
function sign(x) {
return x < 0 ? -1 : 1;
}
function modulo(x, y) {
// https://tc39.github.io/ecma262/#eqn-modulo
// Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos
const signMightNotMatch = x % y;
if (sign(y) !== sign(signMightNotMatch)) {
return signMightNotMatch + y;
}
return signMightNotMatch;
}
function censorNegativeZero(x) {
return x === 0 ? 0 : x;
}
function createIntegerConversion(bitLength, typeOpts) {
const isSigned = !typeOpts.unsigned;
let lowerBound;
let upperBound;
if (bitLength === 64) {
upperBound = NumberMAX_SAFE_INTEGER;
lowerBound = !isSigned ? 0 : NumberMIN_SAFE_INTEGER;
} else if (!isSigned) {
lowerBound = 0;
upperBound = MathPow(2, bitLength) - 1;
} else {
lowerBound = -MathPow(2, bitLength - 1);
upperBound = MathPow(2, bitLength - 1) - 1;
}
const twoToTheBitLength = MathPow(2, bitLength);
const twoToOneLessThanTheBitLength = MathPow(2, bitLength - 1);
return (V, opts = {}) => {
let x = toNumber(V);
x = censorNegativeZero(x);
if (opts.enforceRange) {
if (!NumberIsFinite(x)) {
throw makeException(
TypeError,
"is not a finite number",
opts.prefix,
opts.context,
);
}
x = integerPart(x);
if (x < lowerBound || x > upperBound) {
throw makeException(
TypeError,
`is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,
opts.prefix,
opts.context,
);
}
return x;
}
if (!NumberIsNaN(x) && opts.clamp) {
x = MathMin(MathMax(x, lowerBound), upperBound);
x = evenRound(x);
return x;
}
if (!NumberIsFinite(x) || x === 0) {
return 0;
}
x = integerPart(x);
// Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if
// possible. Hopefully it's an optimization for the non-64-bitLength cases too.
if (x >= lowerBound && x <= upperBound) {
return x;
}
// These will not work great for bitLength of 64, but oh well. See the README for more details.
x = modulo(x, twoToTheBitLength);
if (isSigned && x >= twoToOneLessThanTheBitLength) {
return x - twoToTheBitLength;
}
return x;
};
}
function createLongLongConversion(bitLength, { unsigned }) {
const upperBound = NumberMAX_SAFE_INTEGER;
const lowerBound = unsigned ? 0 : NumberMIN_SAFE_INTEGER;
const asBigIntN = unsigned ? BigIntAsUintN : BigIntAsIntN;
return (V, opts = {}) => {
let x = toNumber(V);
x = censorNegativeZero(x);
if (opts.enforceRange) {
if (!NumberIsFinite(x)) {
throw makeException(
TypeError,
"is not a finite number",
opts.prefix,
opts.context,
);
}
x = integerPart(x);
if (x < lowerBound || x > upperBound) {
throw makeException(
TypeError,
`is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,
opts.prefix,
opts.context,
);
}
return x;
}
if (!NumberIsNaN(x) && opts.clamp) {
x = MathMin(MathMax(x, lowerBound), upperBound);
x = evenRound(x);
return x;
}
if (!NumberIsFinite(x) || x === 0) {
return 0;
}
let xBigInt = BigInt(integerPart(x));
xBigInt = asBigIntN(bitLength, xBigInt);
return Number(xBigInt);
};
}
const converters = [];
converters.any = (V) => {
return V;
};
converters.boolean = function (val) {
return !!val;
};
converters.byte = createIntegerConversion(8, { unsigned: false });
converters.octet = createIntegerConversion(8, { unsigned: true });
converters.short = createIntegerConversion(16, { unsigned: false });
converters["unsigned short"] = createIntegerConversion(16, {
unsigned: true,
});
converters.long = createIntegerConversion(32, { unsigned: false });
converters["unsigned long"] = createIntegerConversion(32, { unsigned: true });
converters["long long"] = createLongLongConversion(64, { unsigned: false });
converters["unsigned long long"] = createLongLongConversion(64, {
unsigned: true,
});
converters.float = (V, opts) => {
const x = toNumber(V);
if (!NumberIsFinite(x)) {
throw makeException(
TypeError,
"is not a finite floating-point value",
opts.prefix,
opts.context,
);
}
if (ObjectIs(x, -0)) {
return x;
}
const y = MathFround(x);
if (!NumberIsFinite(y)) {
throw makeException(
TypeError,
"is outside the range of a single-precision floating-point value",
opts.prefix,
opts.context,
);
}
return y;
};
converters["unrestricted float"] = (V, _opts) => {
const x = toNumber(V);
if (isNaN(x)) {
return x;
}
if (ObjectIs(x, -0)) {
return x;
}
return MathFround(x);
};
converters.double = (V, opts) => {
const x = toNumber(V);
if (!NumberIsFinite(x)) {
throw makeException(
TypeError,
"is not a finite floating-point value",
opts.prefix,
opts.context,
);
}
return x;
};
converters["unrestricted double"] = (V, _opts) => {
const x = toNumber(V);
return x;
};
converters.DOMString = function (V, opts = {}) {
if (typeof V === "string") {
return V;
} else if (V === null && opts.treatNullAsEmptyString) {
return "";
} else if (typeof V === "symbol") {
throw makeException(
TypeError,
"is a symbol, which cannot be converted to a string",
opts.prefix,
opts.context,
);
}
return String(V);
};
// deno-lint-ignore no-control-regex
const IS_BYTE_STRING = new SafeRegExp(/^[\x00-\xFF]*$/);
converters.ByteString = (V, opts) => {
const x = converters.DOMString(V, opts);
if (!RegExpPrototypeTest(IS_BYTE_STRING, x)) {
throw makeException(
TypeError,
"is not a valid ByteString",
opts.prefix,
opts.context,
);
}
return x;
};
converters.USVString = (V, opts) => {
const S = converters.DOMString(V, opts);
const n = S.length;
let U = "";
for (let i = 0; i < n; ++i) {
const c = StringPrototypeCharCodeAt(S, i);
if (c < 0xd800 || c > 0xdfff) {
U += StringFromCodePoint(c);
} else if (0xdc00 <= c && c <= 0xdfff) {
U += StringFromCodePoint(0xfffd);
} else if (i === n - 1) {
U += StringFromCodePoint(0xfffd);
} else {
const d = StringPrototypeCharCodeAt(S, i + 1);
if (0xdc00 <= d && d <= 0xdfff) {
const a = c & 0x3ff;
const b = d & 0x3ff;
U += StringFromCodePoint((2 << 15) + (2 << 9) * a + b);
++i;
} else {
U += StringFromCodePoint(0xfffd);
}
}
}
return U;
};
converters.object = (V, opts) => {
if (type(V) !== "Object") {
throw makeException(
TypeError,
"is not an object",
opts.prefix,
opts.context,
);
}
return V;
};
// Not exported, but used in Function and VoidFunction.
// Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so
// handling for that is omitted.
function convertCallbackFunction(V, opts) {
if (typeof V !== "function") {
throw makeException(
TypeError,
"is not a function",
opts.prefix,
opts.context,
);
}
return V;
}
function isDataView(V) {
return ArrayBufferIsView(V) &&
TypedArrayPrototypeGetSymbolToStringTag(V) === undefined;
}
function isNonSharedArrayBuffer(V) {
return ObjectPrototypeIsPrototypeOf(ArrayBufferPrototype, V);
}
function isSharedArrayBuffer(V) {
// deno-lint-ignore prefer-primordials
return ObjectPrototypeIsPrototypeOf(SharedArrayBuffer.prototype, V);
}
converters.ArrayBuffer = (V, opts = {}) => {
if (!isNonSharedArrayBuffer(V)) {
if (opts.allowShared && !isSharedArrayBuffer(V)) {
throw makeException(
TypeError,
"is not an ArrayBuffer or SharedArrayBuffer",
opts.prefix,
opts.context,
);
}
throw makeException(
TypeError,
"is not an ArrayBuffer",
opts.prefix,
opts.context,
);
}
return V;
};
converters.DataView = (V, opts = {}) => {
if (!isDataView(V)) {
throw makeException(
TypeError,
"is not a DataView",
opts.prefix,
opts.context,
);
}
if (!opts.allowShared && isSharedArrayBuffer(DataViewPrototypeGetBuffer(V))) {
throw makeException(
TypeError,
"is backed by a SharedArrayBuffer, which is not allowed",
opts.prefix,
opts.context,
);
}
return V;
};
ArrayPrototypeForEach(
[
Int8Array,
Int16Array,
Int32Array,
Uint8Array,
Uint16Array,
Uint32Array,
Uint8ClampedArray,
Float32Array,
Float64Array,
],
(func) => {
const name = func.name;
const article = RegExpPrototypeTest(new SafeRegExp(/^[AEIOU]/), name)
? "an"
: "a";
converters[name] = (V, opts = {}) => {
if (TypedArrayPrototypeGetSymbolToStringTag(V) !== name) {
throw makeException(
TypeError,
`is not ${article} ${name} object`,
opts.prefix,
opts.context,
);
}
if (
!opts.allowShared &&
isSharedArrayBuffer(TypedArrayPrototypeGetBuffer(V))
) {
throw makeException(
TypeError,
"is a view on a SharedArrayBuffer, which is not allowed",
opts.prefix,
opts.context,
);
}
return V;
};
},
);
// Common definitions
converters.ArrayBufferView = (V, opts = {}) => {
if (!ArrayBufferIsView(V)) {
throw makeException(
TypeError,
"is not a view on an ArrayBuffer or SharedArrayBuffer",
opts.prefix,
opts.context,
);
}
let buffer;
if (TypedArrayPrototypeGetSymbolToStringTag(V) !== undefined) {
buffer = TypedArrayPrototypeGetBuffer(V);
} else {
buffer = DataViewPrototypeGetBuffer(V);
}
if (!opts.allowShared && isSharedArrayBuffer(buffer)) {
throw makeException(
TypeError,
"is a view on a SharedArrayBuffer, which is not allowed",
opts.prefix,
opts.context,
);
}
return V;
};
converters.BufferSource = (V, opts = {}) => {
if (ArrayBufferIsView(V)) {
let buffer;
if (TypedArrayPrototypeGetSymbolToStringTag(V) !== undefined) {
buffer = TypedArrayPrototypeGetBuffer(V);
} else {
buffer = DataViewPrototypeGetBuffer(V);
}
if (!opts.allowShared && isSharedArrayBuffer(buffer)) {
throw makeException(
TypeError,
"is a view on a SharedArrayBuffer, which is not allowed",
opts.prefix,
opts.context,
);
}
return V;
}
if (!opts.allowShared && !isNonSharedArrayBuffer(V)) {
throw makeException(
TypeError,
"is not an ArrayBuffer or a view on one",
opts.prefix,
opts.context,
);
}
if (
opts.allowShared &&
!isSharedArrayBuffer(V) &&
!isNonSharedArrayBuffer(V)
) {
throw makeException(
TypeError,
"is not an ArrayBuffer, SharedArrayBuffer, or a view on one",
opts.prefix,
opts.context,
);
}
return V;
};
converters.DOMTimeStamp = converters["unsigned long long"];
converters.DOMHighResTimeStamp = converters["double"];
converters.Function = convertCallbackFunction;
converters.VoidFunction = convertCallbackFunction;
converters["UVString?"] = createNullableConverter(
converters.USVString,
);
converters["sequence"] = createSequenceConverter(
converters.double,
);
converters["sequence