SupportBot Pre-7.2
SupportBot Build for DiscordJS 13
This commit is contained in:
1 parent
09f0873f27
commit
37c870c7ab
3723 files changed
+4075
-349720
No files matched your search
+16
-64
@@ -1,11 +1,10 @@
|
||||
# Web IDL Type Conversions on JavaScript Values
|
||||
# WebIDL Type Conversions on JavaScript Values
|
||||
|
||||
This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types).
|
||||
This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types).
|
||||
|
||||
The goal is that you should be able to write code like
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
const conversions = require("webidl-conversions");
|
||||
|
||||
function doStuff(x, y) {
|
||||
@@ -15,7 +14,7 @@ function doStuff(x, y) {
|
||||
}
|
||||
```
|
||||
|
||||
and your function `doStuff` will behave the same as a Web IDL operation declared as
|
||||
and your function `doStuff` will behave the same as a WebIDL operation declared as
|
||||
|
||||
```webidl
|
||||
void doStuff(boolean x, unsigned long y);
|
||||
@@ -23,79 +22,32 @@ void doStuff(boolean x, unsigned long y);
|
||||
|
||||
## API
|
||||
|
||||
This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float).
|
||||
This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float).
|
||||
|
||||
Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`)
|
||||
## Status
|
||||
|
||||
If we are dealing with multiple JavaScript realms (such as those created using Node.js' [vm](https://nodejs.org/api/vm.html) module or the HTML `iframe` element), and exceptions from another realm need to be thrown, one can supply an object option `globals` containing the following properties:
|
||||
All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome!
|
||||
|
||||
```js
|
||||
{
|
||||
globals: {
|
||||
Number,
|
||||
String,
|
||||
TypeError
|
||||
}
|
||||
}
|
||||
```
|
||||
I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see.
|
||||
|
||||
Those specific functions will be used when throwing exceptions.
|
||||
|
||||
Specific conversions may also accept other options, the details of which can be found below.
|
||||
|
||||
## Conversions implemented
|
||||
|
||||
Conversions for all of the basic types from the Web IDL specification are implemented:
|
||||
|
||||
- [`any`](https://heycam.github.io/webidl/#es-any)
|
||||
- [`void`](https://heycam.github.io/webidl/#es-void)
|
||||
- [`boolean`](https://heycam.github.io/webidl/#es-boolean)
|
||||
- [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter
|
||||
- [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float)
|
||||
- [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double)
|
||||
- [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter
|
||||
- [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString)
|
||||
- [`object`](https://heycam.github.io/webidl/#es-object)
|
||||
- [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter
|
||||
|
||||
Additionally, for convenience, the following derived type definitions are implemented:
|
||||
|
||||
- [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter
|
||||
- [`BufferSource`](https://heycam.github.io/webidl/#BufferSource)
|
||||
- [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp)
|
||||
- [`Function`](https://heycam.github.io/webidl/#Function)
|
||||
- [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type)
|
||||
|
||||
Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project.
|
||||
|
||||
### A note on the `long long` types
|
||||
|
||||
The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers. Conversions are still accurate as we make use of BigInt in the conversion process, but in the case of `unsigned long long` we simply cannot represent some possible output values in JavaScript. For example, converting the JavaScript number `-1` to a Web IDL `unsigned long long` is supposed to produce the Web IDL value `18446744073709551615`. Since we are representing our Web IDL values in JavaScript, we can't represent `18446744073709551615`, so we instead the best we could do is `18446744073709551616` as the output.
|
||||
|
||||
To mitigate this, we could return the raw BigInt value from the conversion function, but right now it is not implemented. If your use case requires such precision, [file an issue](https://github.com/jsdom/webidl-conversions/issues/new).
|
||||
|
||||
On the other hand, `long long` conversion is always accurate, since the input value can never be more precise than the output value.
|
||||
|
||||
### A note on `BufferSource` types
|
||||
|
||||
All of the `BufferSource` types will throw when the relevant `ArrayBuffer` has been detached. This technically is not part of the [specified conversion algorithm](https://heycam.github.io/webidl/#es-buffer-source-types), but instead part of the [getting a reference/getting a copy](https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-reference%E2%91%A0) algorithms. We've consolidated them here for convenience and ease of implementation, but if there is a need to separate them in the future, please open an issue so we can investigate.
|
||||
We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do.
|
||||
|
||||
## Background
|
||||
|
||||
What's actually going on here, conceptually, is pretty weird. Let's try to explain.
|
||||
|
||||
Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules.
|
||||
WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules.
|
||||
|
||||
Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on.
|
||||
Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on.
|
||||
|
||||
Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`.
|
||||
Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`.
|
||||
|
||||
The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell.
|
||||
The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell.
|
||||
|
||||
And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`.
|
||||
And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`.
|
||||
|
||||
## Don't use this
|
||||
## Don't Use This
|
||||
|
||||
Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript.
|
||||
Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript.
|
||||
|
||||
The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/jsdom/jsdom) project.
|
||||
The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL.
|
||||
+92
-392
@@ -1,302 +1,146 @@
|
||||
"use strict";
|
||||
|
||||
function makeException(ErrorType, message, opts = {}) {
|
||||
if (opts.globals) {
|
||||
ErrorType = opts.globals[ErrorType.name];
|
||||
}
|
||||
return new ErrorType(`${opts.context ? opts.context : "Value"} ${message}.`);
|
||||
}
|
||||
|
||||
function toNumber(value, opts = {}) {
|
||||
if (!opts.globals) {
|
||||
return +value;
|
||||
}
|
||||
if (typeof value === "bigint") {
|
||||
throw opts.globals.TypeError("Cannot convert a BigInt value to a number");
|
||||
}
|
||||
return opts.globals.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(Math.floor(x));
|
||||
}
|
||||
|
||||
return censorNegativeZero(Math.round(x));
|
||||
}
|
||||
|
||||
function integerPart(n) {
|
||||
return censorNegativeZero(Math.trunc(n));
|
||||
}
|
||||
var conversions = {};
|
||||
module.exports = conversions;
|
||||
|
||||
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 = Number.MAX_SAFE_INTEGER;
|
||||
lowerBound = !isSigned ? 0 : Number.MIN_SAFE_INTEGER;
|
||||
} else if (!isSigned) {
|
||||
lowerBound = 0;
|
||||
upperBound = Math.pow(2, bitLength) - 1;
|
||||
function evenRound(x) {
|
||||
// Round x to the nearest integer, choosing the even integer if it lies halfway between two.
|
||||
if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor)
|
||||
return Math.floor(x);
|
||||
} else {
|
||||
lowerBound = -Math.pow(2, bitLength - 1);
|
||||
upperBound = Math.pow(2, bitLength - 1) - 1;
|
||||
return Math.round(x);
|
||||
}
|
||||
}
|
||||
|
||||
const twoToTheBitLength = Math.pow(2, bitLength);
|
||||
const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1);
|
||||
function createNumberConversion(bitLength, typeOpts) {
|
||||
if (!typeOpts.unsigned) {
|
||||
--bitLength;
|
||||
}
|
||||
const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);
|
||||
const upperBound = Math.pow(2, bitLength) - 1;
|
||||
|
||||
return (V, opts = {}) => {
|
||||
let x = toNumber(V, opts);
|
||||
x = censorNegativeZero(x);
|
||||
const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);
|
||||
const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);
|
||||
|
||||
return function(V, opts) {
|
||||
if (!opts) opts = {};
|
||||
|
||||
let x = +V;
|
||||
|
||||
if (opts.enforceRange) {
|
||||
if (!Number.isFinite(x)) {
|
||||
throw makeException(TypeError, "is not a finite number", opts);
|
||||
throw new TypeError("Argument is not a finite number");
|
||||
}
|
||||
|
||||
x = integerPart(x);
|
||||
|
||||
x = sign(x) * Math.floor(Math.abs(x));
|
||||
if (x < lowerBound || x > upperBound) {
|
||||
throw makeException(TypeError,
|
||||
`is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts);
|
||||
throw new TypeError("Argument is not in byte range");
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
if (!Number.isNaN(x) && opts.clamp) {
|
||||
x = Math.min(Math.max(x, lowerBound), upperBound);
|
||||
if (!isNaN(x) && opts.clamp) {
|
||||
x = evenRound(x);
|
||||
|
||||
if (x < lowerBound) x = lowerBound;
|
||||
if (x > upperBound) x = upperBound;
|
||||
return x;
|
||||
}
|
||||
|
||||
if (!Number.isFinite(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;
|
||||
x = sign(x) * Math.floor(Math.abs(x));
|
||||
x = x % moduloVal;
|
||||
|
||||
if (!typeOpts.unsigned && x >= moduloBound) {
|
||||
return x - moduloVal;
|
||||
} else if (typeOpts.unsigned) {
|
||||
if (x < 0) {
|
||||
x += moduloVal;
|
||||
} else if (x === -0) { // don't return negative zero
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// 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 = Number.MAX_SAFE_INTEGER;
|
||||
const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
|
||||
const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN;
|
||||
|
||||
return (V, opts = {}) => {
|
||||
if (opts === undefined) {
|
||||
opts = {};
|
||||
}
|
||||
|
||||
let x = toNumber(V, opts);
|
||||
x = censorNegativeZero(x);
|
||||
|
||||
if (opts.enforceRange) {
|
||||
if (!Number.isFinite(x)) {
|
||||
throw makeException(TypeError, "is not a finite number", opts);
|
||||
}
|
||||
|
||||
x = integerPart(x);
|
||||
|
||||
if (x < lowerBound || x > upperBound) {
|
||||
throw makeException(TypeError,
|
||||
`is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts);
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
if (!Number.isNaN(x) && opts.clamp) {
|
||||
x = Math.min(Math.max(x, lowerBound), upperBound);
|
||||
x = evenRound(x);
|
||||
return x;
|
||||
}
|
||||
|
||||
if (!Number.isFinite(x) || x === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let xBigInt = BigInt(integerPart(x));
|
||||
xBigInt = asBigIntN(bitLength, xBigInt);
|
||||
return Number(xBigInt);
|
||||
};
|
||||
}
|
||||
|
||||
exports.any = V => {
|
||||
return V;
|
||||
};
|
||||
|
||||
exports.void = function () {
|
||||
conversions["void"] = function () {
|
||||
return undefined;
|
||||
};
|
||||
|
||||
exports.boolean = function (val) {
|
||||
conversions["boolean"] = function (val) {
|
||||
return !!val;
|
||||
};
|
||||
|
||||
exports.byte = createIntegerConversion(8, { unsigned: false });
|
||||
exports.octet = createIntegerConversion(8, { unsigned: true });
|
||||
conversions["byte"] = createNumberConversion(8, { unsigned: false });
|
||||
conversions["octet"] = createNumberConversion(8, { unsigned: true });
|
||||
|
||||
exports.short = createIntegerConversion(16, { unsigned: false });
|
||||
exports["unsigned short"] = createIntegerConversion(16, { unsigned: true });
|
||||
conversions["short"] = createNumberConversion(16, { unsigned: false });
|
||||
conversions["unsigned short"] = createNumberConversion(16, { unsigned: true });
|
||||
|
||||
exports.long = createIntegerConversion(32, { unsigned: false });
|
||||
exports["unsigned long"] = createIntegerConversion(32, { unsigned: true });
|
||||
conversions["long"] = createNumberConversion(32, { unsigned: false });
|
||||
conversions["unsigned long"] = createNumberConversion(32, { unsigned: true });
|
||||
|
||||
exports["long long"] = createLongLongConversion(64, { unsigned: false });
|
||||
exports["unsigned long long"] = createLongLongConversion(64, { unsigned: true });
|
||||
conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });
|
||||
conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });
|
||||
|
||||
exports.double = (V, opts) => {
|
||||
const x = toNumber(V, opts);
|
||||
conversions["double"] = function (V) {
|
||||
const x = +V;
|
||||
|
||||
if (!Number.isFinite(x)) {
|
||||
throw makeException(TypeError, "is not a finite floating-point value", opts);
|
||||
throw new TypeError("Argument is not a finite floating-point value");
|
||||
}
|
||||
|
||||
return x;
|
||||
};
|
||||
|
||||
exports["unrestricted double"] = (V, opts) => {
|
||||
const x = toNumber(V, opts);
|
||||
|
||||
return x;
|
||||
};
|
||||
|
||||
exports.float = (V, opts) => {
|
||||
const x = toNumber(V, opts);
|
||||
|
||||
if (!Number.isFinite(x)) {
|
||||
throw makeException(TypeError, "is not a finite floating-point value", opts);
|
||||
}
|
||||
|
||||
if (Object.is(x, -0)) {
|
||||
return x;
|
||||
}
|
||||
|
||||
const y = Math.fround(x);
|
||||
|
||||
if (!Number.isFinite(y)) {
|
||||
throw makeException(TypeError, "is outside the range of a single-precision floating-point value", opts);
|
||||
}
|
||||
|
||||
return y;
|
||||
};
|
||||
|
||||
exports["unrestricted float"] = (V, opts) => {
|
||||
const x = toNumber(V, opts);
|
||||
conversions["unrestricted double"] = function (V) {
|
||||
const x = +V;
|
||||
|
||||
if (isNaN(x)) {
|
||||
return x;
|
||||
throw new TypeError("Argument is NaN");
|
||||
}
|
||||
|
||||
if (Object.is(x, -0)) {
|
||||
return x;
|
||||
}
|
||||
|
||||
return Math.fround(x);
|
||||
return x;
|
||||
};
|
||||
|
||||
exports.DOMString = function (V, opts = {}) {
|
||||
// not quite valid, but good enough for JS
|
||||
conversions["float"] = conversions["double"];
|
||||
conversions["unrestricted float"] = conversions["unrestricted double"];
|
||||
|
||||
conversions["DOMString"] = function (V, opts) {
|
||||
if (!opts) opts = {};
|
||||
|
||||
if (opts.treatNullAsEmptyString && V === null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof V === "symbol") {
|
||||
throw makeException(TypeError, "is a symbol, which cannot be converted to a string", opts);
|
||||
}
|
||||
|
||||
const StringCtor = opts.globals ? opts.globals.String : String;
|
||||
return StringCtor(V);
|
||||
return String(V);
|
||||
};
|
||||
|
||||
exports.ByteString = (V, opts) => {
|
||||
const x = exports.DOMString(V, opts);
|
||||
let c;
|
||||
conversions["ByteString"] = function (V, opts) {
|
||||
const x = String(V);
|
||||
let c = undefined;
|
||||
for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) {
|
||||
if (c > 255) {
|
||||
throw makeException(TypeError, "is not a valid ByteString", opts);
|
||||
throw new TypeError("Argument is not a valid bytestring");
|
||||
}
|
||||
}
|
||||
|
||||
return x;
|
||||
};
|
||||
|
||||
exports.USVString = (V, opts) => {
|
||||
const S = exports.DOMString(V, opts);
|
||||
conversions["USVString"] = function (V) {
|
||||
const S = String(V);
|
||||
const n = S.length;
|
||||
const U = [];
|
||||
for (let i = 0; i < n; ++i) {
|
||||
@@ -305,185 +149,41 @@ exports.USVString = (V, opts) => {
|
||||
U.push(String.fromCodePoint(c));
|
||||
} else if (0xDC00 <= c && c <= 0xDFFF) {
|
||||
U.push(String.fromCodePoint(0xFFFD));
|
||||
} else if (i === n - 1) {
|
||||
U.push(String.fromCodePoint(0xFFFD));
|
||||
} else {
|
||||
const d = S.charCodeAt(i + 1);
|
||||
if (0xDC00 <= d && d <= 0xDFFF) {
|
||||
const a = c & 0x3FF;
|
||||
const b = d & 0x3FF;
|
||||
U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b));
|
||||
++i;
|
||||
} else {
|
||||
if (i === n - 1) {
|
||||
U.push(String.fromCodePoint(0xFFFD));
|
||||
} else {
|
||||
const d = S.charCodeAt(i + 1);
|
||||
if (0xDC00 <= d && d <= 0xDFFF) {
|
||||
const a = c & 0x3FF;
|
||||
const b = d & 0x3FF;
|
||||
U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
|
||||
++i;
|
||||
} else {
|
||||
U.push(String.fromCodePoint(0xFFFD));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return U.join("");
|
||||
return U.join('');
|
||||
};
|
||||
|
||||
exports.object = (V, opts) => {
|
||||
if (type(V) !== "Object") {
|
||||
throw makeException(TypeError, "is not an object", opts);
|
||||
conversions["Date"] = function (V, opts) {
|
||||
if (!(V instanceof Date)) {
|
||||
throw new TypeError("Argument is not a Date object");
|
||||
}
|
||||
if (isNaN(V)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
return V;
|
||||
}
|
||||
|
||||
const abByteLengthGetter =
|
||||
Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
|
||||
const sabByteLengthGetter =
|
||||
Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get;
|
||||
|
||||
function isNonSharedArrayBuffer(V) {
|
||||
try {
|
||||
// This will throw on SharedArrayBuffers, but not detached ArrayBuffers.
|
||||
// (The spec says it should throw, but the spec conflicts with implementations: https://github.com/tc39/ecma262/issues/678)
|
||||
abByteLengthGetter.call(V);
|
||||
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isSharedArrayBuffer(V) {
|
||||
try {
|
||||
sabByteLengthGetter.call(V);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isArrayBufferDetached(V) {
|
||||
try {
|
||||
// eslint-disable-next-line no-new
|
||||
new Uint8Array(V);
|
||||
return false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
exports.ArrayBuffer = (V, opts = {}) => {
|
||||
if (!isNonSharedArrayBuffer(V)) {
|
||||
if (opts.allowShared && !isSharedArrayBuffer(V)) {
|
||||
throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", opts);
|
||||
}
|
||||
throw makeException(TypeError, "is not an ArrayBuffer", opts);
|
||||
}
|
||||
if (isArrayBufferDetached(V)) {
|
||||
throw makeException(TypeError, "is a detached ArrayBuffer", opts);
|
||||
conversions["RegExp"] = function (V, opts) {
|
||||
if (!(V instanceof RegExp)) {
|
||||
V = new RegExp(V);
|
||||
}
|
||||
|
||||
return V;
|
||||
};
|
||||
|
||||
const dvByteLengthGetter =
|
||||
Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
|
||||
exports.DataView = (V, opts = {}) => {
|
||||
try {
|
||||
dvByteLengthGetter.call(V);
|
||||
} catch (e) {
|
||||
throw makeException(TypeError, "is not a DataView", opts);
|
||||
}
|
||||
|
||||
if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {
|
||||
throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", opts);
|
||||
}
|
||||
if (isArrayBufferDetached(V.buffer)) {
|
||||
throw makeException(TypeError, "is backed by a detached ArrayBuffer", opts);
|
||||
}
|
||||
|
||||
return V;
|
||||
};
|
||||
|
||||
// Returns the unforgeable `TypedArray` constructor name or `undefined`,
|
||||
// if the `this` value isn't a valid `TypedArray` object.
|
||||
//
|
||||
// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag
|
||||
const typedArrayNameGetter = Object.getOwnPropertyDescriptor(
|
||||
Object.getPrototypeOf(Uint8Array).prototype,
|
||||
Symbol.toStringTag
|
||||
).get;
|
||||
[
|
||||
Int8Array, Int16Array, Int32Array, Uint8Array,
|
||||
Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array
|
||||
].forEach(func => {
|
||||
const name = func.name;
|
||||
const article = /^[AEIOU]/.test(name) ? "an" : "a";
|
||||
exports[name] = (V, opts = {}) => {
|
||||
if (!ArrayBuffer.isView(V) || typedArrayNameGetter.call(V) !== name) {
|
||||
throw makeException(TypeError, `is not ${article} ${name} object`, opts);
|
||||
}
|
||||
if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {
|
||||
throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts);
|
||||
}
|
||||
if (isArrayBufferDetached(V.buffer)) {
|
||||
throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts);
|
||||
}
|
||||
|
||||
return V;
|
||||
};
|
||||
});
|
||||
|
||||
// Common definitions
|
||||
|
||||
exports.ArrayBufferView = (V, opts = {}) => {
|
||||
if (!ArrayBuffer.isView(V)) {
|
||||
throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", opts);
|
||||
}
|
||||
|
||||
if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {
|
||||
throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts);
|
||||
}
|
||||
|
||||
if (isArrayBufferDetached(V.buffer)) {
|
||||
throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts);
|
||||
}
|
||||
return V;
|
||||
};
|
||||
|
||||
exports.BufferSource = (V, opts = {}) => {
|
||||
if (ArrayBuffer.isView(V)) {
|
||||
if (!opts.allowShared && isSharedArrayBuffer(V.buffer)) {
|
||||
throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", opts);
|
||||
}
|
||||
|
||||
if (isArrayBufferDetached(V.buffer)) {
|
||||
throw makeException(TypeError, "is a view on a detached ArrayBuffer", opts);
|
||||
}
|
||||
return V;
|
||||
}
|
||||
|
||||
if (!opts.allowShared && !isNonSharedArrayBuffer(V)) {
|
||||
throw makeException(TypeError, "is not an ArrayBuffer or a view on one", opts);
|
||||
}
|
||||
if (opts.allowShared && !isSharedArrayBuffer(V) && !isNonSharedArrayBuffer(V)) {
|
||||
throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBufer, or a view on one", opts);
|
||||
}
|
||||
if (isArrayBufferDetached(V)) {
|
||||
throw makeException(TypeError, "is a detached ArrayBuffer", opts);
|
||||
}
|
||||
|
||||
return V;
|
||||
};
|
||||
|
||||
exports.DOMTimeStamp = exports["unsigned long long"];
|
||||
|
||||
exports.Function = convertCallbackFunction;
|
||||
|
||||
exports.VoidFunction = convertCallbackFunction;
|
||||
+3
-10
@@ -1,12 +1,10 @@
|
||||
{
|
||||
"name": "webidl-conversions",
|
||||
"version": "6.1.0",
|
||||
"version": "3.0.1",
|
||||
"description": "Implements the WebIDL algorithms for converting to and from JavaScript values",
|
||||
"main": "lib/index.js",
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha test/*.js",
|
||||
"coverage": "nyc mocha test/*.js"
|
||||
"test": "mocha test/*.js"
|
||||
},
|
||||
"repository": "jsdom/webidl-conversions",
|
||||
"keywords": [
|
||||
@@ -20,11 +18,6 @@
|
||||
"author": "Domenic Denicola <d@domenic.me> (https://domenic.me/)",
|
||||
"license": "BSD-2-Clause",
|
||||
"devDependencies": {
|
||||
"eslint": "^6.8.0",
|
||||
"mocha": "^7.1.1",
|
||||
"nyc": "^15.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.4"
|
||||
"mocha": "^1.21.4"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user