@metamask/utils 3.3.1 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assert.js +7 -2
- package/dist/assert.js.map +1 -1
- package/dist/base64.d.ts +24 -0
- package/dist/base64.js +35 -0
- package/dist/base64.js.map +1 -0
- package/dist/bytes.js +13 -9
- package/dist/bytes.js.map +1 -1
- package/dist/checksum.d.ts +1 -0
- package/dist/checksum.js +7 -0
- package/dist/checksum.js.map +1 -0
- package/dist/coercers.js +4 -4
- package/dist/coercers.js.map +1 -1
- package/dist/hex.d.ts +4 -4
- package/dist/hex.js +12 -12
- package/dist/hex.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +7 -7
- package/dist/json.js +21 -7
- package/dist/json.js.map +1 -1
- package/dist/json.test-d.js +3 -3
- package/dist/json.test-d.js.map +1 -1
- package/dist/number.js +1 -1
- package/dist/number.js.map +1 -1
- package/dist/opaque.d.ts +5 -0
- package/dist/opaque.js +3 -0
- package/dist/opaque.js.map +1 -0
- package/dist/versions.d.ts +100 -0
- package/dist/versions.js +95 -0
- package/dist/versions.js.map +1 -0
- package/package.json +21 -21
package/dist/assert.js
CHANGED
|
@@ -47,6 +47,7 @@ function getErrorMessage(error) {
|
|
|
47
47
|
* @param message - The error message.
|
|
48
48
|
* @returns The error object.
|
|
49
49
|
*/
|
|
50
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
50
51
|
function getError(ErrorWrapper, message) {
|
|
51
52
|
if (isConstructable(ErrorWrapper)) {
|
|
52
53
|
return new ErrorWrapper({
|
|
@@ -79,7 +80,9 @@ exports.AssertionError = AssertionError;
|
|
|
79
80
|
* Defaults to {@link AssertionError}. If a custom error class is provided for
|
|
80
81
|
* the `message` argument, this argument is ignored.
|
|
81
82
|
*/
|
|
82
|
-
function assert(value, message = 'Assertion failed.',
|
|
83
|
+
function assert(value, message = 'Assertion failed.',
|
|
84
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
85
|
+
ErrorWrapper = AssertionError) {
|
|
83
86
|
if (!value) {
|
|
84
87
|
if (message instanceof Error) {
|
|
85
88
|
throw message;
|
|
@@ -99,7 +102,9 @@ exports.assert = assert;
|
|
|
99
102
|
* Defaults to {@link AssertionError}.
|
|
100
103
|
* @throws If the value is not valid.
|
|
101
104
|
*/
|
|
102
|
-
function assertStruct(value, struct, errorPrefix = 'Assertion failed',
|
|
105
|
+
function assertStruct(value, struct, errorPrefix = 'Assertion failed',
|
|
106
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
107
|
+
ErrorWrapper = AssertionError) {
|
|
103
108
|
try {
|
|
104
109
|
(0, superstruct_1.assert)(value, struct);
|
|
105
110
|
}
|
package/dist/assert.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assert.js","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":";;;AAAA,6CAAkE;AAMlE;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,SAAS,IAAI,KAAK,CAAC;AAC3E,CAAC;AAED;;;;;;GAMG;AACH,SAAS,eAAe,CACtB,EAA6B;;IAE7B,0BAA0B;IAC1B,OAAO,OAAO,CAAC,OAAO,CAAA,MAAA,MAAA,EAAE,aAAF,EAAE,uBAAF,EAAE,CAAE,SAAS,0CAAE,WAAW,0CAAE,IAAI,CAAA,KAAK,QAAQ,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,eAAe,CAAC,KAAc;IACrC,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAE1E,2EAA2E;IAC3E,IAA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C,KAAK,CAAC,GAAG,CAAC,CAAC;KAC5E;AACH,CAAC;AAZD,oCAYC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,gBAAgB,CAAC,OAAc;IAC7C,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;AACJ,CAAC;AAJD,4CAIC","sourcesContent":["import { assert as assertSuperstruct, Struct } from 'superstruct';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `message` property, such as an instance of Error.\n *\n * @param error - The object to check.\n * @returns True or false, depending on the result.\n */\nfunction isErrorWithMessage(error: unknown): error is { message: string } {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n\n/**\n * Check if a value is a constructor, i.e., a function that can be called with\n * the `new` keyword.\n *\n * @param fn - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nfunction isConstructable(\n fn: AssertionErrorConstructor,\n): fn is new (args: { message: string }) => Error {\n /* istanbul ignore next */\n return Boolean(typeof fn?.prototype?.constructor?.name === 'string');\n}\n\n/**\n * Get the error message from an unknown error object. If the error object has\n * a `message` property, that property is returned. Otherwise, the stringified\n * error object is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The error message.\n */\nfunction getErrorMessage(error: unknown): string {\n const message = isErrorWithMessage(error) ? error.message : String(error);\n\n // If the error ends with a period, remove it, as we'll add our own period.\n if (message.endsWith('.')) {\n return message.slice(0, -1);\n }\n\n return message;\n}\n\n/**\n * Initialise an {@link AssertionErrorConstructor} error.\n *\n * @param ErrorWrapper - The error class to use.\n * @param message - The error message.\n * @returns The error object.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction getError(ErrorWrapper: AssertionErrorConstructor, message: string) {\n if (isConstructable(ErrorWrapper)) {\n return new ErrorWrapper({\n message,\n });\n }\n return ErrorWrapper({\n message,\n });\n}\n\n/**\n * The default error class that is thrown if an assertion fails.\n */\nexport class AssertionError extends Error {\n readonly code = 'ERR_ASSERTION';\n\n constructor(options: { message: string }) {\n super(options.message);\n }\n}\n\n/**\n * Same as Node.js assert.\n * If the value is falsy, throws an error, does nothing otherwise.\n *\n * @throws {@link AssertionError} If value is falsy.\n * @param value - The test that should be truthy to pass.\n * @param message - Message to be passed to {@link AssertionError} or an\n * {@link Error} instance to throw.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}. If a custom error class is provided for\n * the `message` argument, this argument is ignored.\n */\nexport function assert(\n value: any,\n message: string | Error = 'Assertion failed.',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value {\n if (!value) {\n if (message instanceof Error) {\n throw message;\n }\n\n throw getError(ErrorWrapper, message);\n }\n}\n\n/**\n * Assert a value against a Superstruct struct.\n *\n * @param value - The value to validate.\n * @param struct - The struct to validate against.\n * @param errorPrefix - A prefix to add to the error message. Defaults to\n * \"Assertion failed\".\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the value is not valid.\n */\nexport function assertStruct<T, S>(\n value: unknown,\n struct: Struct<T, S>,\n errorPrefix = 'Assertion failed',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value is T {\n try {\n assertSuperstruct(value, struct);\n } catch (error) {\n throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessage(error)}.`);\n }\n}\n\n/**\n * Use in the default case of a switch that you want to be fully exhaustive.\n * Using this function forces the compiler to enforce exhaustivity during\n * compile-time.\n *\n * @example\n * ```\n * const number = 1;\n * switch (number) {\n * case 0:\n * ...\n * case 1:\n * ...\n * default:\n * assertExhaustive(snapPrefix);\n * }\n * ```\n * @param _object - The object on which the switch is being operated.\n */\nexport function assertExhaustive(_object: never): never {\n throw new Error(\n 'Invalid branch reached. Should be detected during compilation.',\n );\n}\n"]}
|
package/dist/base64.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Struct } from 'superstruct';
|
|
2
|
+
export declare type Base64Options = {
|
|
3
|
+
/**
|
|
4
|
+
* Is the `=` padding at the end required or not.
|
|
5
|
+
*
|
|
6
|
+
* @default false
|
|
7
|
+
*/
|
|
8
|
+
paddingRequired?: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Which character set should be used.
|
|
11
|
+
* The sets are based on {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}.
|
|
12
|
+
*
|
|
13
|
+
* @default 'base64'
|
|
14
|
+
*/
|
|
15
|
+
characterSet?: 'base64' | 'base64url';
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Ensure that a provided string-based struct is valid base64.
|
|
19
|
+
*
|
|
20
|
+
* @param struct - The string based struct.
|
|
21
|
+
* @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.
|
|
22
|
+
* @returns A superstruct validating base64.
|
|
23
|
+
*/
|
|
24
|
+
export declare const base64: <T extends string, S>(struct: Struct<T, S>, options?: Base64Options) => Struct<T, S>;
|
package/dist/base64.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.base64 = void 0;
|
|
4
|
+
const superstruct_1 = require("superstruct");
|
|
5
|
+
const assert_1 = require("./assert");
|
|
6
|
+
/**
|
|
7
|
+
* Ensure that a provided string-based struct is valid base64.
|
|
8
|
+
*
|
|
9
|
+
* @param struct - The string based struct.
|
|
10
|
+
* @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.
|
|
11
|
+
* @returns A superstruct validating base64.
|
|
12
|
+
*/
|
|
13
|
+
const base64 = (struct, options = {}) => {
|
|
14
|
+
var _a, _b;
|
|
15
|
+
const paddingRequired = (_a = options.paddingRequired) !== null && _a !== void 0 ? _a : false;
|
|
16
|
+
const characterSet = (_b = options.characterSet) !== null && _b !== void 0 ? _b : 'base64';
|
|
17
|
+
let letters;
|
|
18
|
+
if (characterSet === 'base64') {
|
|
19
|
+
letters = String.raw `[A-Za-z0-9+\/]`;
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
(0, assert_1.assert)(characterSet === 'base64url');
|
|
23
|
+
letters = String.raw `[-_A-Za-z0-9]`;
|
|
24
|
+
}
|
|
25
|
+
let re;
|
|
26
|
+
if (paddingRequired) {
|
|
27
|
+
re = new RegExp(`^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`, 'u');
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
re = new RegExp(`^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`, 'u');
|
|
31
|
+
}
|
|
32
|
+
return (0, superstruct_1.pattern)(struct, re);
|
|
33
|
+
};
|
|
34
|
+
exports.base64 = base64;
|
|
35
|
+
//# sourceMappingURL=base64.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base64.js","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":";;;AAAA,6CAA8C;AAE9C,qCAAkC;AAmBlC;;;;;;GAMG;AACI,MAAM,MAAM,GAAG,CACpB,MAAoB,EACpB,UAAyB,EAAE,EAC3B,EAAE;;IACF,MAAM,eAAe,GAAG,MAAA,OAAO,CAAC,eAAe,mCAAI,KAAK,CAAC;IACzD,MAAM,YAAY,GAAG,MAAA,OAAO,CAAC,YAAY,mCAAI,QAAQ,CAAC;IAEtD,IAAI,OAAe,CAAC;IACpB,IAAI,YAAY,KAAK,QAAQ,EAAE;QAC7B,OAAO,GAAG,MAAM,CAAC,GAAG,CAAA,gBAAgB,CAAC;KACtC;SAAM;QACL,IAAA,eAAM,EAAC,YAAY,KAAK,WAAW,CAAC,CAAC;QACrC,OAAO,GAAG,MAAM,CAAC,GAAG,CAAA,eAAe,CAAC;KACrC;IAED,IAAI,EAAU,CAAC;IACf,IAAI,eAAe,EAAE;QACnB,EAAE,GAAG,IAAI,MAAM,CACb,OAAO,OAAO,WAAW,OAAO,QAAQ,OAAO,UAAU,EACzD,GAAG,CACJ,CAAC;KACH;SAAM;QACL,EAAE,GAAG,IAAI,MAAM,CACb,OAAO,OAAO,WAAW,OAAO,SAAS,OAAO,QAAQ,OAAO,UAAU,EACzE,GAAG,CACJ,CAAC;KACH;IAED,OAAO,IAAA,qBAAO,EAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC,CAAC;AA7BW,QAAA,MAAM,UA6BjB","sourcesContent":["import { pattern, Struct } from 'superstruct';\n\nimport { assert } from './assert';\n\nexport type Base64Options = {\n /**\n * Is the `=` padding at the end required or not.\n *\n * @default false\n */\n // Padding is optional in RFC 4648, that's why the default value is false\n paddingRequired?: boolean;\n /**\n * Which character set should be used.\n * The sets are based on {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}.\n *\n * @default 'base64'\n */\n characterSet?: 'base64' | 'base64url';\n};\n\n/**\n * Ensure that a provided string-based struct is valid base64.\n *\n * @param struct - The string based struct.\n * @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.\n * @returns A superstruct validating base64.\n */\nexport const base64 = <T extends string, S>(\n struct: Struct<T, S>,\n options: Base64Options = {},\n) => {\n const paddingRequired = options.paddingRequired ?? false;\n const characterSet = options.characterSet ?? 'base64';\n\n let letters: string;\n if (characterSet === 'base64') {\n letters = String.raw`[A-Za-z0-9+\\/]`;\n } else {\n assert(characterSet === 'base64url');\n letters = String.raw`[-_A-Za-z0-9]`;\n }\n\n let re: RegExp;\n if (paddingRequired) {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n } else {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n }\n\n return pattern(struct, re);\n};\n"]}
|
package/dist/bytes.js
CHANGED
|
@@ -74,12 +74,12 @@ function bytesToHex(bytes) {
|
|
|
74
74
|
return '0x';
|
|
75
75
|
}
|
|
76
76
|
const lookupTable = getPrecomputedHexValues();
|
|
77
|
-
const
|
|
77
|
+
const hexadecimal = new Array(bytes.length);
|
|
78
78
|
for (let i = 0; i < bytes.length; i++) {
|
|
79
79
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
80
|
-
|
|
80
|
+
hexadecimal[i] = lookupTable[bytes[i]];
|
|
81
81
|
}
|
|
82
|
-
return (0, hex_1.add0x)(
|
|
82
|
+
return (0, hex_1.add0x)(hexadecimal.join(''));
|
|
83
83
|
}
|
|
84
84
|
exports.bytesToHex = bytesToHex;
|
|
85
85
|
/**
|
|
@@ -94,8 +94,8 @@ exports.bytesToHex = bytesToHex;
|
|
|
94
94
|
*/
|
|
95
95
|
function bytesToBigInt(bytes) {
|
|
96
96
|
assertIsBytes(bytes);
|
|
97
|
-
const
|
|
98
|
-
return BigInt(
|
|
97
|
+
const hexadecimal = bytesToHex(bytes);
|
|
98
|
+
return BigInt(hexadecimal);
|
|
99
99
|
}
|
|
100
100
|
exports.bytesToBigInt = bytesToBigInt;
|
|
101
101
|
/**
|
|
@@ -198,8 +198,8 @@ exports.hexToBytes = hexToBytes;
|
|
|
198
198
|
function bigIntToBytes(value) {
|
|
199
199
|
(0, assert_1.assert)(typeof value === 'bigint', 'Value must be a bigint.');
|
|
200
200
|
(0, assert_1.assert)(value >= BigInt(0), 'Value must be a non-negative bigint.');
|
|
201
|
-
const
|
|
202
|
-
return hexToBytes(
|
|
201
|
+
const hexadecimal = value.toString(16);
|
|
202
|
+
return hexToBytes(hexadecimal);
|
|
203
203
|
}
|
|
204
204
|
exports.bigIntToBytes = bigIntToBytes;
|
|
205
205
|
/**
|
|
@@ -258,8 +258,8 @@ function numberToBytes(value) {
|
|
|
258
258
|
(0, assert_1.assert)(typeof value === 'number', 'Value must be a number.');
|
|
259
259
|
(0, assert_1.assert)(value >= 0, 'Value must be a non-negative number.');
|
|
260
260
|
(0, assert_1.assert)(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToBytes` instead.');
|
|
261
|
-
const
|
|
262
|
-
return hexToBytes(
|
|
261
|
+
const hexadecimal = value.toString(16);
|
|
262
|
+
return hexToBytes(hexadecimal);
|
|
263
263
|
}
|
|
264
264
|
exports.numberToBytes = numberToBytes;
|
|
265
265
|
/**
|
|
@@ -364,6 +364,10 @@ exports.concatBytes = concatBytes;
|
|
|
364
364
|
* @returns The {@link DataView}.
|
|
365
365
|
*/
|
|
366
366
|
function createDataView(bytes) {
|
|
367
|
+
// To maintain compatibility with Node.js, we need to check if the bytes are
|
|
368
|
+
// a Buffer. If so, we need to slice the buffer to get the underlying
|
|
369
|
+
// ArrayBuffer.
|
|
370
|
+
// eslint-disable-next-line no-restricted-globals
|
|
367
371
|
if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {
|
|
368
372
|
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
369
373
|
return new DataView(buffer);
|
package/dist/bytes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../src/bytes.ts"],"names":[],"mappings":";;;AAAA,qCAAkC;AAClC,+BAAgE;AAEhE,2BAA2B;AAC3B,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAExC,2BAA2B;AAC3B,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAIhC;;;;;;;;;;;;;GAaG;AACH,SAAS,8BAA8B;IACrC,6EAA6E;IAC7E,6EAA6E;IAC7E,6EAA6E;IAC7E,eAAe;IACf,MAAM,WAAW,GAAa,EAAE,CAAC;IAEjC,OAAO,GAAG,EAAE;QACV,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE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,CAAC,UAAU,EAChB,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CACpC,CAAC;QAEF,OAAO,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC;KAC7B;IAED,OAAO,IAAI,QAAQ,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;AACxE,CAAC;AAXD,wCAWC","sourcesContent":["import { assert } from './assert';\nimport { add0x, assertIsHexString, Hex, remove0x } from './hex';\n\n// '0'.charCodeAt(0) === 48\nconst HEX_MINIMUM_NUMBER_CHARACTER = 48;\n\n// '9'.charCodeAt(0) === 57\nconst HEX_MAXIMUM_NUMBER_CHARACTER = 58;\nconst HEX_CHARACTER_OFFSET = 87;\n\nexport type Bytes = bigint | number | string | Uint8Array;\n\n/**\n * Memoized function that returns an array to be used as a lookup table for\n * converting bytes to hexadecimal values.\n *\n * The array is created lazily and then cached for future use. The benefit of\n * this approach is that the performance of converting bytes to hex is much\n * better than if we were to call `toString(16)` on each byte.\n *\n * The downside is that the array is created once and then never garbage\n * collected. This is not a problem in practice because the array is only 256\n * elements long.\n *\n * @returns A function that returns the lookup table.\n */\nfunction getPrecomputedHexValuesBuilder(): () => string[] {\n // To avoid issues with tree shaking, we need to use a function to return the\n // array. This is because the array is only used in the `bytesToHex` function\n // and if we were to use a global variable, the array might be removed by the\n // tree shaker.\n const lookupTable: string[] = [];\n\n return () => {\n if (lookupTable.length === 0) {\n for (let i = 0; i < 256; i++) {\n lookupTable.push(i.toString(16).padStart(2, '0'));\n }\n }\n\n return lookupTable;\n };\n}\n\n/**\n * Function implementation of the {@link getPrecomputedHexValuesBuilder}\n * function.\n */\nconst getPrecomputedHexValues = getPrecomputedHexValuesBuilder();\n\n/**\n * Check if a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @returns Whether the value is a `Uint8Array`.\n */\nexport function isBytes(value: unknown): value is Uint8Array {\n return value instanceof Uint8Array;\n}\n\n/**\n * Assert that a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @throws If the value is not a `Uint8Array`.\n */\nexport function assertIsBytes(value: unknown): asserts value is Uint8Array {\n assert(isBytes(value), 'Value must be a Uint8Array.');\n}\n\n/**\n * Convert a `Uint8Array` to a hexadecimal string.\n *\n * @param bytes - The bytes to convert to a hexadecimal string.\n * @returns The hexadecimal string.\n */\nexport function bytesToHex(bytes: Uint8Array): Hex {\n assertIsBytes(bytes);\n\n if (bytes.length === 0) {\n return '0x';\n }\n\n const lookupTable = getPrecomputedHexValues();\n const hex = new Array(bytes.length);\n\n for (let i = 0; i < bytes.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n hex[i] = lookupTable[bytes[i]!];\n }\n\n return add0x(hex.join(''));\n}\n\n/**\n * Convert a `Uint8Array` to a `bigint`.\n *\n * To convert a `Uint8Array` to a `number` instead, use {@link bytesToNumber}.\n * To convert a two's complement encoded `Uint8Array` to a `bigint`, use\n * {@link bytesToSignedBigInt}.\n *\n * @param bytes - The bytes to convert to a `bigint`.\n * @returns The `bigint`.\n */\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n const hex = bytesToHex(bytes);\n return BigInt(hex);\n}\n\n/**\n * Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are\n * encoded in two's complement.\n *\n * To convert a `Uint8Array` to an unsigned `bigint` instead, use\n * {@link bytesToBigInt}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param bytes - The bytes to convert to a signed `bigint`.\n * @returns The signed `bigint`.\n */\nexport function bytesToSignedBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n let value = BigInt(0);\n for (const byte of bytes) {\n // eslint-disable-next-line no-bitwise\n value = (value << BigInt(8)) + BigInt(byte);\n }\n\n return BigInt.asIntN(bytes.length * 8, value);\n}\n\n/**\n * Convert a `Uint8Array` to a `number`.\n *\n * To convert a `Uint8Array` to a `bigint` instead, use {@link bytesToBigInt}.\n *\n * @param bytes - The bytes to convert to a number.\n * @returns The number.\n * @throws If the resulting number is not a safe integer.\n */\nexport function bytesToNumber(bytes: Uint8Array): number {\n assertIsBytes(bytes);\n\n const bigint = bytesToBigInt(bytes);\n\n assert(\n bigint <= BigInt(Number.MAX_SAFE_INTEGER),\n 'Number is not a safe integer. Use `bytesToBigInt` instead.',\n );\n\n return Number(bigint);\n}\n\n/**\n * Convert a UTF-8 encoded `Uint8Array` to a `string`.\n *\n * @param bytes - The bytes to convert to a string.\n * @returns The string.\n */\nexport function bytesToString(bytes: Uint8Array): string {\n assertIsBytes(bytes);\n\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be\n * prefixed with `0x`. It accepts even and odd length strings.\n *\n * If the value is \"0x\", an empty `Uint8Array` is returned.\n *\n * @param value - The hexadecimal string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function hexToBytes(value: string): Uint8Array {\n // \"0x\" is often used as empty byte array.\n if (value?.toLowerCase?.() === '0x') {\n return new Uint8Array();\n }\n\n assertIsHexString(value);\n\n // Remove the `0x` prefix if it exists, and pad the string to have an even\n // number of characters.\n const strippedValue = remove0x(value).toLowerCase();\n const normalizedValue =\n strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;\n const bytes = new Uint8Array(normalizedValue.length / 2);\n\n for (let i = 0; i < bytes.length; i++) {\n // While this is not the prettiest way to convert a hexadecimal string to a\n // `Uint8Array`, it is a lot faster than using `parseInt` to convert each\n // character.\n const c1 = normalizedValue.charCodeAt(i * 2);\n const c2 = normalizedValue.charCodeAt(i * 2 + 1);\n const n1 =\n c1 -\n (c1 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n const n2 =\n c2 -\n (c2 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n\n bytes[i] = n1 * 16 + n2;\n }\n\n return bytes;\n}\n\n/**\n * Convert a `bigint` to a `Uint8Array`.\n *\n * This assumes that the `bigint` is an unsigned integer. To convert a signed\n * `bigint` instead, use {@link signedBigIntToBytes}.\n *\n * @param value - The bigint to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function bigIntToBytes(value: bigint): Uint8Array {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= BigInt(0), 'Value must be a non-negative bigint.');\n\n const hex = value.toString(16);\n return hexToBytes(hex);\n}\n\n/**\n * Check if a `bigint` fits in a certain number of bytes.\n *\n * @param value - The `bigint` to check.\n * @param bytes - The number of bytes.\n * @returns Whether the `bigint` fits in the number of bytes.\n */\nfunction bigIntFits(value: bigint, bytes: number): boolean {\n assert(bytes > 0);\n\n /* eslint-disable no-bitwise */\n const mask = value >> BigInt(31);\n return !(((~value & mask) + (value & ~mask)) >> BigInt(bytes * 8 + ~0));\n /* eslint-enable no-bitwise */\n}\n\n/**\n * Convert a signed `bigint` to a `Uint8Array`. This uses two's complement\n * encoding to represent negative numbers.\n *\n * To convert an unsigned `bigint` to a `Uint8Array` instead, use\n * {@link bigIntToBytes}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param value - The number to convert to bytes.\n * @param byteLength - The length of the resulting `Uint8Array`. If the number\n * is larger than the maximum value that can be represented by the given length,\n * an error is thrown.\n * @returns The bytes as `Uint8Array`.\n */\nexport function signedBigIntToBytes(\n value: bigint,\n byteLength: number,\n): Uint8Array {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(typeof byteLength === 'number', 'Byte length must be a number.');\n assert(byteLength > 0, 'Byte length must be greater than 0.');\n assert(\n bigIntFits(value, byteLength),\n 'Byte length is too small to represent the given value.',\n );\n\n // ESLint doesn't like mutating function parameters, so to avoid having to\n // disable the rule, we create a new variable.\n let numberValue = value;\n const bytes = new Uint8Array(byteLength);\n\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number(BigInt.asUintN(8, numberValue));\n // eslint-disable-next-line no-bitwise\n numberValue >>= BigInt(8);\n }\n\n return bytes.reverse();\n}\n\n/**\n * Convert a `number` to a `Uint8Array`.\n *\n * @param value - The number to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n * @throws If the number is not a safe integer.\n */\nexport function numberToBytes(value: number): Uint8Array {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToBytes` instead.',\n );\n\n const hex = value.toString(16);\n return hexToBytes(hex);\n}\n\n/**\n * Convert a `string` to a UTF-8 encoded `Uint8Array`.\n *\n * @param value - The string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function stringToBytes(value: string): Uint8Array {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return new TextEncoder().encode(value);\n}\n\n/**\n * Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,\n * a `bigint`, a `number`, or a `string`.\n *\n * This will attempt to guess the type of the value based on its type and\n * contents. For more control over the conversion, use the more specific\n * conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.\n *\n * If the value is a `string`, and it is prefixed with `0x`, it will be\n * interpreted as a hexadecimal string. Otherwise, it will be interpreted as a\n * UTF-8 string. To convert a hexadecimal string to bytes without interpreting\n * it as a UTF-8 string, use {@link hexToBytes} instead.\n *\n * If the value is a `bigint`, it is assumed to be unsigned. To convert a signed\n * `bigint` to bytes, use {@link signedBigIntToBytes} instead.\n *\n * If the value is a `Uint8Array`, it will be returned as-is.\n *\n * @param value - The value to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function valueToBytes(value: Bytes): Uint8Array {\n if (typeof value === 'bigint') {\n return bigIntToBytes(value);\n }\n\n if (typeof value === 'number') {\n return numberToBytes(value);\n }\n\n if (typeof value === 'string') {\n if (value.startsWith('0x')) {\n return hexToBytes(value);\n }\n\n return stringToBytes(value);\n }\n\n if (isBytes(value)) {\n return value;\n }\n\n throw new TypeError(`Unsupported value type: \"${typeof value}\".`);\n}\n\n/**\n * Concatenate multiple byte-like values into a single `Uint8Array`. The values\n * can be `Uint8Array`, `bigint`, `number`, or `string`. This uses\n * {@link valueToBytes} under the hood to convert each value to bytes. Refer to\n * the documentation of that function for more information.\n *\n * @param values - The values to concatenate.\n * @returns The concatenated bytes as `Uint8Array`.\n */\nexport function concatBytes(values: Bytes[]): Uint8Array {\n const normalizedValues = new Array(values.length);\n let byteLength = 0;\n\n for (let i = 0; i < values.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const value = valueToBytes(values[i]!);\n\n normalizedValues[i] = value;\n byteLength += value.length;\n }\n\n const bytes = new Uint8Array(byteLength);\n for (let i = 0, offset = 0; i < normalizedValues.length; i++) {\n // While we could simply spread the values into an array and use\n // `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`.\n bytes.set(normalizedValues[i], offset);\n offset += normalizedValues[i].length;\n }\n\n return bytes;\n}\n\n/**\n * Create a {@link DataView} from a {@link Uint8Array}. This is a convenience\n * function that avoids having to create a {@link DataView} manually, which\n * requires passing the `byteOffset` and `byteLength` parameters every time.\n *\n * Not passing the `byteOffset` and `byteLength` parameters can result in\n * unexpected behavior when the {@link Uint8Array} is a view of a larger\n * {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}.\n *\n * This function also supports Node.js {@link Buffer}s.\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([1, 2, 3]);\n *\n * // This is equivalent to:\n * // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n * const dataView = createDataView(bytes);\n * ```\n * @param bytes - The bytes to create the {@link DataView} from.\n * @returns The {@link DataView}.\n */\nexport function createDataView(bytes: Uint8Array): DataView {\n if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {\n const buffer = bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n );\n\n return new DataView(buffer);\n }\n\n return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bytes.js","sourceRoot":"","sources":["../src/bytes.ts"],"names":[],"mappings":";;;AAAA,qCAAkC;AAClC,+BAAgE;AAEhE,2BAA2B;AAC3B,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAExC,2BAA2B;AAC3B,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAIhC;;;;;;;;;;;;;GAaG;AACH,SAAS,8BAA8B;IACrC,6EAA6E;IAC7E,6EAA6E;IAC7E,6EAA6E;IAC7E,eAAe;IACf,MAAM,WAAW,GAAa,EAAE,CAAC;IAEjC,OAAO,GAAG,EAAE;QACV,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;gBAC5B,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;aACnD;SACF;QAED,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,uBAAuB,GAAG,8BAA8B,EAAE,CAAC;AAEjE;;;;;GAKG;AACH,SAAgB,OAAO,CAAC,KAAc;IACpC,OAAO,KAAK,YAAY,UAAU,CAAC;AACrC,CAAC;AAFD,0BAEC;AAED;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,KAAc;IAC1C,IAAA,eAAM,EAAC,OAAO,CAAC,KAAK,CAAC,EAAE,6BAA6B,CAAC,CAAC;AACxD,CAAC;AAFD,sCAEC;AAED;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,KAAiB;IAC1C,aAAa,CAAC,KAAK,CAAC,CAAC;IAErB,IAAI,K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,CAAC;KAC5B;IAED,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;IACzC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAC5D,gEAAgE;QAChE,uEAAuE;QACvE,KAAK,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACvC,MAAM,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;KACtC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AArBD,kCAqBC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,SAAgB,cAAc,CAAC,KAAiB;IAC9C,4EAA4E;IAC5E,qEAAqE;IACrE,eAAe;IACf,iDAAiD;IACjD,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,KAAK,YAAY,MAAM,EAAE;QAC5D,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAC/B,KAAK,CAAC,UAAU,EAChB,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CACpC,CAAC;QAEF,OAAO,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC;KAC7B;IAED,OAAO,IAAI,QAAQ,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;AACxE,CAAC;AAfD,wCAeC","sourcesContent":["import { assert } from './assert';\nimport { add0x, assertIsHexString, Hex, remove0x } from './hex';\n\n// '0'.charCodeAt(0) === 48\nconst HEX_MINIMUM_NUMBER_CHARACTER = 48;\n\n// '9'.charCodeAt(0) === 57\nconst HEX_MAXIMUM_NUMBER_CHARACTER = 58;\nconst HEX_CHARACTER_OFFSET = 87;\n\nexport type Bytes = bigint | number | string | Uint8Array;\n\n/**\n * Memoized function that returns an array to be used as a lookup table for\n * converting bytes to hexadecimal values.\n *\n * The array is created lazily and then cached for future use. The benefit of\n * this approach is that the performance of converting bytes to hex is much\n * better than if we were to call `toString(16)` on each byte.\n *\n * The downside is that the array is created once and then never garbage\n * collected. This is not a problem in practice because the array is only 256\n * elements long.\n *\n * @returns A function that returns the lookup table.\n */\nfunction getPrecomputedHexValuesBuilder(): () => string[] {\n // To avoid issues with tree shaking, we need to use a function to return the\n // array. This is because the array is only used in the `bytesToHex` function\n // and if we were to use a global variable, the array might be removed by the\n // tree shaker.\n const lookupTable: string[] = [];\n\n return () => {\n if (lookupTable.length === 0) {\n for (let i = 0; i < 256; i++) {\n lookupTable.push(i.toString(16).padStart(2, '0'));\n }\n }\n\n return lookupTable;\n };\n}\n\n/**\n * Function implementation of the {@link getPrecomputedHexValuesBuilder}\n * function.\n */\nconst getPrecomputedHexValues = getPrecomputedHexValuesBuilder();\n\n/**\n * Check if a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @returns Whether the value is a `Uint8Array`.\n */\nexport function isBytes(value: unknown): value is Uint8Array {\n return value instanceof Uint8Array;\n}\n\n/**\n * Assert that a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @throws If the value is not a `Uint8Array`.\n */\nexport function assertIsBytes(value: unknown): asserts value is Uint8Array {\n assert(isBytes(value), 'Value must be a Uint8Array.');\n}\n\n/**\n * Convert a `Uint8Array` to a hexadecimal string.\n *\n * @param bytes - The bytes to convert to a hexadecimal string.\n * @returns The hexadecimal string.\n */\nexport function bytesToHex(bytes: Uint8Array): Hex {\n assertIsBytes(bytes);\n\n if (bytes.length === 0) {\n return '0x';\n }\n\n const lookupTable = getPrecomputedHexValues();\n const hexadecimal = new Array(bytes.length);\n\n for (let i = 0; i < bytes.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n hexadecimal[i] = lookupTable[bytes[i]!];\n }\n\n return add0x(hexadecimal.join(''));\n}\n\n/**\n * Convert a `Uint8Array` to a `bigint`.\n *\n * To convert a `Uint8Array` to a `number` instead, use {@link bytesToNumber}.\n * To convert a two's complement encoded `Uint8Array` to a `bigint`, use\n * {@link bytesToSignedBigInt}.\n *\n * @param bytes - The bytes to convert to a `bigint`.\n * @returns The `bigint`.\n */\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n const hexadecimal = bytesToHex(bytes);\n return BigInt(hexadecimal);\n}\n\n/**\n * Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are\n * encoded in two's complement.\n *\n * To convert a `Uint8Array` to an unsigned `bigint` instead, use\n * {@link bytesToBigInt}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param bytes - The bytes to convert to a signed `bigint`.\n * @returns The signed `bigint`.\n */\nexport function bytesToSignedBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n let value = BigInt(0);\n for (const byte of bytes) {\n // eslint-disable-next-line no-bitwise\n value = (value << BigInt(8)) + BigInt(byte);\n }\n\n return BigInt.asIntN(bytes.length * 8, value);\n}\n\n/**\n * Convert a `Uint8Array` to a `number`.\n *\n * To convert a `Uint8Array` to a `bigint` instead, use {@link bytesToBigInt}.\n *\n * @param bytes - The bytes to convert to a number.\n * @returns The number.\n * @throws If the resulting number is not a safe integer.\n */\nexport function bytesToNumber(bytes: Uint8Array): number {\n assertIsBytes(bytes);\n\n const bigint = bytesToBigInt(bytes);\n\n assert(\n bigint <= BigInt(Number.MAX_SAFE_INTEGER),\n 'Number is not a safe integer. Use `bytesToBigInt` instead.',\n );\n\n return Number(bigint);\n}\n\n/**\n * Convert a UTF-8 encoded `Uint8Array` to a `string`.\n *\n * @param bytes - The bytes to convert to a string.\n * @returns The string.\n */\nexport function bytesToString(bytes: Uint8Array): string {\n assertIsBytes(bytes);\n\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be\n * prefixed with `0x`. It accepts even and odd length strings.\n *\n * If the value is \"0x\", an empty `Uint8Array` is returned.\n *\n * @param value - The hexadecimal string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function hexToBytes(value: string): Uint8Array {\n // \"0x\" is often used as empty byte array.\n if (value?.toLowerCase?.() === '0x') {\n return new Uint8Array();\n }\n\n assertIsHexString(value);\n\n // Remove the `0x` prefix if it exists, and pad the string to have an even\n // number of characters.\n const strippedValue = remove0x(value).toLowerCase();\n const normalizedValue =\n strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;\n const bytes = new Uint8Array(normalizedValue.length / 2);\n\n for (let i = 0; i < bytes.length; i++) {\n // While this is not the prettiest way to convert a hexadecimal string to a\n // `Uint8Array`, it is a lot faster than using `parseInt` to convert each\n // character.\n const c1 = normalizedValue.charCodeAt(i * 2);\n const c2 = normalizedValue.charCodeAt(i * 2 + 1);\n const n1 =\n c1 -\n (c1 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n const n2 =\n c2 -\n (c2 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n\n bytes[i] = n1 * 16 + n2;\n }\n\n return bytes;\n}\n\n/**\n * Convert a `bigint` to a `Uint8Array`.\n *\n * This assumes that the `bigint` is an unsigned integer. To convert a signed\n * `bigint` instead, use {@link signedBigIntToBytes}.\n *\n * @param value - The bigint to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function bigIntToBytes(value: bigint): Uint8Array {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= BigInt(0), 'Value must be a non-negative bigint.');\n\n const hexadecimal = value.toString(16);\n return hexToBytes(hexadecimal);\n}\n\n/**\n * Check if a `bigint` fits in a certain number of bytes.\n *\n * @param value - The `bigint` to check.\n * @param bytes - The number of bytes.\n * @returns Whether the `bigint` fits in the number of bytes.\n */\nfunction bigIntFits(value: bigint, bytes: number): boolean {\n assert(bytes > 0);\n\n /* eslint-disable no-bitwise */\n const mask = value >> BigInt(31);\n return !(((~value & mask) + (value & ~mask)) >> BigInt(bytes * 8 + ~0));\n /* eslint-enable no-bitwise */\n}\n\n/**\n * Convert a signed `bigint` to a `Uint8Array`. This uses two's complement\n * encoding to represent negative numbers.\n *\n * To convert an unsigned `bigint` to a `Uint8Array` instead, use\n * {@link bigIntToBytes}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param value - The number to convert to bytes.\n * @param byteLength - The length of the resulting `Uint8Array`. If the number\n * is larger than the maximum value that can be represented by the given length,\n * an error is thrown.\n * @returns The bytes as `Uint8Array`.\n */\nexport function signedBigIntToBytes(\n value: bigint,\n byteLength: number,\n): Uint8Array {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(typeof byteLength === 'number', 'Byte length must be a number.');\n assert(byteLength > 0, 'Byte length must be greater than 0.');\n assert(\n bigIntFits(value, byteLength),\n 'Byte length is too small to represent the given value.',\n );\n\n // ESLint doesn't like mutating function parameters, so to avoid having to\n // disable the rule, we create a new variable.\n let numberValue = value;\n const bytes = new Uint8Array(byteLength);\n\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number(BigInt.asUintN(8, numberValue));\n // eslint-disable-next-line no-bitwise\n numberValue >>= BigInt(8);\n }\n\n return bytes.reverse();\n}\n\n/**\n * Convert a `number` to a `Uint8Array`.\n *\n * @param value - The number to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n * @throws If the number is not a safe integer.\n */\nexport function numberToBytes(value: number): Uint8Array {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToBytes` instead.',\n );\n\n const hexadecimal = value.toString(16);\n return hexToBytes(hexadecimal);\n}\n\n/**\n * Convert a `string` to a UTF-8 encoded `Uint8Array`.\n *\n * @param value - The string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function stringToBytes(value: string): Uint8Array {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return new TextEncoder().encode(value);\n}\n\n/**\n * Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,\n * a `bigint`, a `number`, or a `string`.\n *\n * This will attempt to guess the type of the value based on its type and\n * contents. For more control over the conversion, use the more specific\n * conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.\n *\n * If the value is a `string`, and it is prefixed with `0x`, it will be\n * interpreted as a hexadecimal string. Otherwise, it will be interpreted as a\n * UTF-8 string. To convert a hexadecimal string to bytes without interpreting\n * it as a UTF-8 string, use {@link hexToBytes} instead.\n *\n * If the value is a `bigint`, it is assumed to be unsigned. To convert a signed\n * `bigint` to bytes, use {@link signedBigIntToBytes} instead.\n *\n * If the value is a `Uint8Array`, it will be returned as-is.\n *\n * @param value - The value to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function valueToBytes(value: Bytes): Uint8Array {\n if (typeof value === 'bigint') {\n return bigIntToBytes(value);\n }\n\n if (typeof value === 'number') {\n return numberToBytes(value);\n }\n\n if (typeof value === 'string') {\n if (value.startsWith('0x')) {\n return hexToBytes(value);\n }\n\n return stringToBytes(value);\n }\n\n if (isBytes(value)) {\n return value;\n }\n\n throw new TypeError(`Unsupported value type: \"${typeof value}\".`);\n}\n\n/**\n * Concatenate multiple byte-like values into a single `Uint8Array`. The values\n * can be `Uint8Array`, `bigint`, `number`, or `string`. This uses\n * {@link valueToBytes} under the hood to convert each value to bytes. Refer to\n * the documentation of that function for more information.\n *\n * @param values - The values to concatenate.\n * @returns The concatenated bytes as `Uint8Array`.\n */\nexport function concatBytes(values: Bytes[]): Uint8Array {\n const normalizedValues = new Array(values.length);\n let byteLength = 0;\n\n for (let i = 0; i < values.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const value = valueToBytes(values[i]!);\n\n normalizedValues[i] = value;\n byteLength += value.length;\n }\n\n const bytes = new Uint8Array(byteLength);\n for (let i = 0, offset = 0; i < normalizedValues.length; i++) {\n // While we could simply spread the values into an array and use\n // `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`.\n bytes.set(normalizedValues[i], offset);\n offset += normalizedValues[i].length;\n }\n\n return bytes;\n}\n\n/**\n * Create a {@link DataView} from a {@link Uint8Array}. This is a convenience\n * function that avoids having to create a {@link DataView} manually, which\n * requires passing the `byteOffset` and `byteLength` parameters every time.\n *\n * Not passing the `byteOffset` and `byteLength` parameters can result in\n * unexpected behavior when the {@link Uint8Array} is a view of a larger\n * {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}.\n *\n * This function also supports Node.js {@link Buffer}s.\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([1, 2, 3]);\n *\n * // This is equivalent to:\n * // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n * const dataView = createDataView(bytes);\n * ```\n * @param bytes - The bytes to create the {@link DataView} from.\n * @returns The {@link DataView}.\n */\nexport function createDataView(bytes: Uint8Array): DataView {\n // To maintain compatibility with Node.js, we need to check if the bytes are\n // a Buffer. If so, we need to slice the buffer to get the underlying\n // ArrayBuffer.\n // eslint-disable-next-line no-restricted-globals\n if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {\n const buffer = bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n );\n\n return new DataView(buffer);\n }\n\n return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const ChecksumStruct: import("superstruct").Struct<string, null>;
|
package/dist/checksum.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ChecksumStruct = void 0;
|
|
4
|
+
const superstruct_1 = require("superstruct");
|
|
5
|
+
const base64_1 = require("./base64");
|
|
6
|
+
exports.ChecksumStruct = (0, superstruct_1.size)((0, base64_1.base64)((0, superstruct_1.string)(), { paddingRequired: true }), 44, 44);
|
|
7
|
+
//# sourceMappingURL=checksum.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checksum.js","sourceRoot":"","sources":["../src/checksum.ts"],"names":[],"mappings":";;;AAAA,6CAA2C;AAE3C,qCAAkC;AAErB,QAAA,cAAc,GAAG,IAAA,kBAAI,EAChC,IAAA,eAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,EAC3C,EAAE,EACF,EAAE,CACH,CAAC","sourcesContent":["import { size, string } from 'superstruct';\n\nimport { base64 } from './base64';\n\nexport const ChecksumStruct = size(\n base64(string(), { paddingRequired: true }),\n 44,\n 44,\n);\n"]}
|
package/dist/coercers.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createHex = exports.createBytes = exports.createBigInt = exports.createNumber = void 0;
|
|
4
4
|
const superstruct_1 = require("superstruct");
|
|
5
|
-
const hex_1 = require("./hex");
|
|
6
5
|
const assert_1 = require("./assert");
|
|
7
6
|
const bytes_1 = require("./bytes");
|
|
7
|
+
const hex_1 = require("./hex");
|
|
8
8
|
const NumberLikeStruct = (0, superstruct_1.union)([(0, superstruct_1.number)(), (0, superstruct_1.bigint)(), (0, superstruct_1.string)(), hex_1.StrictHexStruct]);
|
|
9
9
|
const NumberCoercer = (0, superstruct_1.coerce)((0, superstruct_1.number)(), NumberLikeStruct, Number);
|
|
10
10
|
const BigIntCoercer = (0, superstruct_1.coerce)((0, superstruct_1.bigint)(), NumberLikeStruct, BigInt);
|
|
@@ -81,7 +81,7 @@ function createBigInt(value) {
|
|
|
81
81
|
}
|
|
82
82
|
catch (error) {
|
|
83
83
|
if (error instanceof superstruct_1.StructError) {
|
|
84
|
-
throw new Error(`Expected a number-like value, got "${error.value}".`);
|
|
84
|
+
throw new Error(`Expected a number-like value, got "${String(error.value)}".`);
|
|
85
85
|
}
|
|
86
86
|
/* istanbul ignore next */
|
|
87
87
|
throw error;
|
|
@@ -116,7 +116,7 @@ function createBytes(value) {
|
|
|
116
116
|
}
|
|
117
117
|
catch (error) {
|
|
118
118
|
if (error instanceof superstruct_1.StructError) {
|
|
119
|
-
throw new Error(`Expected a bytes-like value, got "${error.value}".`);
|
|
119
|
+
throw new Error(`Expected a bytes-like value, got "${String(error.value)}".`);
|
|
120
120
|
}
|
|
121
121
|
/* istanbul ignore next */
|
|
122
122
|
throw error;
|
|
@@ -152,7 +152,7 @@ function createHex(value) {
|
|
|
152
152
|
}
|
|
153
153
|
catch (error) {
|
|
154
154
|
if (error instanceof superstruct_1.StructError) {
|
|
155
|
-
throw new Error(`Expected a bytes-like value, got "${error.value}".`);
|
|
155
|
+
throw new Error(`Expected a bytes-like value, got "${String(error.value)}".`);
|
|
156
156
|
}
|
|
157
157
|
/* istanbul ignore next */
|
|
158
158
|
throw error;
|
package/dist/coercers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coercers.js","sourceRoot":"","sources":["../src/coercers.ts"],"names":[],"mappings":";;;AAAA,6CAUqB;
|
|
1
|
+
{"version":3,"file":"coercers.js","sourceRoot":"","sources":["../src/coercers.ts"],"names":[],"mappings":";;;AAAA,6CAUqB;AAErB,qCAAkC;AAClC,mCAAiD;AACjD,+BAA6C;AAE7C,MAAM,gBAAgB,GAAG,IAAA,mBAAK,EAAC,CAAC,IAAA,oBAAM,GAAE,EAAE,IAAA,oBAAM,GAAE,EAAE,IAAA,oBAAM,GAAE,EAAE,qBAAe,CAAC,CAAC,CAAC;AAChF,MAAM,aAAa,GAAG,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,gBAAgB,EAAE,MAAM,CAAC,CAAC;AACjE,MAAM,aAAa,GAAG,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,gBAAgB,EAAE,MAAM,CAAC,CAAC;AAEjE,M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ACb;AACH,CAAC;AAfD,oCAeC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,WAAW,CAAC,KAAgB;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;QAC7D,OAAO,IAAI,UAAU,EAAE,CAAC;KACzB;IAED,IAAI;QACF,OAAO,IAAA,oBAAM,EAAC,KAAK,EAAE,YAAY,CAAC,CAAC;KACpC;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,YAAY,yBAAW,EAAE;YAChC,MAAM,IAAI,KAAK,CACb,qCAAqC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAC7D,CAAC;SACH;QAED,0BAA0B;QAC1B,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAjBD,kCAiBC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAgB,SAAS,CAAC,KAAgB;IACxC,IACE,CAAC,KAAK,YAAY,UAAU,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC;QACnD,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,IAAI,CAAC,EAC3D;QACA,OAAO,IAAI,CAAC;KACb;IAED,IAAI;QACF,OAAO,IAAA,oBAAM,EAAC,KAAK,EAAE,UAAU,CAAC,CAAC;KAClC;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,KAAK,YAAY,yBAAW,EAAE;YAChC,MAAM,IAAI,KAAK,CACb,qCAAqC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAC7D,CAAC;SACH;QAED,0BAA0B;QAC1B,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AApBD,8BAoBC","sourcesContent":["import {\n bigint,\n coerce,\n create,\n Infer,\n instance,\n number,\n string,\n StructError,\n union,\n} from 'superstruct';\n\nimport { assert } from './assert';\nimport { bytesToHex, hexToBytes } from './bytes';\nimport { Hex, StrictHexStruct } from './hex';\n\nconst NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);\nconst NumberCoercer = coerce(number(), NumberLikeStruct, Number);\nconst BigIntCoercer = coerce(bigint(), NumberLikeStruct, BigInt);\n\nconst BytesLikeStruct = union([StrictHexStruct, instance(Uint8Array)]);\nconst BytesCoercer = coerce(\n instance(Uint8Array),\n union([StrictHexStruct]),\n hexToBytes,\n);\n\nconst HexCoercer = coerce(StrictHexStruct, instance(Uint8Array), bytesToHex);\n\nexport type NumberLike = Infer<typeof NumberLikeStruct>;\nexport type BytesLike = Infer<typeof BytesLikeStruct>;\n\n/**\n * Create a number from a number-like value.\n *\n * - If the value is a number, it is returned as-is.\n * - If the value is a `bigint`, it is converted to a number.\n * - If the value is a string, it is interpreted as a decimal number.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number.\n *\n * This validates that the value is a number-like value, and that the resulting\n * number is not `NaN` or `Infinity`.\n *\n * @example\n * ```typescript\n * const value = createNumber('0x010203');\n * console.log(value); // 66051\n *\n * const otherValue = createNumber(123n);\n * console.log(otherValue); // 123\n * ```\n * @param value - The value to create the number from.\n * @returns The created number.\n * @throws If the value is not a number-like value, or if the resulting number\n * is `NaN` or `Infinity`.\n */\nexport function createNumber(value: NumberLike): number {\n try {\n const result = create(value, NumberCoercer);\n\n assert(\n Number.isFinite(result),\n `Expected a number-like value, got \"${value}\".`,\n );\n\n return result;\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(`Expected a number-like value, got \"${value}\".`);\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a `bigint` from a number-like value.\n *\n * - If the value is a number, it is converted to a `bigint`.\n * - If the value is a `bigint`, it is returned as-is.\n * - If the value is a string, it is interpreted as a decimal number and\n * converted to a `bigint`.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number and converted to a `bigint`.\n *\n * @example\n * ```typescript\n * const value = createBigInt('0x010203');\n * console.log(value); // 16909060n\n *\n * const otherValue = createBigInt(123);\n * console.log(otherValue); // 123n\n * ```\n * @param value - The value to create the bigint from.\n * @returns The created bigint.\n * @throws If the value is not a number-like value.\n */\nexport function createBigInt(value: NumberLike): bigint {\n try {\n // The `BigInt` constructor throws if the value is not a number-like value.\n // There is no need to validate the value manually.\n return create(value, BigIntCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a number-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a byte array from a bytes-like value.\n *\n * - If the value is a byte array, it is returned as-is.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is interpreted\n * as a hexadecimal number and converted to a byte array.\n *\n * @example\n * ```typescript\n * const value = createBytes('0x010203');\n * console.log(value); // Uint8Array [ 1, 2, 3 ]\n *\n * const otherValue = createBytes('0x010203');\n * console.log(otherValue); // Uint8Array [ 1, 2, 3 ]\n * ```\n * @param value - The value to create the byte array from.\n * @returns The created byte array.\n * @throws If the value is not a bytes-like value.\n */\nexport function createBytes(value: BytesLike): Uint8Array {\n if (typeof value === 'string' && value.toLowerCase() === '0x') {\n return new Uint8Array();\n }\n\n try {\n return create(value, BytesCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a hexadecimal string from a bytes-like value.\n *\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is returned\n * as-is.\n * - If the value is a `Uint8Array`, it is converted to a hex string.\n *\n * @example\n * ```typescript\n * const value = createHex(new Uint8Array([1, 2, 3]));\n * console.log(value); // '0x010203'\n *\n * const otherValue = createHex('0x010203');\n * console.log(otherValue); // '0x010203'\n * ```\n * @param value - The value to create the hex string from.\n * @returns The created hex string.\n * @throws If the value is not a bytes-like value.\n */\nexport function createHex(value: BytesLike): Hex {\n if (\n (value instanceof Uint8Array && value.length === 0) ||\n (typeof value === 'string' && value.toLowerCase() === '0x')\n ) {\n return '0x';\n }\n\n try {\n return create(value, HexCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n"]}
|
package/dist/hex.d.ts
CHANGED
|
@@ -36,15 +36,15 @@ export declare function assertIsStrictHexString(value: unknown): asserts value i
|
|
|
36
36
|
* Add the `0x`-prefix to a hexadecimal string. If the string already has the
|
|
37
37
|
* prefix, it is returned as-is.
|
|
38
38
|
*
|
|
39
|
-
* @param
|
|
39
|
+
* @param hexadecimal - The hexadecimal string to add the prefix to.
|
|
40
40
|
* @returns The prefixed hexadecimal string.
|
|
41
41
|
*/
|
|
42
|
-
export declare function add0x(
|
|
42
|
+
export declare function add0x(hexadecimal: string): Hex;
|
|
43
43
|
/**
|
|
44
44
|
* Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have
|
|
45
45
|
* the prefix, it is returned as-is.
|
|
46
46
|
*
|
|
47
|
-
* @param
|
|
47
|
+
* @param hexadecimal - The hexadecimal string to remove the prefix from.
|
|
48
48
|
* @returns The un-prefixed hexadecimal string.
|
|
49
49
|
*/
|
|
50
|
-
export declare function remove0x(
|
|
50
|
+
export declare function remove0x(hexadecimal: string): string;
|
package/dist/hex.js
CHANGED
|
@@ -51,31 +51,31 @@ exports.assertIsStrictHexString = assertIsStrictHexString;
|
|
|
51
51
|
* Add the `0x`-prefix to a hexadecimal string. If the string already has the
|
|
52
52
|
* prefix, it is returned as-is.
|
|
53
53
|
*
|
|
54
|
-
* @param
|
|
54
|
+
* @param hexadecimal - The hexadecimal string to add the prefix to.
|
|
55
55
|
* @returns The prefixed hexadecimal string.
|
|
56
56
|
*/
|
|
57
|
-
function add0x(
|
|
58
|
-
if (
|
|
59
|
-
return
|
|
57
|
+
function add0x(hexadecimal) {
|
|
58
|
+
if (hexadecimal.startsWith('0x')) {
|
|
59
|
+
return hexadecimal;
|
|
60
60
|
}
|
|
61
|
-
if (
|
|
62
|
-
return `0x${
|
|
61
|
+
if (hexadecimal.startsWith('0X')) {
|
|
62
|
+
return `0x${hexadecimal.substring(2)}`;
|
|
63
63
|
}
|
|
64
|
-
return `0x${
|
|
64
|
+
return `0x${hexadecimal}`;
|
|
65
65
|
}
|
|
66
66
|
exports.add0x = add0x;
|
|
67
67
|
/**
|
|
68
68
|
* Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have
|
|
69
69
|
* the prefix, it is returned as-is.
|
|
70
70
|
*
|
|
71
|
-
* @param
|
|
71
|
+
* @param hexadecimal - The hexadecimal string to remove the prefix from.
|
|
72
72
|
* @returns The un-prefixed hexadecimal string.
|
|
73
73
|
*/
|
|
74
|
-
function remove0x(
|
|
75
|
-
if (
|
|
76
|
-
return
|
|
74
|
+
function remove0x(hexadecimal) {
|
|
75
|
+
if (hexadecimal.startsWith('0x') || hexadecimal.startsWith('0X')) {
|
|
76
|
+
return hexadecimal.substring(2);
|
|
77
77
|
}
|
|
78
|
-
return
|
|
78
|
+
return hexadecimal;
|
|
79
79
|
}
|
|
80
80
|
exports.remove0x = remove0x;
|
|
81
81
|
//# sourceMappingURL=hex.js.map
|
package/dist/hex.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hex.js","sourceRoot":"","sources":["../src/hex.ts"],"names":[],"mappings":";;;AAAA,6CAA0D;
|
|
1
|
+
{"version":3,"file":"hex.js","sourceRoot":"","sources":["../src/hex.ts"],"names":[],"mappings":";;;AAAA,6CAA0D;AAE1D,qCAAkC;AAIrB,QAAA,SAAS,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,sBAAsB,CAAC,CAAC;AACtD,QAAA,eAAe,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,iBAAiB,CAGjE,CAAC;AAEF;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,iBAAS,CAAC,CAAC;AAC9B,CAAC;AAFD,kCAEC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,uBAAe,CAAC,CAAC;AACpC,CAAC;AAFD,8CAEC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,KAAc;IAC9C,IAAA,eAAM,EAAC,WAAW,CAAC,KAAK,CAAC,EAAE,qCAAqC,CAAC,CAAC;AACpE,CAAC;AAFD,8CAEC;AAED;;;;;;GAMG;AACH,SAAgB,uBAAuB,CAAC,KAAc;IACpD,IAAA,eAAM,EACJ,iBAAiB,CAAC,KAAK,CAAC,EACxB,yDAAyD,CAC1D,CAAC;AACJ,CAAC;AALD,0DAKC;AAED;;;;;;GAMG;AACH,SAAgB,KAAK,CAAC,WAAmB;IACvC,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAChC,OAAO,WAAkB,CAAC;KAC3B;IAED,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAChC,OAAO,KAAK,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;KACxC;IAED,OAAO,KAAK,WAAW,EAAE,CAAC;AAC5B,CAAC;AAVD,sBAUC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,WAAmB;IAC1C,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAChE,OAAO,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;KACjC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AAND,4BAMC","sourcesContent":["import { is, pattern, string, Struct } from 'superstruct';\n\nimport { assert } from './assert';\n\nexport type Hex = `0x${string}`;\n\nexport const HexStruct = pattern(string(), /^(?:0x)?[0-9a-f]+$/iu);\nexport const StrictHexStruct = pattern(string(), /^0x[0-9a-f]+$/iu) as Struct<\n Hex,\n null\n>;\n\n/**\n * Check if a string is a valid hex string.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex string.\n */\nexport function isHexString(value: unknown): value is string {\n return is(value, HexStruct);\n}\n\n/**\n * Strictly check if a string is a valid hex string. A valid hex string must\n * start with the \"0x\"-prefix.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex string.\n */\nexport function isStrictHexString(value: unknown): value is Hex {\n return is(value, StrictHexStruct);\n}\n\n/**\n * Assert that a value is a valid hex string.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid hex string.\n */\nexport function assertIsHexString(value: unknown): asserts value is string {\n assert(isHexString(value), 'Value must be a hexadecimal string.');\n}\n\n/**\n * Assert that a value is a valid hex string. A valid hex string must start with\n * the \"0x\"-prefix.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid hex string.\n */\nexport function assertIsStrictHexString(value: unknown): asserts value is Hex {\n assert(\n isStrictHexString(value),\n 'Value must be a hexadecimal string, starting with \"0x\".',\n );\n}\n\n/**\n * Add the `0x`-prefix to a hexadecimal string. If the string already has the\n * prefix, it is returned as-is.\n *\n * @param hexadecimal - The hexadecimal string to add the prefix to.\n * @returns The prefixed hexadecimal string.\n */\nexport function add0x(hexadecimal: string): Hex {\n if (hexadecimal.startsWith('0x')) {\n return hexadecimal as Hex;\n }\n\n if (hexadecimal.startsWith('0X')) {\n return `0x${hexadecimal.substring(2)}`;\n }\n\n return `0x${hexadecimal}`;\n}\n\n/**\n * Remove the `0x`-prefix from a hexadecimal string. If the string doesn't have\n * the prefix, it is returned as-is.\n *\n * @param hexadecimal - The hexadecimal string to remove the prefix from.\n * @returns The un-prefixed hexadecimal string.\n */\nexport function remove0x(hexadecimal: string): string {\n if (hexadecimal.startsWith('0x') || hexadecimal.startsWith('0X')) {\n return hexadecimal.substring(2);\n }\n\n return hexadecimal;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export * from './assert';
|
|
2
|
+
export * from './base64';
|
|
2
3
|
export * from './bytes';
|
|
4
|
+
export * from './checksum';
|
|
3
5
|
export * from './coercers';
|
|
4
6
|
export * from './collections';
|
|
5
7
|
export * from './hex';
|
|
@@ -7,4 +9,6 @@ export * from './json';
|
|
|
7
9
|
export * from './logging';
|
|
8
10
|
export * from './misc';
|
|
9
11
|
export * from './number';
|
|
12
|
+
export * from './opaque';
|
|
10
13
|
export * from './time';
|
|
14
|
+
export * from './versions';
|
package/dist/index.js
CHANGED
|
@@ -15,7 +15,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./assert"), exports);
|
|
18
|
+
__exportStar(require("./base64"), exports);
|
|
18
19
|
__exportStar(require("./bytes"), exports);
|
|
20
|
+
__exportStar(require("./checksum"), exports);
|
|
19
21
|
__exportStar(require("./coercers"), exports);
|
|
20
22
|
__exportStar(require("./collections"), exports);
|
|
21
23
|
__exportStar(require("./hex"), exports);
|
|
@@ -23,5 +25,7 @@ __exportStar(require("./json"), exports);
|
|
|
23
25
|
__exportStar(require("./logging"), exports);
|
|
24
26
|
__exportStar(require("./misc"), exports);
|
|
25
27
|
__exportStar(require("./number"), exports);
|
|
28
|
+
__exportStar(require("./opaque"), exports);
|
|
26
29
|
__exportStar(require("./time"), exports);
|
|
30
|
+
__exportStar(require("./versions"), exports);
|
|
27
31
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,0CAAwB;AACxB,6CAA2B;AAC3B,gDAA8B;AAC9B,wCAAsB;AACtB,yCAAuB;AACvB,4CAA0B;AAC1B,yCAAuB;AACvB,2CAAyB;AACzB,yCAAuB","sourcesContent":["export * from './assert';\nexport * from './bytes';\nexport * from './coercers';\nexport * from './collections';\nexport * from './hex';\nexport * from './json';\nexport * from './logging';\nexport * from './misc';\nexport * from './number';\nexport * from './time';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,2CAAyB;AACzB,0CAAwB;AACxB,6CAA2B;AAC3B,6CAA2B;AAC3B,gDAA8B;AAC9B,wCAAsB;AACtB,yCAAuB;AACvB,4CAA0B;AAC1B,yCAAuB;AACvB,2CAAyB;AACzB,2CAAyB;AACzB,yCAAuB;AACvB,6CAA2B","sourcesContent":["export * from './assert';\nexport * from './base64';\nexport * from './bytes';\nexport * from './checksum';\nexport * from './coercers';\nexport * from './collections';\nexport * from './hex';\nexport * from './json';\nexport * from './logging';\nexport * from './misc';\nexport * from './number';\nexport * from './opaque';\nexport * from './time';\nexport * from './versions';\n"]}
|
package/dist/json.d.ts
CHANGED
|
@@ -69,7 +69,7 @@ export declare const JsonRpcRequestStruct: Struct<{
|
|
|
69
69
|
method: Struct<string, null>;
|
|
70
70
|
params: Struct<Record<string, Json> | Json[] | undefined, null>;
|
|
71
71
|
}>;
|
|
72
|
-
export declare type InferWithParams<Type extends Struct<any
|
|
72
|
+
export declare type InferWithParams<Type extends Struct<any>, Params extends JsonRpcParams> = Omit<Infer<Type>, 'params'> & (keyof Params extends undefined ? {
|
|
73
73
|
params?: Params;
|
|
74
74
|
} : {
|
|
75
75
|
params: Params;
|
|
@@ -77,7 +77,7 @@ export declare type InferWithParams<Type extends Struct<any, unknown>, Params ex
|
|
|
77
77
|
/**
|
|
78
78
|
* A JSON-RPC request object.
|
|
79
79
|
*/
|
|
80
|
-
export declare type JsonRpcRequest<Params extends JsonRpcParams> = InferWithParams<typeof JsonRpcRequestStruct, Params>;
|
|
80
|
+
export declare type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> = InferWithParams<typeof JsonRpcRequestStruct, Params>;
|
|
81
81
|
export declare const JsonRpcNotificationStruct: Struct<{
|
|
82
82
|
method: string;
|
|
83
83
|
jsonrpc: "2.0";
|
|
@@ -91,7 +91,7 @@ export declare const JsonRpcNotificationStruct: Struct<{
|
|
|
91
91
|
/**
|
|
92
92
|
* A JSON-RPC notification object.
|
|
93
93
|
*/
|
|
94
|
-
export declare type JsonRpcNotification<Params extends JsonRpcParams> = InferWithParams<typeof JsonRpcNotificationStruct, Params>;
|
|
94
|
+
export declare type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> = InferWithParams<typeof JsonRpcNotificationStruct, Params>;
|
|
95
95
|
/**
|
|
96
96
|
* Check if the given value is a valid {@link JsonRpcNotification} object.
|
|
97
97
|
*
|
|
@@ -99,7 +99,7 @@ export declare type JsonRpcNotification<Params extends JsonRpcParams> = InferWit
|
|
|
99
99
|
* @returns Whether the given value is a valid {@link JsonRpcNotification}
|
|
100
100
|
* object.
|
|
101
101
|
*/
|
|
102
|
-
export declare function isJsonRpcNotification(value: unknown): value is JsonRpcNotification
|
|
102
|
+
export declare function isJsonRpcNotification(value: unknown): value is JsonRpcNotification;
|
|
103
103
|
/**
|
|
104
104
|
* Assert that the given value is a valid {@link JsonRpcNotification} object.
|
|
105
105
|
*
|
|
@@ -108,14 +108,14 @@ export declare function isJsonRpcNotification(value: unknown): value is JsonRpcN
|
|
|
108
108
|
* Defaults to {@link AssertionError}.
|
|
109
109
|
* @throws If the given value is not a valid {@link JsonRpcNotification} object.
|
|
110
110
|
*/
|
|
111
|
-
export declare function assertIsJsonRpcNotification(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is JsonRpcNotification
|
|
111
|
+
export declare function assertIsJsonRpcNotification(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is JsonRpcNotification;
|
|
112
112
|
/**
|
|
113
113
|
* Check if the given value is a valid {@link JsonRpcRequest} object.
|
|
114
114
|
*
|
|
115
115
|
* @param value - The value to check.
|
|
116
116
|
* @returns Whether the given value is a valid {@link JsonRpcRequest} object.
|
|
117
117
|
*/
|
|
118
|
-
export declare function isJsonRpcRequest(value: unknown): value is JsonRpcRequest
|
|
118
|
+
export declare function isJsonRpcRequest(value: unknown): value is JsonRpcRequest;
|
|
119
119
|
/**
|
|
120
120
|
* Assert that the given value is a valid {@link JsonRpcRequest} object.
|
|
121
121
|
*
|
|
@@ -124,7 +124,7 @@ export declare function isJsonRpcRequest(value: unknown): value is JsonRpcReques
|
|
|
124
124
|
* Defaults to {@link AssertionError}.
|
|
125
125
|
* @throws If the given value is not a valid {@link JsonRpcRequest} object.
|
|
126
126
|
*/
|
|
127
|
-
export declare function assertIsJsonRpcRequest(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is JsonRpcRequest
|
|
127
|
+
export declare function assertIsJsonRpcRequest(value: unknown, ErrorWrapper?: AssertionErrorConstructor): asserts value is JsonRpcRequest;
|
|
128
128
|
export declare const PendingJsonRpcResponseStruct: Struct<{
|
|
129
129
|
id: string | number | null;
|
|
130
130
|
jsonrpc: "2.0";
|
package/dist/json.js
CHANGED
|
@@ -61,7 +61,9 @@ exports.isJsonRpcNotification = isJsonRpcNotification;
|
|
|
61
61
|
* Defaults to {@link AssertionError}.
|
|
62
62
|
* @throws If the given value is not a valid {@link JsonRpcNotification} object.
|
|
63
63
|
*/
|
|
64
|
-
function assertIsJsonRpcNotification(value,
|
|
64
|
+
function assertIsJsonRpcNotification(value,
|
|
65
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
66
|
+
ErrorWrapper) {
|
|
65
67
|
(0, assert_1.assertStruct)(value, exports.JsonRpcNotificationStruct, 'Invalid JSON-RPC notification', ErrorWrapper);
|
|
66
68
|
}
|
|
67
69
|
exports.assertIsJsonRpcNotification = assertIsJsonRpcNotification;
|
|
@@ -83,7 +85,9 @@ exports.isJsonRpcRequest = isJsonRpcRequest;
|
|
|
83
85
|
* Defaults to {@link AssertionError}.
|
|
84
86
|
* @throws If the given value is not a valid {@link JsonRpcRequest} object.
|
|
85
87
|
*/
|
|
86
|
-
function assertIsJsonRpcRequest(value,
|
|
88
|
+
function assertIsJsonRpcRequest(value,
|
|
89
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
90
|
+
ErrorWrapper) {
|
|
87
91
|
(0, assert_1.assertStruct)(value, exports.JsonRpcRequestStruct, 'Invalid JSON-RPC request', ErrorWrapper);
|
|
88
92
|
}
|
|
89
93
|
exports.assertIsJsonRpcRequest = assertIsJsonRpcRequest;
|
|
@@ -127,7 +131,9 @@ exports.isPendingJsonRpcResponse = isPendingJsonRpcResponse;
|
|
|
127
131
|
* @throws If the given value is not a valid {@link PendingJsonRpcResponse}
|
|
128
132
|
* object.
|
|
129
133
|
*/
|
|
130
|
-
function assertIsPendingJsonRpcResponse(response,
|
|
134
|
+
function assertIsPendingJsonRpcResponse(response,
|
|
135
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
136
|
+
ErrorWrapper) {
|
|
131
137
|
(0, assert_1.assertStruct)(response, exports.PendingJsonRpcResponseStruct, 'Invalid pending JSON-RPC response', ErrorWrapper);
|
|
132
138
|
}
|
|
133
139
|
exports.assertIsPendingJsonRpcResponse = assertIsPendingJsonRpcResponse;
|
|
@@ -149,7 +155,9 @@ exports.isJsonRpcResponse = isJsonRpcResponse;
|
|
|
149
155
|
* Defaults to {@link AssertionError}.
|
|
150
156
|
* @throws If the given value is not a valid {@link JsonRpcResponse} object.
|
|
151
157
|
*/
|
|
152
|
-
function assertIsJsonRpcResponse(value,
|
|
158
|
+
function assertIsJsonRpcResponse(value,
|
|
159
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
160
|
+
ErrorWrapper) {
|
|
153
161
|
(0, assert_1.assertStruct)(value, exports.JsonRpcResponseStruct, 'Invalid JSON-RPC response', ErrorWrapper);
|
|
154
162
|
}
|
|
155
163
|
exports.assertIsJsonRpcResponse = assertIsJsonRpcResponse;
|
|
@@ -171,7 +179,9 @@ exports.isJsonRpcSuccess = isJsonRpcSuccess;
|
|
|
171
179
|
* Defaults to {@link AssertionError}.
|
|
172
180
|
* @throws If the given value is not a valid {@link JsonRpcSuccess} object.
|
|
173
181
|
*/
|
|
174
|
-
function assertIsJsonRpcSuccess(value,
|
|
182
|
+
function assertIsJsonRpcSuccess(value,
|
|
183
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
184
|
+
ErrorWrapper) {
|
|
175
185
|
(0, assert_1.assertStruct)(value, exports.JsonRpcSuccessStruct, 'Invalid JSON-RPC success response', ErrorWrapper);
|
|
176
186
|
}
|
|
177
187
|
exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess;
|
|
@@ -193,7 +203,9 @@ exports.isJsonRpcFailure = isJsonRpcFailure;
|
|
|
193
203
|
* Defaults to {@link AssertionError}.
|
|
194
204
|
* @throws If the given value is not a valid {@link JsonRpcFailure} object.
|
|
195
205
|
*/
|
|
196
|
-
function assertIsJsonRpcFailure(value,
|
|
206
|
+
function assertIsJsonRpcFailure(value,
|
|
207
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
208
|
+
ErrorWrapper) {
|
|
197
209
|
(0, assert_1.assertStruct)(value, exports.JsonRpcFailureStruct, 'Invalid JSON-RPC failure response', ErrorWrapper);
|
|
198
210
|
}
|
|
199
211
|
exports.assertIsJsonRpcFailure = assertIsJsonRpcFailure;
|
|
@@ -215,7 +227,9 @@ exports.isJsonRpcError = isJsonRpcError;
|
|
|
215
227
|
* Defaults to {@link AssertionError}.
|
|
216
228
|
* @throws If the given value is not a valid {@link JsonRpcError} object.
|
|
217
229
|
*/
|
|
218
|
-
function assertIsJsonRpcError(value,
|
|
230
|
+
function assertIsJsonRpcError(value,
|
|
231
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
232
|
+
ErrorWrapper) {
|
|
219
233
|
(0, assert_1.assertStruct)(value, exports.JsonRpcErrorStruct, 'Invalid JSON-RPC error', ErrorWrapper);
|
|
220
234
|
}
|
|
221
235
|
exports.assertIsJsonRpcError = assertIsJsonRpcError;
|
package/dist/json.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;AAAA,6CAiBqB;AACrB,qCAAmE;AACnE,iCAKgB;AAEH,QAAA,UAAU,GAAG,IAAA,oBAAM,EAAO,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;IACvD,MAAM,CAAC,OAAO,CAAC,GAAG,sBAAsB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACtD,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,0CAA0C,CAAC;KACnD;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,CAAC;AAaH;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,kBAAU,CAAC,CAAC;AAC/B,CAAC;AAFD,kCAEC;AAED;;GAEG;AACU,QAAA,QAAQ,GAAG,KAAc,CAAC;AAC1B,QAAA,oBAAoB,GAAG,IAAA,qBAAO,EAAC,gBAAQ,CAAC,CAAC;AAQzC,QAAA,eAAe,GAAG,IAAA,sBAAQ,EAAC,IAAA,mBAAK,EAAC,CAAC,IAAA,oBAAM,GAAE,EAAE,IAAA,oBAAM,GAAE,CAAC,CAAC,CAAC,CAAC;AAUxD,QAAA,kBAAkB,GAAG,IAAA,oBAAM,EAAC;IACvC,IAAI,EAAE,IAAA,qBAAO,GAAE;IACf,OAAO,EAAE,IAAA,oBAAM,GAAE;IACjB,IAAI,EAAE,IAAA,sBAAQ,EAAC,kBAAU,CAAC;IAC1B,KAAK,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC;CAC1B,CAAC,CAAC;AAsBU,QAAA,mBAAmB,GAAG,IAAA,sBAAQ,EACzC,IAAA,mBAAK,EAAC,CAAC,IAAA,oBAAM,E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n omit,\n optional,\n record,\n string,\n Struct,\n union,\n unknown,\n} from 'superstruct';\nimport { AssertionErrorConstructor, assertStruct } from './assert';\nimport {\n calculateNumberSize,\n calculateStringSize,\n isPlainObject,\n JsonSize,\n} from './misc';\n\nexport const JsonStruct = define<Json>('Json', (value) => {\n const [isValid] = validateJsonAndGetSize(value, true);\n if (!isValid) {\n return 'Expected a valid JSON-serializable value';\n }\n return true;\n});\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n return is(value, JsonStruct);\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: optional(JsonStruct),\n stack: optional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct = optional(\n union([record(string(), JsonStruct), array(JsonStruct)]),\n);\nexport type JsonRpcParams = Infer<typeof JsonRpcParamsStruct>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: JsonRpcParamsStruct,\n});\n\nexport type InferWithParams<\n Type extends Struct<any, unknown>,\n Params extends JsonRpcParams,\n> = Omit<Infer<Type>, 'params'> &\n (keyof Params extends undefined\n ? {\n params?: Params;\n }\n : {\n params: Params;\n });\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams> = InferWithParams<\n typeof JsonRpcRequestStruct,\n Params\n>;\n\nexport const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams> = InferWithParams<\n typeof JsonRpcNotificationStruct,\n Params\n>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification<JsonRpcParams> {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification<JsonRpcParams> {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(\n value: unknown,\n): value is JsonRpcRequest<JsonRpcParams> {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest<JsonRpcParams> {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n\n/**\n * Checks whether a value is JSON serializable and counts the total number\n * of bytes needed to store the serialized version of the value.\n *\n * @param jsObject - Potential JSON serializable object.\n * @param skipSizingProcess - Skip JSON size calculation (default: false).\n * @returns Tuple [isValid, plainTextSizeInBytes] containing a boolean that signals whether\n * the value was serializable and a number of bytes that it will use when serialized to JSON.\n */\nexport function validateJsonAndGetSize(\n jsObject: unknown,\n skipSizingProcess = false,\n): [isValid: boolean, plainTextSizeInBytes: number] {\n const seenObjects = new Set();\n /**\n * Checks whether a value is JSON serializable and counts the total number\n * of bytes needed to store the serialized version of the value.\n *\n * This function assumes the encoding of the JSON is done in UTF-8.\n *\n * @param value - Potential JSON serializable value.\n * @param skipSizing - Skip JSON size calculation (default: false).\n * @returns Tuple [isValid, plainTextSizeInBytes] containing a boolean that signals whether\n * the value was serializable and a number of bytes that it will use when serialized to JSON.\n */\n function getJsonSerializableInfo(\n value: unknown,\n skipSizing: boolean,\n ): [isValid: boolean, plainTextSizeInBytes: number] {\n if (value === undefined) {\n return [false, 0];\n } else if (value === null) {\n // Return already specified constant size for null (special object)\n return [true, skipSizing ? 0 : JsonSize.Null];\n }\n\n // Check and calculate sizes for basic (and some special) types\n const typeOfValue = typeof value;\n try {\n if (typeOfValue === 'function') {\n return [false, 0];\n } else if (typeOfValue === 'string' || value instanceof String) {\n return [\n true,\n skipSizing\n ? 0\n : calculateStringSize(value as string) + JsonSize.Quote * 2,\n ];\n } else if (typeOfValue === 'boolean' || value instanceof Boolean) {\n if (skipSizing) {\n return [true, 0];\n }\n // eslint-disable-next-line eqeqeq\n return [true, value == true ? JsonSize.True : JsonSize.False];\n } else if (typeOfValue === 'number' || value instanceof Number) {\n if (skipSizing) {\n return [true, 0];\n }\n return [true, calculateNumberSize(value as number)];\n } else if (value instanceof Date) {\n if (skipSizing) {\n return [true, 0];\n }\n return [\n true,\n // Note: Invalid dates will serialize to null\n isNaN(value.getDate())\n ? JsonSize.Null\n : JsonSize.Date + JsonSize.Quote * 2,\n ];\n }\n } catch (_) {\n return [false, 0];\n }\n\n // If object is not plain and cannot be serialized properly,\n // stop here and return false for serialization\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [false, 0];\n }\n\n // Circular object detection (handling)\n // Check if the same object already exists\n if (seenObjects.has(value)) {\n return [false, 0];\n }\n // Add new object to the seen objects set\n // Only the plain objects should be added (Primitive types are skipped)\n seenObjects.add(value);\n\n // Continue object decomposition\n try {\n return [\n true,\n Object.entries(value).reduce(\n (sum, [key, nestedValue], idx, arr) => {\n // Recursively process next nested object or primitive type\n // eslint-disable-next-line prefer-const\n let [valid, size] = getJsonSerializableInfo(\n nestedValue,\n skipSizing,\n );\n if (!valid) {\n throw new Error(\n 'JSON validation did not pass. Validation process stopped.',\n );\n }\n\n // Circular object detection\n // Once a child node is visited and processed remove it from the set.\n // This will prevent false positives with the same adjacent objects.\n seenObjects.delete(value);\n\n if (skipSizing) {\n return 0;\n }\n\n // Objects will have be serialized with \"key\": value,\n // therefore we include the key in the calculation here\n const keySize = Array.isArray(value)\n ? 0\n : key.length + JsonSize.Comma + JsonSize.Colon * 2;\n\n const separator = idx < arr.length - 1 ? JsonSize.Comma : 0;\n\n return sum + keySize + size + separator;\n },\n // Starts at 2 because the serialized JSON string data (plain text)\n // will minimally contain {}/[]\n skipSizing ? 0 : JsonSize.Wrapper * 2,\n ),\n ];\n } catch (_) {\n return [false, 0];\n }\n }\n\n return getJsonSerializableInfo(jsObject, skipSizingProcess);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;AAAA,6CAiBqB;AAErB,qCAAmE;AACnE,iCAKgB;AAEH,QAAA,UAAU,GAAG,IAAA,oBAAM,EAAO,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;IACvD,MAAM,CAAC,OAAO,CAAC,GAAG,sBAAsB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACtD,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,0CAA0C,CAAC;KACnD;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,CAAC;AAaH;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,kBAAU,CAAC,CAAC;AAC/B,CAAC;AAFD,kCAEC;AAED;;GAEG;AACU,Q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,CAAC,GAAG,CAAC,MAAM,GAAG,eAAQ,CAAC,KAAK,GAAG,eAAQ,CAAC,KAAK,GAAG,CAAC,CAAC;oBAErD,MAAM,SAAS,GAAG,GAAG,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,eAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;oBAE5D,OAAO,GAAG,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;gBAC1C,CAAC;gBACD,mEAAmE;gBACnE,+BAA+B;gBAC/B,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,eAAQ,CAAC,OAAO,GAAG,CAAC,CACtC;aACF,CAAC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;SACnB;IACH,CAAC;IAED,OAAO,uBAAuB,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;AAC9D,CAAC;AAjID,wDAiIC","sourcesContent":["import {\n array,\n define,\n Infer,\n integer,\n is,\n literal,\n nullable,\n number,\n object,\n omit,\n optional,\n record,\n string,\n Struct,\n union,\n unknown,\n} from 'superstruct';\n\nimport { AssertionErrorConstructor, assertStruct } from './assert';\nimport {\n calculateNumberSize,\n calculateStringSize,\n isPlainObject,\n JsonSize,\n} from './misc';\n\nexport const JsonStruct = define<Json>('Json', (value) => {\n const [isValid] = validateJsonAndGetSize(value, true);\n if (!isValid) {\n return 'Expected a valid JSON-serializable value';\n }\n return true;\n});\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n return is(value, JsonStruct);\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: optional(JsonStruct),\n stack: optional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct = optional(\n union([record(string(), JsonStruct), array(JsonStruct)]),\n);\nexport type JsonRpcParams = Infer<typeof JsonRpcParamsStruct>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: JsonRpcParamsStruct,\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Omit<Infer<Type>, 'params'> &\n (keyof Params extends undefined\n ? {\n params?: Params;\n }\n : {\n params: Params;\n });\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n\n/**\n * Checks whether a value is JSON serializable and counts the total number\n * of bytes needed to store the serialized version of the value.\n *\n * @param jsObject - Potential JSON serializable object.\n * @param skipSizingProcess - Skip JSON size calculation (default: false).\n * @returns Tuple [isValid, plainTextSizeInBytes] containing a boolean that signals whether\n * the value was serializable and a number of bytes that it will use when serialized to JSON.\n */\nexport function validateJsonAndGetSize(\n jsObject: unknown,\n skipSizingProcess = false,\n): [isValid: boolean, plainTextSizeInBytes: number] {\n const seenObjects = new Set();\n /**\n * Checks whether a value is JSON serializable and counts the total number\n * of bytes needed to store the serialized version of the value.\n *\n * This function assumes the encoding of the JSON is done in UTF-8.\n *\n * @param value - Potential JSON serializable value.\n * @param skipSizing - Skip JSON size calculation (default: false).\n * @returns Tuple [isValid, plainTextSizeInBytes] containing a boolean that signals whether\n * the value was serializable and a number of bytes that it will use when serialized to JSON.\n */\n function getJsonSerializableInfo(\n value: unknown,\n skipSizing: boolean,\n ): [isValid: boolean, plainTextSizeInBytes: number] {\n if (value === undefined) {\n return [false, 0];\n } else if (value === null) {\n // Return already specified constant size for null (special object)\n return [true, skipSizing ? 0 : JsonSize.Null];\n }\n\n // Check and calculate sizes for basic (and some special) types\n const typeOfValue = typeof value;\n try {\n if (typeOfValue === 'function') {\n return [false, 0];\n } else if (typeOfValue === 'string' || value instanceof String) {\n return [\n true,\n skipSizing\n ? 0\n : calculateStringSize(value as string) + JsonSize.Quote * 2,\n ];\n } else if (typeOfValue === 'boolean' || value instanceof Boolean) {\n if (skipSizing) {\n return [true, 0];\n }\n // eslint-disable-next-line eqeqeq\n return [true, value == true ? JsonSize.True : JsonSize.False];\n } else if (typeOfValue === 'number' || value instanceof Number) {\n if (skipSizing) {\n return [true, 0];\n }\n return [true, calculateNumberSize(value as number)];\n } else if (value instanceof Date) {\n if (skipSizing) {\n return [true, 0];\n }\n return [\n true,\n // Note: Invalid dates will serialize to null\n isNaN(value.getDate())\n ? JsonSize.Null\n : JsonSize.Date + JsonSize.Quote * 2,\n ];\n }\n } catch (_) {\n return [false, 0];\n }\n\n // If object is not plain and cannot be serialized properly,\n // stop here and return false for serialization\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [false, 0];\n }\n\n // Circular object detection (handling)\n // Check if the same object already exists\n if (seenObjects.has(value)) {\n return [false, 0];\n }\n // Add new object to the seen objects set\n // Only the plain objects should be added (Primitive types are skipped)\n seenObjects.add(value);\n\n // Continue object decomposition\n try {\n return [\n true,\n Object.entries(value).reduce(\n (sum, [key, nestedValue], idx, arr) => {\n // Recursively process next nested object or primitive type\n // eslint-disable-next-line prefer-const\n let [valid, size] = getJsonSerializableInfo(\n nestedValue,\n skipSizing,\n );\n if (!valid) {\n throw new Error(\n 'JSON validation did not pass. Validation process stopped.',\n );\n }\n\n // Circular object detection\n // Once a child node is visited and processed remove it from the set.\n // This will prevent false positives with the same adjacent objects.\n seenObjects.delete(value);\n\n if (skipSizing) {\n return 0;\n }\n\n // Objects will have be serialized with \"key\": value,\n // therefore we include the key in the calculation here\n const keySize = Array.isArray(value)\n ? 0\n : key.length + JsonSize.Comma + JsonSize.Colon * 2;\n\n const separator = idx < arr.length - 1 ? JsonSize.Comma : 0;\n\n return sum + keySize + size + separator;\n },\n // Starts at 2 because the serialized JSON string data (plain text)\n // will minimally contain {}/[]\n skipSizing ? 0 : JsonSize.Wrapper * 2,\n ),\n ];\n } catch (_) {\n return [false, 0];\n }\n }\n\n return getJsonSerializableInfo(jsObject, skipSizingProcess);\n}\n"]}
|
package/dist/json.test-d.js
CHANGED
|
@@ -55,8 +55,8 @@ const a = { a: 0 };
|
|
|
55
55
|
(0, tsd_1.expectNotAssignable)(a);
|
|
56
56
|
// The Json type gets confused by classes. This class instance is valid Json,
|
|
57
57
|
// but it's incompatible with the Json type.
|
|
58
|
-
class
|
|
58
|
+
class Foo {
|
|
59
59
|
}
|
|
60
|
-
const
|
|
61
|
-
(0, tsd_1.expectNotAssignable)(
|
|
60
|
+
const foo = new Foo();
|
|
61
|
+
(0, tsd_1.expectNotAssignable)(foo);
|
|
62
62
|
//# sourceMappingURL=json.test-d.js.map
|
package/dist/json.test-d.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.test-d.js","sourceRoot":"","sources":["../src/json.test-d.ts"],"names":[],"mappings":";AAAA,mEAAmE;;AAEnE,6BAA4D;
|
|
1
|
+
{"version":3,"file":"json.test-d.js","sourceRoot":"","sources":["../src/json.test-d.ts"],"names":[],"mappings":";AAAA,mEAAmE;;AAEnE,6BAA4D;AAI5D,cAAc;AAEd,IAAA,sBAAgB,EAAO,IAAI,CAAC,CAAC;AAE7B,IAAA,sBAAgB,EAAO,KAAK,CAAC,CAAC;AAE9B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAAO,CAAC,CAAC,CAAC;AAE1B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAA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M,GAAG;CAER;AACD,MAAM,GAAG,GAAG,IAAI,GAAG,EAAE,CAAC;AACtB,IAAA,yBAAmB,EAAO,GAAG,CAAC,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/consistent-type-definitions */\n\nimport { expectAssignable, expectNotAssignable } from 'tsd';\n\nimport type { Json } from '.';\n\n// Valid Json:\n\nexpectAssignable<Json>(null);\n\nexpectAssignable<Json>(false);\n\nexpectAssignable<Json>('');\n\nexpectAssignable<Json>(0);\n\nexpectAssignable<Json>([]);\n\nexpectAssignable<Json>({});\n\nexpectAssignable<Json>([0]);\n\nexpectAssignable<Json>({ a: 0 });\n\nexpectAssignable<Json>({ deeply: [{ nested: 1 }, 'mixed', 'types', 0] });\n\nexpectAssignable<Json>(['array', { nested: { mixed: true, types: null } }, 0]);\n\ntype JsonCompatibleType = {\n c: number;\n};\nconst jsonCompatibleType: JsonCompatibleType = { c: 0 };\nexpectAssignable<Json>(jsonCompatibleType);\n\n// Invalid Json:\n\nexpectNotAssignable<Json>(undefined);\n\nexpectNotAssignable<Json>(new Date());\n\nexpectNotAssignable<Json>(() => 0);\n\nexpectNotAssignable<Json>(new Set());\n\nexpectNotAssignable<Json>(new Map());\n\nexpectNotAssignable<Json>(Symbol('test'));\n\nexpectNotAssignable<Json>({ a: new Date() });\n\nexpectNotAssignable<Json>(5 as number | undefined);\n\ninterface InterfaceWithOptionalProperty {\n a?: number;\n}\nconst interfaceWithOptionalProperty: InterfaceWithOptionalProperty = { a: 0 };\nexpectNotAssignable<Json>(interfaceWithOptionalProperty);\n\ninterface InterfaceWithDate {\n a: Date;\n}\nconst interfaceWithDate: InterfaceWithDate = { a: new Date() };\nexpectNotAssignable<Json>(interfaceWithDate);\n\ninterface InterfaceWithOptionalDate {\n a?: Date;\n}\nconst interfaceWithOptionalDate: InterfaceWithOptionalDate = { a: new Date() };\nexpectNotAssignable<Json>(interfaceWithOptionalDate);\n\ninterface InterfaceWithUndefinedTypeUnion {\n a: number | undefined;\n}\nconst interfaceWithUndefinedTypeUnion: InterfaceWithUndefinedTypeUnion = {\n a: 0,\n};\nexpectNotAssignable<Json>(interfaceWithUndefinedTypeUnion);\n\ninterface InterfaceWithFunction {\n a: () => number;\n}\nconst interfaceWithFunction: InterfaceWithFunction = { a: () => 0 };\nexpectNotAssignable<Json>(interfaceWithFunction);\n\ntype TypeWithDate = {\n a: Date;\n};\nconst typeWithDate: TypeWithDate = { a: new Date() };\nexpectNotAssignable<Json>(typeWithDate);\n\ntype TypeWithOptionalDate = {\n a?: Date;\n};\nconst typeWithOptionalDate: TypeWithOptionalDate = { a: new Date() };\nexpectNotAssignable<Json>(typeWithOptionalDate);\n\ntype TypeWithUndefinedTypeUnion = {\n a: number | undefined;\n};\nconst typeWithUndefinedTypeUnion: TypeWithUndefinedTypeUnion = {\n a: 0,\n};\nexpectNotAssignable<Json>(typeWithUndefinedTypeUnion);\n\ntype TypeWithFunction = {\n a: () => number;\n};\nconst typeWithFunction: TypeWithFunction = { a: () => 0 };\nexpectNotAssignable<Json>(typeWithFunction);\n\ntype TypeWithOptionalProperty = {\n a?: number | undefined;\n};\nconst typeWithOptionalProperty: TypeWithOptionalProperty = { a: undefined };\nexpectNotAssignable<Json>(typeWithOptionalProperty);\n\n// Edge cases:\n\n// The Json type doesn't protect against the `any` type.\nexpectAssignable<Json>(null as any);\n\n// The Json type gets confused by interfaces. This interface is valid Json,\n// but it's incompatible with the Json type.\ninterface A {\n a: number;\n}\nconst a: A = { a: 0 };\nexpectNotAssignable<Json>(a);\n\n// The Json type gets confused by classes. This class instance is valid Json,\n// but it's incompatible with the Json type.\nclass Foo {\n a!: number;\n}\nconst foo = new Foo();\nexpectNotAssignable<Json>(foo);\n"]}
|
package/dist/number.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.hexToBigInt = exports.hexToNumber = exports.bigIntToHex = exports.numberToHex = void 0;
|
|
4
|
-
const hex_1 = require("./hex");
|
|
5
4
|
const assert_1 = require("./assert");
|
|
5
|
+
const hex_1 = require("./hex");
|
|
6
6
|
/**
|
|
7
7
|
* Convert a number to a hexadecimal string. This verifies that the number is a
|
|
8
8
|
* non-negative safe integer.
|
package/dist/number.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"number.js","sourceRoot":"","sources":["../src/number.ts"],"names":[],"mappings":";;;AAAA,+BAAiD;
|
|
1
|
+
{"version":3,"file":"number.js","sourceRoot":"","sources":["../src/number.ts"],"names":[],"mappings":";;;AAAA,qCAAkC;AAClC,+BAAiD;AAEjD;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE;IACnD,IAAA,eAAM,EAAC,OAAO,KAAK,KAAK,QAAQ,EAAE,yBAAyB,CAAC,CAAC;IAC7D,IAAA,eAAM,EAAC,KAAK,IAAI,CAAC,EAAE,sCAAsC,CAAC,CAAC;IAC3D,IAAA,eAAM,EACJ,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,EAC3B,yDAAyD,CAC1D,CAAC;IAEF,OAAO,IAAA,WAAK,EAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;AACnC,CAAC,CAAC;AATW,QAAA,WAAW,eAStB;AAEF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE;IACnD,IAAA,eAAM,EAAC,OAAO,KAAK,KAAK,QAAQ,EAAE,yBAAyB,CAAC,CAAC;IAC7D,IAAA,eAAM,EAAC,KAAK,IAAI,CAAC,EAAE,sCAAsC,CAAC,CAAC;IAE3D,OAAO,IAAA,WAAK,EAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;AACnC,CAAC,CAAC;AALW,QAAA,WAAW,eAKtB;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACI,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE;IACnD,IAAA,uBAAiB,EAAC,KAAK,CAAC,CAAC;IAEzB,2EAA2E;IAC3E,kEAAkE;IAClE,MAAM,WAAW,GAAG,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAExC,IAAA,eAAM,EACJ,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,EACjC,yDAAyD,CAC1D,CAAC;IAEF,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC;AAbW,QAAA,WAAW,eAatB;AAEF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,WAAW,GAAG,CAAC,KAAa,EAAU,EAAE;IACnD,IAAA,uBAAiB,EAAC,KAAK,CAAC,CAAC;IAEzB,2EAA2E;IAC3E,OAAO,MAAM,CAAC,IAAA,WAAK,EAAC,KAAK,CAAC,CAAC,CAAC;AAC9B,CAAC,CAAC;AALW,QAAA,WAAW,eAKtB","sourcesContent":["import { assert } from './assert';\nimport { add0x, assertIsHexString } from './hex';\n\n/**\n * Convert a number to a hexadecimal string. This verifies that the number is a\n * non-negative safe integer.\n *\n * To convert a `bigint` to a hexadecimal string instead, use\n * {@link bigIntToHex}.\n *\n * @example\n * ```typescript\n * numberToHex(0); // '0x0'\n * numberToHex(1); // '0x1'\n * numberToHex(16); // '0x10'\n * ```\n * @param value - The number to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the number is not a non-negative safe integer.\n */\nexport const numberToHex = (value: number): string => {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToHex` instead.',\n );\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a `bigint` to a hexadecimal string. This verifies that the `bigint`\n * is a non-negative integer.\n *\n * To convert a number to a hexadecimal string instead, use {@link numberToHex}.\n *\n * @example\n * ```typescript\n * bigIntToHex(0n); // '0x0'\n * bigIntToHex(1n); // '0x1'\n * bigIntToHex(16n); // '0x10'\n * ```\n * @param value - The `bigint` to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the `bigint` is not a non-negative integer.\n */\nexport const bigIntToHex = (value: bigint): string => {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= 0, 'Value must be a non-negative bigint.');\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a hexadecimal string to a number. This verifies that the string is a\n * valid hex string, and that the resulting number is a safe integer. Both\n * \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a `bigint` instead, use\n * {@link hexToBigInt}.\n *\n * @example\n * ```typescript\n * hexToNumber('0x0'); // 0\n * hexToNumber('0x1'); // 1\n * hexToNumber('0x10'); // 16\n * ```\n * @param value - The hexadecimal string to convert to a number.\n * @returns The number.\n * @throws If the value is not a valid hexadecimal string, or if the resulting\n * number is not a safe integer.\n */\nexport const hexToNumber = (value: string): number => {\n assertIsHexString(value);\n\n // `parseInt` accepts values without the \"0x\"-prefix, whereas `Number` does\n // not. Using this is slightly faster than `Number(add0x(value))`.\n const numberValue = parseInt(value, 16);\n\n assert(\n Number.isSafeInteger(numberValue),\n 'Value is not a safe integer. Use `hexToBigInt` instead.',\n );\n\n return numberValue;\n};\n\n/**\n * Convert a hexadecimal string to a `bigint`. This verifies that the string is\n * a valid hex string. Both \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a number instead, use {@link hexToNumber}.\n *\n * @example\n * ```typescript\n * hexToBigInt('0x0'); // 0n\n * hexToBigInt('0x1'); // 1n\n * hexToBigInt('0x10'); // 16n\n * ```\n * @param value - The hexadecimal string to convert to a `bigint`.\n * @returns The `bigint`.\n * @throws If the value is not a valid hexadecimal string.\n */\nexport const hexToBigInt = (value: string): bigint => {\n assertIsHexString(value);\n\n // The `BigInt` constructor requires the \"0x\"-prefix to parse a hex string.\n return BigInt(add0x(value));\n};\n"]}
|
package/dist/opaque.d.ts
ADDED
package/dist/opaque.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"opaque.js","sourceRoot":"","sources":["../src/opaque.ts"],"names":[],"mappings":"","sourcesContent":["// We use a symbol property name instead of { _type: Brand }, because that would show up in IDE suggestions,\n// while internal symbols do not.\ndeclare const brand: unique symbol;\nexport type Opaque<Base, Brand extends symbol> = Base & { [brand]: Brand };\n"]}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Struct } from 'superstruct';
|
|
2
|
+
import { Opaque } from './opaque';
|
|
3
|
+
/**
|
|
4
|
+
* {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.
|
|
5
|
+
*
|
|
6
|
+
* @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.
|
|
7
|
+
* ```typescript
|
|
8
|
+
* const unsafeRange: string = dataFromUser();
|
|
9
|
+
* assertIsSemVerRange(unsafeRange);
|
|
10
|
+
* unsafeRange
|
|
11
|
+
* // ^? SemVerRange
|
|
12
|
+
* ```
|
|
13
|
+
* @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.
|
|
14
|
+
* ```typescript
|
|
15
|
+
* const unsafeRange: string = dataFromUser();
|
|
16
|
+
* unsafeRange as SemVerRange;
|
|
17
|
+
* // ^? SemVerRange
|
|
18
|
+
* ```
|
|
19
|
+
* @see {@link assertIsSemVerRange}
|
|
20
|
+
* @see {@link isValidSemVerRange}
|
|
21
|
+
*/
|
|
22
|
+
export declare type SemVerRange = Opaque<string, typeof semVerRange>;
|
|
23
|
+
declare const semVerRange: unique symbol;
|
|
24
|
+
/**
|
|
25
|
+
* {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.
|
|
26
|
+
*
|
|
27
|
+
* @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.
|
|
28
|
+
* ```typescript
|
|
29
|
+
* const unsafeVersion: string = dataFromUser();
|
|
30
|
+
* assertIsSemVerVersion(unsafeRange);
|
|
31
|
+
* unsafeVersion
|
|
32
|
+
* // ^? SemVerVersion
|
|
33
|
+
* ```
|
|
34
|
+
* @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.
|
|
35
|
+
* ```typescript
|
|
36
|
+
* const unsafeVersion: string = dataFromUser();
|
|
37
|
+
* unsafeRange as SemVerVersion;
|
|
38
|
+
* // ^? SemVerVersion
|
|
39
|
+
* ```
|
|
40
|
+
* @see {@link assertIsSemVerVersion}
|
|
41
|
+
* @see {@link isValidSemVerVersion}
|
|
42
|
+
*/
|
|
43
|
+
export declare type SemVerVersion = Opaque<string, typeof semVerVersion>;
|
|
44
|
+
declare const semVerVersion: unique symbol;
|
|
45
|
+
/**
|
|
46
|
+
* A struct for validating a version string.
|
|
47
|
+
*/
|
|
48
|
+
export declare const VersionStruct: Struct<SemVerVersion, null>;
|
|
49
|
+
export declare const VersionRangeStruct: Struct<SemVerRange, null>;
|
|
50
|
+
/**
|
|
51
|
+
* Checks whether a SemVer version is valid.
|
|
52
|
+
*
|
|
53
|
+
* @param version - A potential version.
|
|
54
|
+
* @returns `true` if the version is valid, and `false` otherwise.
|
|
55
|
+
*/
|
|
56
|
+
export declare function isValidSemVerVersion(version: unknown): version is SemVerVersion;
|
|
57
|
+
/**
|
|
58
|
+
* Checks whether a SemVer version range is valid.
|
|
59
|
+
*
|
|
60
|
+
* @param versionRange - A potential version range.
|
|
61
|
+
* @returns `true` if the version range is valid, and `false` otherwise.
|
|
62
|
+
*/
|
|
63
|
+
export declare function isValidSemVerRange(versionRange: unknown): versionRange is SemVerRange;
|
|
64
|
+
/**
|
|
65
|
+
* Asserts that a value is a valid concrete SemVer version.
|
|
66
|
+
*
|
|
67
|
+
* @param version - A potential SemVer concrete version.
|
|
68
|
+
*/
|
|
69
|
+
export declare function assertIsSemVerVersion(version: unknown): asserts version is SemVerVersion;
|
|
70
|
+
/**
|
|
71
|
+
* Asserts that a value is a valid SemVer range.
|
|
72
|
+
*
|
|
73
|
+
* @param range - A potential SemVer range.
|
|
74
|
+
*/
|
|
75
|
+
export declare function assertIsSemVerRange(range: unknown): asserts range is SemVerRange;
|
|
76
|
+
/**
|
|
77
|
+
* Checks whether a SemVer version is greater than another.
|
|
78
|
+
*
|
|
79
|
+
* @param version1 - The left-hand version.
|
|
80
|
+
* @param version2 - The right-hand version.
|
|
81
|
+
* @returns `version1 > version2`.
|
|
82
|
+
*/
|
|
83
|
+
export declare function gtVersion(version1: SemVerVersion, version2: SemVerVersion): boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Checks whether a SemVer version is greater than all possibilities in a range.
|
|
86
|
+
*
|
|
87
|
+
* @param version - A SemvVer version.
|
|
88
|
+
* @param range - The range to check against.
|
|
89
|
+
* @returns `version > range`.
|
|
90
|
+
*/
|
|
91
|
+
export declare function gtRange(version: SemVerVersion, range: SemVerRange): boolean;
|
|
92
|
+
/**
|
|
93
|
+
* Returns whether a SemVer version satisfies a SemVer range.
|
|
94
|
+
*
|
|
95
|
+
* @param version - The SemVer version to check.
|
|
96
|
+
* @param versionRange - The SemVer version range to check against.
|
|
97
|
+
* @returns Whether the version satisfied the version range.
|
|
98
|
+
*/
|
|
99
|
+
export declare function satisfiesVersionRange(version: SemVerVersion, versionRange: SemVerRange): boolean;
|
|
100
|
+
export {};
|
package/dist/versions.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.satisfiesVersionRange = exports.gtRange = exports.gtVersion = exports.assertIsSemVerRange = exports.assertIsSemVerVersion = exports.isValidSemVerRange = exports.isValidSemVerVersion = exports.VersionRangeStruct = exports.VersionStruct = void 0;
|
|
4
|
+
const semver_1 = require("semver");
|
|
5
|
+
const superstruct_1 = require("superstruct");
|
|
6
|
+
const assert_1 = require("./assert");
|
|
7
|
+
/**
|
|
8
|
+
* A struct for validating a version string.
|
|
9
|
+
*/
|
|
10
|
+
exports.VersionStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'Version', (value) => {
|
|
11
|
+
if ((0, semver_1.valid)(value) === null) {
|
|
12
|
+
return `Expected SemVer version, got "${value}"`;
|
|
13
|
+
}
|
|
14
|
+
return true;
|
|
15
|
+
});
|
|
16
|
+
exports.VersionRangeStruct = (0, superstruct_1.refine)((0, superstruct_1.string)(), 'Version range', (value) => {
|
|
17
|
+
if ((0, semver_1.validRange)(value) === null) {
|
|
18
|
+
return `Expected SemVer range, got "${value}"`;
|
|
19
|
+
}
|
|
20
|
+
return true;
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* Checks whether a SemVer version is valid.
|
|
24
|
+
*
|
|
25
|
+
* @param version - A potential version.
|
|
26
|
+
* @returns `true` if the version is valid, and `false` otherwise.
|
|
27
|
+
*/
|
|
28
|
+
function isValidSemVerVersion(version) {
|
|
29
|
+
return (0, superstruct_1.is)(version, exports.VersionStruct);
|
|
30
|
+
}
|
|
31
|
+
exports.isValidSemVerVersion = isValidSemVerVersion;
|
|
32
|
+
/**
|
|
33
|
+
* Checks whether a SemVer version range is valid.
|
|
34
|
+
*
|
|
35
|
+
* @param versionRange - A potential version range.
|
|
36
|
+
* @returns `true` if the version range is valid, and `false` otherwise.
|
|
37
|
+
*/
|
|
38
|
+
function isValidSemVerRange(versionRange) {
|
|
39
|
+
return (0, superstruct_1.is)(versionRange, exports.VersionRangeStruct);
|
|
40
|
+
}
|
|
41
|
+
exports.isValidSemVerRange = isValidSemVerRange;
|
|
42
|
+
/**
|
|
43
|
+
* Asserts that a value is a valid concrete SemVer version.
|
|
44
|
+
*
|
|
45
|
+
* @param version - A potential SemVer concrete version.
|
|
46
|
+
*/
|
|
47
|
+
function assertIsSemVerVersion(version) {
|
|
48
|
+
(0, assert_1.assertStruct)(version, exports.VersionStruct);
|
|
49
|
+
}
|
|
50
|
+
exports.assertIsSemVerVersion = assertIsSemVerVersion;
|
|
51
|
+
/**
|
|
52
|
+
* Asserts that a value is a valid SemVer range.
|
|
53
|
+
*
|
|
54
|
+
* @param range - A potential SemVer range.
|
|
55
|
+
*/
|
|
56
|
+
function assertIsSemVerRange(range) {
|
|
57
|
+
(0, assert_1.assertStruct)(range, exports.VersionRangeStruct);
|
|
58
|
+
}
|
|
59
|
+
exports.assertIsSemVerRange = assertIsSemVerRange;
|
|
60
|
+
/**
|
|
61
|
+
* Checks whether a SemVer version is greater than another.
|
|
62
|
+
*
|
|
63
|
+
* @param version1 - The left-hand version.
|
|
64
|
+
* @param version2 - The right-hand version.
|
|
65
|
+
* @returns `version1 > version2`.
|
|
66
|
+
*/
|
|
67
|
+
function gtVersion(version1, version2) {
|
|
68
|
+
return (0, semver_1.gt)(version1, version2);
|
|
69
|
+
}
|
|
70
|
+
exports.gtVersion = gtVersion;
|
|
71
|
+
/**
|
|
72
|
+
* Checks whether a SemVer version is greater than all possibilities in a range.
|
|
73
|
+
*
|
|
74
|
+
* @param version - A SemvVer version.
|
|
75
|
+
* @param range - The range to check against.
|
|
76
|
+
* @returns `version > range`.
|
|
77
|
+
*/
|
|
78
|
+
function gtRange(version, range) {
|
|
79
|
+
return (0, semver_1.gtr)(version, range);
|
|
80
|
+
}
|
|
81
|
+
exports.gtRange = gtRange;
|
|
82
|
+
/**
|
|
83
|
+
* Returns whether a SemVer version satisfies a SemVer range.
|
|
84
|
+
*
|
|
85
|
+
* @param version - The SemVer version to check.
|
|
86
|
+
* @param versionRange - The SemVer version range to check against.
|
|
87
|
+
* @returns Whether the version satisfied the version range.
|
|
88
|
+
*/
|
|
89
|
+
function satisfiesVersionRange(version, versionRange) {
|
|
90
|
+
return (0, semver_1.satisfies)(version, versionRange, {
|
|
91
|
+
includePrerelease: true,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
exports.satisfiesVersionRange = satisfiesVersionRange;
|
|
95
|
+
//# sourceMappingURL=versions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"versions.js","sourceRoot":"","sources":["../src/versions.ts"],"names":[],"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,CAAC,CAAC;AACtC,CAAC;AALD,8BAKC;AAED;;;;;;GAMG;AACH,SAAgB,OAAO,CAAC,OAAsB,EAAE,KAAkB;IAChE,OAAO,IAAA,YAAS,EAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AACnC,CAAC;AAFD,0BAEC;AAED;;;;;;GAMG;AACH,SAAgB,qBAAqB,CACnC,OAAsB,EACtB,YAAyB;IAEzB,OAAO,IAAA,kBAAe,EAAC,OAAO,EAAE,YAAY,EAAE;QAC5C,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC;AAPD,sDAOC","sourcesContent":["import {\n gt as gtSemver,\n gtr as gtrSemver,\n satisfies as satisfiesSemver,\n valid as validSemVerVersion,\n validRange as validSemVerRange,\n} from 'semver';\nimport { is, refine, string, Struct } from 'superstruct';\n\nimport { assertStruct } from './assert';\nimport { Opaque } from './opaque';\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.\n *\n * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * assertIsSemVerRange(unsafeRange);\n * unsafeRange\n * // ^? SemVerRange\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * unsafeRange as SemVerRange;\n * // ^? SemVerRange\n * ```\n * @see {@link assertIsSemVerRange}\n * @see {@link isValidSemVerRange}\n */\nexport type SemVerRange = Opaque<string, typeof semVerRange>;\ndeclare const semVerRange: unique symbol;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.\n *\n * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * assertIsSemVerVersion(unsafeRange);\n * unsafeVersion\n * // ^? SemVerVersion\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * unsafeRange as SemVerVersion;\n * // ^? SemVerVersion\n * ```\n * @see {@link assertIsSemVerVersion}\n * @see {@link isValidSemVerVersion}\n */\nexport type SemVerVersion = Opaque<string, typeof semVerVersion>;\ndeclare const semVerVersion: unique symbol;\n\n/**\n * A struct for validating a version string.\n */\nexport const VersionStruct = refine<SemVerVersion, null>(\n string() as unknown as Struct<SemVerVersion, null>,\n 'Version',\n (value) => {\n if (validSemVerVersion(value) === null) {\n return `Expected SemVer version, got \"${value}\"`;\n }\n return true;\n },\n);\n\nexport const VersionRangeStruct = refine<SemVerRange, null>(\n string() as unknown as Struct<SemVerRange, null>,\n 'Version range',\n (value) => {\n if (validSemVerRange(value) === null) {\n return `Expected SemVer range, got \"${value}\"`;\n }\n return true;\n },\n);\n\n/**\n * Checks whether a SemVer version is valid.\n *\n * @param version - A potential version.\n * @returns `true` if the version is valid, and `false` otherwise.\n */\nexport function isValidSemVerVersion(\n version: unknown,\n): version is SemVerVersion {\n return is(version, VersionStruct);\n}\n\n/**\n * Checks whether a SemVer version range is valid.\n *\n * @param versionRange - A potential version range.\n * @returns `true` if the version range is valid, and `false` otherwise.\n */\nexport function isValidSemVerRange(\n versionRange: unknown,\n): versionRange is SemVerRange {\n return is(versionRange, VersionRangeStruct);\n}\n\n/**\n * Asserts that a value is a valid concrete SemVer version.\n *\n * @param version - A potential SemVer concrete version.\n */\nexport function assertIsSemVerVersion(\n version: unknown,\n): asserts version is SemVerVersion {\n assertStruct(version, VersionStruct);\n}\n\n/**\n * Asserts that a value is a valid SemVer range.\n *\n * @param range - A potential SemVer range.\n */\nexport function assertIsSemVerRange(\n range: unknown,\n): asserts range is SemVerRange {\n assertStruct(range, VersionRangeStruct);\n}\n\n/**\n * Checks whether a SemVer version is greater than another.\n *\n * @param version1 - The left-hand version.\n * @param version2 - The right-hand version.\n * @returns `version1 > version2`.\n */\nexport function gtVersion(\n version1: SemVerVersion,\n version2: SemVerVersion,\n): boolean {\n return gtSemver(version1, version2);\n}\n\n/**\n * Checks whether a SemVer version is greater than all possibilities in a range.\n *\n * @param version - A SemvVer version.\n * @param range - The range to check against.\n * @returns `version > range`.\n */\nexport function gtRange(version: SemVerVersion, range: SemVerRange): boolean {\n return gtrSemver(version, range);\n}\n\n/**\n * Returns whether a SemVer version satisfies a SemVer range.\n *\n * @param version - The SemVer version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns Whether the version satisfied the version range.\n */\nexport function satisfiesVersionRange(\n version: SemVerVersion,\n versionRange: SemVerRange,\n): boolean {\n return satisfiesSemver(version, versionRange, {\n includePrerelease: true,\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/utils",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.0",
|
|
4
4
|
"description": "Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -15,13 +15,12 @@
|
|
|
15
15
|
"scripts": {
|
|
16
16
|
"build": "tsc --project tsconfig.build.json",
|
|
17
17
|
"build:clean": "rimraf dist && yarn build",
|
|
18
|
-
"docs": "typedoc",
|
|
19
|
-
"docs:publish": "typedoc --cleanOutputDir false --gitRevision \"v$(jq -r .version < ./package.json)\"",
|
|
18
|
+
"build:docs": "typedoc",
|
|
20
19
|
"lint": "yarn lint:eslint && yarn lint:misc --check",
|
|
21
20
|
"lint:eslint": "eslint . --cache --ext js,ts",
|
|
22
21
|
"lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write",
|
|
23
|
-
"lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' --ignore-path .gitignore",
|
|
24
|
-
"
|
|
22
|
+
"lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore --no-error-on-unmatched-pattern",
|
|
23
|
+
"prepack": "./scripts/prepack.sh",
|
|
25
24
|
"test": "yarn test:source && yarn test:types",
|
|
26
25
|
"test:source": "jest",
|
|
27
26
|
"test:types": "tsd",
|
|
@@ -33,35 +32,36 @@
|
|
|
33
32
|
"dependencies": {
|
|
34
33
|
"@types/debug": "^4.1.7",
|
|
35
34
|
"debug": "^4.3.4",
|
|
35
|
+
"semver": "^7.3.8",
|
|
36
36
|
"superstruct": "^0.16.7"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@lavamoat/allow-scripts": "^2.0.3",
|
|
40
40
|
"@metamask/auto-changelog": "^2.3.0",
|
|
41
|
-
"@metamask/eslint-config": "^
|
|
42
|
-
"@metamask/eslint-config-jest": "^
|
|
43
|
-
"@metamask/eslint-config-nodejs": "^
|
|
44
|
-
"@metamask/eslint-config-typescript": "^
|
|
41
|
+
"@metamask/eslint-config": "^11.0.1",
|
|
42
|
+
"@metamask/eslint-config-jest": "^11.0.0",
|
|
43
|
+
"@metamask/eslint-config-nodejs": "^11.0.1",
|
|
44
|
+
"@metamask/eslint-config-typescript": "^11.0.0",
|
|
45
45
|
"@types/jest": "^28.1.7",
|
|
46
|
-
"@typescript-eslint/eslint-plugin": "^
|
|
47
|
-
"@typescript-eslint/parser": "^
|
|
48
|
-
"eslint": "^
|
|
49
|
-
"eslint-config-prettier": "^8.
|
|
50
|
-
"eslint-plugin-import": "^2.
|
|
51
|
-
"eslint-plugin-jest": "^
|
|
52
|
-
"eslint-plugin-jsdoc": "^
|
|
46
|
+
"@typescript-eslint/eslint-plugin": "^5.42.1",
|
|
47
|
+
"@typescript-eslint/parser": "^5.42.1",
|
|
48
|
+
"eslint": "^8.27.0",
|
|
49
|
+
"eslint-config-prettier": "^8.5.0",
|
|
50
|
+
"eslint-plugin-import": "^2.26.0",
|
|
51
|
+
"eslint-plugin-jest": "^27.1.5",
|
|
52
|
+
"eslint-plugin-jsdoc": "^39.6.2",
|
|
53
53
|
"eslint-plugin-node": "^11.1.0",
|
|
54
|
-
"eslint-plugin-prettier": "^
|
|
55
|
-
"jest": "^
|
|
54
|
+
"eslint-plugin-prettier": "^4.2.1",
|
|
55
|
+
"jest": "^29.2.2",
|
|
56
56
|
"json-bigint": "^1.0.0",
|
|
57
|
-
"prettier": "^2.
|
|
57
|
+
"prettier": "^2.7.1",
|
|
58
58
|
"prettier-plugin-packagejson": "^2.2.11",
|
|
59
59
|
"rimraf": "^3.0.2",
|
|
60
60
|
"stdio-mock": "^1.2.0",
|
|
61
|
-
"ts-jest": "^
|
|
61
|
+
"ts-jest": "^29.0.3",
|
|
62
62
|
"tsd": "^0.24.1",
|
|
63
63
|
"typedoc": "^0.23.10",
|
|
64
|
-
"typescript": "~4.
|
|
64
|
+
"typescript": "~4.8.4"
|
|
65
65
|
},
|
|
66
66
|
"packageManager": "yarn@3.2.3",
|
|
67
67
|
"engines": {
|