@metamask-previews/utils 11.12.1-preview-2caaa71 → 11.12.1-preview-4bb3dbb
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/CHANGELOG.md +4 -5
- package/dist/assert.d.ts.map +1 -1
- package/dist/assert.js.map +1 -1
- package/dist/base64.d.ts.map +1 -1
- package/dist/base64.js.map +1 -1
- package/dist/collections.d.ts +8 -8
- package/dist/collections.d.ts.map +1 -1
- package/dist/collections.js +6 -0
- package/dist/collections.js.map +1 -1
- package/dist/fs.js.map +1 -1
- package/dist/hashing.d.ts.map +1 -1
- package/dist/hashing.js +22 -8
- package/dist/hashing.js.map +1 -1
- package/dist/hex.d.ts.map +1 -1
- package/dist/hex.js.map +1 -1
- package/dist/json.d.ts.map +1 -1
- package/dist/json.js.map +1 -1
- package/dist/misc.d.ts.map +1 -1
- package/dist/misc.js.map +1 -1
- package/dist/time.js.map +1 -1
- package/dist/unitsConversion.d.ts.map +1 -1
- package/dist/unitsConversion.js +5 -2
- package/dist/unitsConversion.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,13 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Changed
|
|
11
11
|
|
|
12
|
-
- **BREAKING:** Bump
|
|
13
|
-
-
|
|
12
|
+
- **BREAKING:** Bump TypeScript target to ES2022 ([#332](https://github.com/MetaMask/utils/pull/332))
|
|
13
|
+
- This package now ships ES2022 code, requiring a compatible modern environment or bundler configuration to consume.
|
|
14
14
|
- **BREAKING:** Drop support for Node 18 and 20 ([#328](https://github.com/MetaMask/utils/pull/328))
|
|
15
|
-
- The supported range is now `^22.14.0 || ^24`, matching core.
|
|
16
15
|
- **BREAKING:** The package is now ESM only ([#323](https://github.com/MetaMask/utils/pull/323))
|
|
17
|
-
- The CommonJS build is gone. `
|
|
18
|
-
- `
|
|
16
|
+
- The CommonJS build is gone. `main` and `module` are removed, and both `.` and `./node` resolve through `exports` to a single `./dist/*.js` with `./dist/*.d.ts` types.
|
|
17
|
+
- `require()` continues to work on the supported Node.js versions, which load ES modules from CommonJS natively. Toolchains that do not support that will need to `import` instead.
|
|
19
18
|
- Consumers already using `import` are unaffected.
|
|
20
19
|
- Bump `@ethereumjs/tx` from `^4.2.0` to `^5.4.0` ([#321](https://github.com/MetaMask/utils/pull/321))
|
|
21
20
|
- The deprecated `Keyring.signTransaction` now returns `LegacyTxData` rather than `TxData`. These describe the same shape: `@ethereumjs/tx@5` repurposed the name `TxData` for a map keyed by transaction type and renamed the old meaning to `LegacyTxData`. Implementations do not need changing.
|
package/dist/assert.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assert.d.ts","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAKpD,MAAM,MAAM,yBAAyB,GACjC,CAAC,KAAK,IAAI,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,KAAK,KAAK,CAAC,GAC1C,CAAC,CAAC,IAAI,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,KAAK,KAAK,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"assert.d.ts","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAKpD,MAAM,MAAM,yBAAyB,GACjC,CAAC,KAAK,IAAI,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,KAAK,KAAK,CAAC,GAC1C,CAAC,CAAC,IAAI,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,KAAK,KAAK,CAAC,CAAC;AAoD3C;;GAEG;AACH,qBAAa,cAAe,SAAQ,KAAK;IACvC,QAAQ,CAAC,IAAI,mBAAmB;IAEhC,YAAY,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,EAEvC;CACF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,MAAM,CACpB,KAAK,EAAE,GAAG,EACV,OAAO,GAAE,MAAM,GAAG,KAA2B,EAC7C,YAAY,GAAE,yBAA0C,GACvD,OAAO,CAAC,KAAK,CAQf;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EACvC,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,EAC5B,WAAW,SAAqB,EAChC,YAAY,GAAE,yBAA0C,GACvD,OAAO,CAAC,KAAK,IAAI,IAAI,CASvB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,KAAK,GAAG,KAAK,CAItD"}
|
package/dist/assert.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assert.js","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,IAAI,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAEpE,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAM9C;;;;;;GAMG;AACH,SAAS,eAAe,CACtB,EAA6B;IAE7B,0BAA0B;IAC1B,OAAO,OAAO,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC;AACvE,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,oCAAoC,CAAC,KAAc;IAC1D,4BAA4B;IAC5B,OAAO,eAAe,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AACpD,CAAC;AAED;;;;;;GAMG;AACH,SAAS,QAAQ,
|
|
1
|
+
{"version":3,"file":"assert.js","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":"AACA,OAAO,EAA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,kBAAkB,EAChC,YAAY,GAA8B,cAAc;IAExD,IAAI,CAAC;QACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,CACZ,YAAY,EACZ,GAAG,WAAW,KAAK,oCAAoC,CAAC,KAAK,CAAC,GAAG,CAClE,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAc;IAC7C,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;AACJ,CAAC","sourcesContent":["import type { Struct } from '@metamask/superstruct';\nimport { assert as assertSuperstruct } from '@metamask/superstruct';\n\nimport { getErrorMessage } from './errors.js';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\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 * Attempts to obtain the message from a possible error object. If it is\n * possible to do so, any trailing period will be removed from the message;\n * otherwise an empty string is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The message without any trailing period if `error` is an object\n * with a `message` property; the string version of `error` without any trailing\n * period if it is not `undefined` or `null`; otherwise an empty string.\n */\nfunction getErrorMessageWithoutTrailingPeriod(error: unknown): string {\n // We'll add our own period.\n return getErrorMessage(error).replace(/\\.$/u, '');\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 */\nfunction getError(\n ErrorWrapper: AssertionErrorConstructor,\n message: string,\n): Error {\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 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<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n errorPrefix = 'Assertion failed',\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value is Type {\n try {\n assertSuperstruct(value, struct);\n } catch (error) {\n throw getError(\n ErrorWrapper,\n `${errorPrefix}: ${getErrorMessageWithoutTrailingPeriod(error)}.`,\n );\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.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAKpD,MAAM,MAAM,aAAa,GAAG;IAC1B;;;;OAIG;IAEH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,QAAQ,GAAG,WAAW,CAAC;CACvC,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,MAAM,GAAI,IAAI,SAAS,MAAM,EAAE,MAAM,UACxC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,YACnB,aAAa,
|
|
1
|
+
{"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAKpD,MAAM,MAAM,aAAa,GAAG;IAC1B;;;;OAIG;IAEH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,QAAQ,GAAG,WAAW,CAAC;CACvC,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,MAAM,GAAI,IAAI,SAAS,MAAM,EAAE,MAAM,UACxC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,YACnB,aAAa,KACrB,MAAM,CAAC,IAAI,EAAE,MAAM,CA0BrB,CAAC"}
|
package/dist/base64.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base64.js","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAmBrC;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,MAA4B,EAC5B,OAAO,GAAkB,EAAE,
|
|
1
|
+
{"version":3,"file":"base64.js","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAmBrC;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,MAA4B,EAC5B,OAAO,GAAkB,EAAE,EACL,EAAE;IACxB,MAAM,eAAe,GAAG,OAAO,CAAC,eAAe,IAAI,KAAK,CAAC;IACzD,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,QAAQ,CAAC;IAEtD,IAAI,OAAe,CAAC;IACpB,IAAI,YAAY,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,GAAG,MAAM,CAAC,GAAG,CAAA,gBAAgB,CAAC;IACvC,CAAC;SAAM,CAAC;QACN,MAAM,CAAC,YAAY,KAAK,WAAW,CAAC,CAAC;QACrC,OAAO,GAAG,MAAM,CAAC,GAAG,CAAA,eAAe,CAAC;IACtC,CAAC;IAED,IAAI,EAAU,CAAC;IACf,IAAI,eAAe,EAAE,CAAC;QACpB,EAAE,GAAG,IAAI,MAAM,CACb,OAAO,OAAO,WAAW,OAAO,QAAQ,OAAO,UAAU,EACzD,GAAG,CACJ,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,EAAE,GAAG,IAAI,MAAM,CACb,OAAO,OAAO,WAAW,OAAO,SAAS,OAAO,QAAQ,OAAO,UAAU,EACzE,GAAG,CACJ,CAAC;IACJ,CAAC;IAED,OAAO,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC,CAAC","sourcesContent":["import type { Struct } from '@metamask/superstruct';\nimport { pattern } from '@metamask/superstruct';\n\nimport { assert } from './assert.js';\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 = <Type extends string, Schema>(\n struct: Struct<Type, Schema>,\n options: Base64Options = {},\n): Struct<Type, Schema> => {\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/collections.d.ts
CHANGED
|
@@ -7,14 +7,14 @@
|
|
|
7
7
|
declare class FrozenMap<Key, Value> implements ReadonlyMap<Key, Value> {
|
|
8
8
|
#private;
|
|
9
9
|
get size(): number;
|
|
10
|
-
[Symbol.iterator]():
|
|
10
|
+
[Symbol.iterator](): ReturnType<Map<Key, Value>[typeof Symbol.iterator]>;
|
|
11
11
|
constructor(entries?: readonly (readonly [Key, Value])[] | null);
|
|
12
|
-
entries():
|
|
12
|
+
entries(): ReturnType<Map<Key, Value>['entries']>;
|
|
13
13
|
forEach(callbackfn: (value: Value, key: Key, map: this) => void, thisArg?: any): void;
|
|
14
14
|
get(key: Key): Value | undefined;
|
|
15
15
|
has(key: Key): boolean;
|
|
16
|
-
keys():
|
|
17
|
-
values():
|
|
16
|
+
keys(): ReturnType<Map<Key, Value>['keys']>;
|
|
17
|
+
values(): ReturnType<Map<Key, Value>['values']>;
|
|
18
18
|
toString(): string;
|
|
19
19
|
}
|
|
20
20
|
/**
|
|
@@ -26,13 +26,13 @@ declare class FrozenMap<Key, Value> implements ReadonlyMap<Key, Value> {
|
|
|
26
26
|
declare class FrozenSet<Value> implements ReadonlySet<Value> {
|
|
27
27
|
#private;
|
|
28
28
|
get size(): number;
|
|
29
|
-
[Symbol.iterator]():
|
|
29
|
+
[Symbol.iterator](): ReturnType<Set<Value>[typeof Symbol.iterator]>;
|
|
30
30
|
constructor(values?: readonly Value[] | null);
|
|
31
|
-
entries():
|
|
31
|
+
entries(): ReturnType<Set<Value>['entries']>;
|
|
32
32
|
forEach(callbackfn: (value: Value, value2: Value, set: this) => void, thisArg?: any): void;
|
|
33
33
|
has(value: Value): boolean;
|
|
34
|
-
keys():
|
|
35
|
-
values():
|
|
34
|
+
keys(): ReturnType<Set<Value>['keys']>;
|
|
35
|
+
values(): ReturnType<Set<Value>['values']>;
|
|
36
36
|
toString(): string;
|
|
37
37
|
}
|
|
38
38
|
export { FrozenMap, FrozenSet };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections.d.ts","sourceRoot":"","sources":["../src/collections.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAM,SAAS,CAAC,GAAG,EAAE,KAAK,CAAE,YAAW,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC;;
|
|
1
|
+
{"version":3,"file":"collections.d.ts","sourceRoot":"","sources":["../src/collections.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAM,SAAS,CAAC,GAAG,EAAE,KAAK,CAAE,YAAW,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC;;IAQ5D,IAAW,IAAI,IAAI,MAAM,CAExB;IAEM,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU,CACpC,GA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AE,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,KAAK,IAAI,EAC5D,OAAO,CAAC,EAAE,GAAG,GACZ,IAAI,CAMN;IAEM,GAAG,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAEhC;IAEM,IAAI,IAAI,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAE5C;IAEM,MAAM,IAAI,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,CAEhD;IAEM,QAAQ,IAAI,MAAM,CAMxB;CACF;AAQD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC"}
|
package/dist/collections.js
CHANGED
|
@@ -5,6 +5,11 @@
|
|
|
5
5
|
* to this map.
|
|
6
6
|
*/
|
|
7
7
|
class FrozenMap {
|
|
8
|
+
// The iterator methods below borrow their return types from the inner map
|
|
9
|
+
// rather than naming one. The name changed across TypeScript versions
|
|
10
|
+
// (`IterableIterator` became `MapIterator`), and `tsd` type tests run against
|
|
11
|
+
// a different version than the build, so any hardcoded name is wrong for one
|
|
12
|
+
// of them. Deriving the type keeps it correct under both.
|
|
8
13
|
#map;
|
|
9
14
|
get size() {
|
|
10
15
|
return this.#map.size;
|
|
@@ -51,6 +56,7 @@ class FrozenMap {
|
|
|
51
56
|
* to this set.
|
|
52
57
|
*/
|
|
53
58
|
class FrozenSet {
|
|
59
|
+
// Derived from the inner set for the same reason as `FrozenMap` above.
|
|
54
60
|
#set;
|
|
55
61
|
get size() {
|
|
56
62
|
return this.#set.size;
|
package/dist/collections.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections.js","sourceRoot":"","sources":["../src/collections.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,SAAS;
|
|
1
|
+
{"version":3,"file":"collections.js","sourceRoot":"","sources":["../src/collections.ts"],"names":[],"mappings":"AAA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AAC,IAAI,CAAC,IAAI,EAAE,CAAC;IAC1B,CAAC;IAEM,MAAM;QACX,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IAC5B,CAAC;IAEM,QAAQ;QACb,OAAO,aAAa,IAAI,CAAC,IAAI,MAC3B,IAAI,CAAC,IAAI,GAAG,CAAC;YACX,CAAC,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;YACtE,CAAC,CAAC,EACN,GAAG,CAAC;IACN,CAAC;CACF;AAED,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AACzB,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;AAEnC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AACzB,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;AAEnC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC","sourcesContent":["/**\n * A {@link ReadonlyMap} that cannot be modified after instantiation.\n * The implementation uses an inner map hidden via a private field, and the\n * immutability guarantee relies on it being impossible to get a reference\n * to this map.\n */\nclass FrozenMap<Key, Value> implements ReadonlyMap<Key, Value> {\n // The iterator methods below borrow their return types from the inner map\n // rather than naming one. The name changed across TypeScript versions\n // (`IterableIterator` became `MapIterator`), and `tsd` type tests run against\n // a different version than the build, so any hardcoded name is wrong for one\n // of them. Deriving the type keeps it correct under both.\n readonly #map: Map<Key, Value>;\n\n public get size(): number {\n return this.#map.size;\n }\n\n public [Symbol.iterator](): ReturnType<\n Map<Key, Value>[typeof Symbol.iterator]\n > {\n return this.#map[Symbol.iterator]();\n }\n\n constructor(entries?: readonly (readonly [Key, Value])[] | null) {\n this.#map = new Map<Key, Value>(entries);\n Object.freeze(this);\n }\n\n public entries(): ReturnType<Map<Key, Value>['entries']> {\n return this.#map.entries();\n }\n\n public forEach(\n callbackfn: (value: Value, key: Key, map: this) => void,\n thisArg?: any,\n ): void {\n // We have to wrap the specified callback in order to prevent it from\n // receiving a reference to the inner map.\n return this.#map.forEach((value: Value, key: Key, _map: unknown) =>\n callbackfn.call(thisArg, value, key, this),\n );\n }\n\n public get(key: Key): Value | undefined {\n return this.#map.get(key);\n }\n\n public has(key: Key): boolean {\n return this.#map.has(key);\n }\n\n public keys(): ReturnType<Map<Key, Value>['keys']> {\n return this.#map.keys();\n }\n\n public values(): ReturnType<Map<Key, Value>['values']> {\n return this.#map.values();\n }\n\n public toString(): string {\n return `FrozenMap(${this.size}) {${\n this.size > 0\n ? ` ${[...this.entries()]\n .map(([key, value]) => `${String(key)} => ${String(value)}`)\n .join(', ')} `\n : ''\n }}`;\n }\n}\n\n/**\n * A {@link ReadonlySet} that cannot be modified after instantiation.\n * The implementation uses an inner set hidden via a private field, and the\n * immutability guarantee relies on it being impossible to get a reference\n * to this set.\n */\nclass FrozenSet<Value> implements ReadonlySet<Value> {\n // Derived from the inner set for the same reason as `FrozenMap` above.\n readonly #set: Set<Value>;\n\n public get size(): number {\n return this.#set.size;\n }\n\n public [Symbol.iterator](): ReturnType<Set<Value>[typeof Symbol.iterator]> {\n return this.#set[Symbol.iterator]();\n }\n\n constructor(values?: readonly Value[] | null) {\n this.#set = new Set<Value>(values);\n Object.freeze(this);\n }\n\n public entries(): ReturnType<Set<Value>['entries']> {\n return this.#set.entries();\n }\n\n public forEach(\n callbackfn: (value: Value, value2: Value, set: this) => void,\n thisArg?: any,\n ): void {\n // We have to wrap the specified callback in order to prevent it from\n // receiving a reference to the inner set.\n return this.#set.forEach((value: Value, value2: Value, _set: unknown) =>\n callbackfn.call(thisArg, value, value2, this),\n );\n }\n\n public has(value: Value): boolean {\n return this.#set.has(value);\n }\n\n public keys(): ReturnType<Set<Value>['keys']> {\n return this.#set.keys();\n }\n\n public values(): ReturnType<Set<Value>['values']> {\n return this.#set.values();\n }\n\n public toString(): string {\n return `FrozenSet(${this.size}) {${\n this.size > 0\n ? ` ${[...this.values()].map((member) => String(member)).join(', ')} `\n : ''\n }}`;\n }\n}\n\nObject.freeze(FrozenMap);\nObject.freeze(FrozenMap.prototype);\n\nObject.freeze(FrozenSet);\nObject.freeze(FrozenSet.prototype);\n\nexport { FrozenMap, FrozenSet };\n"]}
|
package/dist/fs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fs.js","sourceRoot":"","sources":["../src/fs.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,+CAA+C;AAE/C,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAczD;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,QAAgB;IAC7C,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IACtD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,SAAS,CAAC,KAAK,EAAE,wBAAwB,QAAQ,GAAG,CAAC,CAAC;IAC9D,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,QAAgB,EAChB,OAAe;IAEf,IAAI,CAAC;QACH,MAAM,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACrE,MAAM,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,QAAQ,EAAE,O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AAK,EACL,yCAAyC,aAAa,GAAG,CAC1D,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,SAAiB;IACjD,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,SAAS,EAAE;YACrC,SAAS,EAAE,IAAI;YACf,KAAK,EAAE,IAAI;SACZ,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,SAAS,CAAC,KAAK,EAAE,uCAAuC,SAAS,GAAG,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,aAAa,CAAC,WAAmB;IAC/C,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;IAEpE,OAAO;QACL,aAAa;QACb,KAAK,CAAC,aAAa,CACjB,IAAwD;YAExD,IAAI,MAAM,eAAe,CAAC,aAAa,CAAC,EAAE,CAAC;gBACzC,MAAM,IAAI,KAAK,CAAC,GAAG,aAAa,mCAAmC,CAAC,CAAC;YACvE,CAAC;YAED,MAAM,8BAA8B,CAAC,aAAa,CAAC,CAAC;YAEpD,IAAI,CAAC;gBACH,MAAM,IAAI,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC;YAChC,CAAC;oBAAS,CAAC;gBACT,MAAM,WAAW,CAAC,aAAa,CAAC,CAAC;YACnC,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// This file is intended to be used only in a Node.js context.\n/* eslint-disable import-x/no-nodejs-modules */\n\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport { v4 as uuidV4 } from 'uuid';\n\nimport { isErrorWithCode, wrapError } from './errors.js';\nimport type { Json } from './json.js';\n\n/**\n * Information about the file sandbox provided to tests that need temporary\n * access to the filesystem.\n */\nexport type FileSandbox = {\n directoryPath: string;\n withinSandbox: (\n test: (args: { directoryPath: string }) => Promise<void>,\n ) => Promise<void>;\n};\n\n/**\n * Read the file at the given path, assuming its content is encoded as UTF-8.\n *\n * @param filePath - The path to the file.\n * @returns The content of the file.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function readFile(filePath: string): Promise<string> {\n try {\n return await fs.promises.readFile(filePath, 'utf8');\n } catch (error) {\n throw wrapError(error, `Could not read file '${filePath}'`);\n }\n}\n\n/**\n * Write content to the file at the given path, creating the directory structure\n * for the file automatically if necessary.\n *\n * @param filePath - The path to the file.\n * @param content - The new content of the file.\n * @throws An error with a stack trace if writing fails in any way.\n */\nexport async function writeFile(\n filePath: string,\n content: string,\n): Promise<void> {\n try {\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n await fs.promises.writeFile(filePath, content);\n } catch (error) {\n throw wrapError(error, `Could not write file '${filePath}'`);\n }\n}\n\n/**\n * Read the assumed JSON file at the given path, attempts to parse it, and\n * get the resulting object. Supports a custom parser (in case you want to\n * use the [JSON5](https://www.npmjs.com/package/json5) package instead).\n *\n * @param filePath - The path segments pointing to the JSON file. Will be passed\n * to path.join().\n * @param options - Options to this function.\n * @param options.parser - The parser object to use. Defaults to `JSON`.\n * @param options.parser.parse - A function that parses JSON data.\n * @returns The object corresponding to the parsed JSON file, typed against the\n * struct.\n * @throws An error with a stack trace if reading fails in any way, or if the\n * parsed value is not a plain object.\n */\nexport async function readJsonFile<Value extends Json>(\n filePath: string,\n {\n parser = JSON,\n }: {\n parser?: {\n parse: (\n text: Parameters<typeof JSON.parse>[0],\n ) => ReturnType<typeof JSON.parse>;\n };\n } = {},\n): Promise<Value> {\n try {\n const content = await fs.promises.readFile(filePath, 'utf8');\n return parser.parse(content);\n } catch (error) {\n throw wrapError(error, `Could not read JSON file '${filePath}'`);\n }\n}\n\n/**\n * Attempt to write the given JSON-like value to the file at the given path,\n * creating the directory structure for the file automatically if necessary.\n * Adds a newline to the end of the file. Supports a custom parser (in case you\n * want to use the [JSON5](https://www.npmjs.com/package/json5) package\n * instead).\n *\n * @param filePath - The path to write the JSON file to, including the file\n * itself.\n * @param jsonValue - The JSON-like value to write to the file. Make sure that\n * JSON.stringify can handle it.\n * @param options - The options to this function.\n * @param options.prettify - Whether to format the JSON as it is turned into a\n * string such that it is broken up into separate lines (using 2 spaces as\n * indentation).\n * @param options.stringifier - The stringifier to use. Defaults to `JSON`.\n * @param options.stringifier.stringify - A function that stringifies JSON.\n * @returns The object corresponding to the parsed JSON file, typed against the\n * struct.\n * @throws An error with a stack trace if writing fails in any way.\n */\nexport async function writeJsonFile(\n filePath: string,\n jsonValue: Json,\n {\n stringifier = JSON,\n prettify = false,\n }: {\n stringifier?: {\n stringify: typeof JSON.stringify;\n };\n prettify?: boolean;\n } = {},\n): Promise<void> {\n try {\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n const json = prettify\n ? stringifier.stringify(jsonValue, null, ' ')\n : stringifier.stringify(jsonValue);\n await fs.promises.writeFile(filePath, json);\n } catch (error) {\n throw wrapError(error, `Could not write JSON file '${filePath}'`);\n }\n}\n\n/**\n * Test the given path to determine whether it represents a file.\n *\n * @param filePath - The path to a (supposed) file on the filesystem.\n * @returns A promise for true if the file exists or false otherwise.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(filePath);\n return stats.isFile();\n } catch (error) {\n if (isErrorWithCode(error) && error.code === 'ENOENT') {\n return false;\n }\n\n throw wrapError(error, `Could not determine if file exists '${filePath}'`);\n }\n}\n\n/**\n * Test the given path to determine whether it represents a directory.\n *\n * @param directoryPath - The path to a (supposed) directory on the filesystem.\n * @returns A promise for true if the file exists or false otherwise.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function directoryExists(directoryPath: string): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(directoryPath);\n return stats.isDirectory();\n } catch (error) {\n if (isErrorWithCode(error) && error.code === 'ENOENT') {\n return false;\n }\n\n throw wrapError(\n error,\n `Could not determine if directory exists '${directoryPath}'`,\n );\n }\n}\n\n/**\n * Create the given directory along with any directories leading up to the\n * directory, or do nothing if the directory already exists.\n *\n * @param directoryPath - The path to the desired directory.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function ensureDirectoryStructureExists(\n directoryPath: string,\n): Promise<void> {\n try {\n await fs.promises.mkdir(directoryPath, { recursive: true });\n } catch (error) {\n throw wrapError(\n error,\n `Could not create directory structure '${directoryPath}'`,\n );\n }\n}\n\n/**\n * Remove the given file or directory if it exists, or do nothing if it does\n * not.\n *\n * @param entryPath - The path to the file or directory.\n * @throws An error with a stack trace if removal fails in any way.\n */\nexport async function forceRemove(entryPath: string): Promise<void> {\n try {\n return await fs.promises.rm(entryPath, {\n recursive: true,\n force: true,\n });\n } catch (error) {\n throw wrapError(error, `Could not remove file or directory '${entryPath}'`);\n }\n}\n\n/**\n * Construct a sandbox object which can be used in tests that need temporary\n * access to the filesystem.\n *\n * @param projectName - The name of the project.\n * @returns The sandbox object. This contains a `withinSandbox` function which\n * can be used in tests (see example).\n * @example\n * ```typescript\n * const { withinSandbox } = createSandbox('utils');\n *\n * // ... later ...\n *\n * it('does something with the filesystem', async () => {\n * await withinSandbox(async ({ directoryPath }) => {\n * await fs.promises.writeFile(\n * path.join(directoryPath, 'some-file'),\n * 'some content',\n * 'utf8'\n * );\n * })\n * });\n * ```\n */\nexport function createSandbox(projectName: string): FileSandbox {\n const directoryPath = path.join(os.tmpdir(), projectName, uuidV4());\n\n return {\n directoryPath,\n async withinSandbox(\n test: (args: { directoryPath: string }) => Promise<void>,\n ) {\n if (await directoryExists(directoryPath)) {\n throw new Error(`${directoryPath} already exists. Cannot continue.`);\n }\n\n await ensureDirectoryStructureExists(directoryPath);\n\n try {\n await test({ directoryPath });\n } finally {\n await forceRemove(directoryPath);\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3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CAAC;QACf,MAAM,SAAS,CAAC,KAAK,EAAE,uCAAuC,SAAS,GAAG,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,aAAa,CAAC,WAAmB;IAC/C,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;IAEpE,OAAO;QACL,aAAa;QACb,KAAK,CAAC,aAAa,CACjB,IAAwD;YAExD,IAAI,MAAM,eAAe,CAAC,aAAa,CAAC,EAAE,CAAC;gBACzC,MAAM,IAAI,KAAK,CAAC,GAAG,aAAa,mCAAmC,CAAC,CAAC;YACvE,CAAC;YAED,MAAM,8BAA8B,CAAC,aAAa,CAAC,CAAC;YAEpD,IAAI,CAAC;gBACH,MAAM,IAAI,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC;YAChC,CAAC;oBAAS,CAAC;gBACT,MAAM,WAAW,CAAC,aAAa,CAAC,CAAC;YACnC,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// This file is intended to be used only in a Node.js context.\n/* eslint-disable import-x/no-nodejs-modules */\n\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport { v4 as uuidV4 } from 'uuid';\n\nimport { isErrorWithCode, wrapError } from './errors.js';\nimport type { Json } from './json.js';\n\n/**\n * Information about the file sandbox provided to tests that need temporary\n * access to the filesystem.\n */\nexport type FileSandbox = {\n directoryPath: string;\n withinSandbox: (\n test: (args: { directoryPath: string }) => Promise<void>,\n ) => Promise<void>;\n};\n\n/**\n * Read the file at the given path, assuming its content is encoded as UTF-8.\n *\n * @param filePath - The path to the file.\n * @returns The content of the file.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function readFile(filePath: string): Promise<string> {\n try {\n return await fs.promises.readFile(filePath, 'utf8');\n } catch (error) {\n throw wrapError(error, `Could not read file '${filePath}'`);\n }\n}\n\n/**\n * Write content to the file at the given path, creating the directory structure\n * for the file automatically if necessary.\n *\n * @param filePath - The path to the file.\n * @param content - The new content of the file.\n * @throws An error with a stack trace if writing fails in any way.\n */\nexport async function writeFile(\n filePath: string,\n content: string,\n): Promise<void> {\n try {\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n await fs.promises.writeFile(filePath, content);\n } catch (error) {\n throw wrapError(error, `Could not write file '${filePath}'`);\n }\n}\n\n/**\n * Read the assumed JSON file at the given path, attempts to parse it, and\n * get the resulting object. Supports a custom parser (in case you want to\n * use the [JSON5](https://www.npmjs.com/package/json5) package instead).\n *\n * @param filePath - The path segments pointing to the JSON file. Will be passed\n * to path.join().\n * @param options - Options to this function.\n * @param options.parser - The parser object to use. Defaults to `JSON`.\n * @param options.parser.parse - A function that parses JSON data.\n * @returns The object corresponding to the parsed JSON file, typed against the\n * struct.\n * @throws An error with a stack trace if reading fails in any way, or if the\n * parsed value is not a plain object.\n */\nexport async function readJsonFile<Value extends Json>(\n filePath: string,\n {\n parser = JSON,\n }: {\n parser?: {\n parse: (\n text: Parameters<typeof JSON.parse>[0],\n ) => ReturnType<typeof JSON.parse>;\n };\n } = {},\n): Promise<Value> {\n try {\n const content = await fs.promises.readFile(filePath, 'utf8');\n return parser.parse(content);\n } catch (error) {\n throw wrapError(error, `Could not read JSON file '${filePath}'`);\n }\n}\n\n/**\n * Attempt to write the given JSON-like value to the file at the given path,\n * creating the directory structure for the file automatically if necessary.\n * Adds a newline to the end of the file. Supports a custom parser (in case you\n * want to use the [JSON5](https://www.npmjs.com/package/json5) package\n * instead).\n *\n * @param filePath - The path to write the JSON file to, including the file\n * itself.\n * @param jsonValue - The JSON-like value to write to the file. Make sure that\n * JSON.stringify can handle it.\n * @param options - The options to this function.\n * @param options.prettify - Whether to format the JSON as it is turned into a\n * string such that it is broken up into separate lines (using 2 spaces as\n * indentation).\n * @param options.stringifier - The stringifier to use. Defaults to `JSON`.\n * @param options.stringifier.stringify - A function that stringifies JSON.\n * @returns The object corresponding to the parsed JSON file, typed against the\n * struct.\n * @throws An error with a stack trace if writing fails in any way.\n */\nexport async function writeJsonFile(\n filePath: string,\n jsonValue: Json,\n {\n stringifier = JSON,\n prettify = false,\n }: {\n stringifier?: {\n stringify: typeof JSON.stringify;\n };\n prettify?: boolean;\n } = {},\n): Promise<void> {\n try {\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n const json = prettify\n ? stringifier.stringify(jsonValue, null, ' ')\n : stringifier.stringify(jsonValue);\n await fs.promises.writeFile(filePath, json);\n } catch (error) {\n throw wrapError(error, `Could not write JSON file '${filePath}'`);\n }\n}\n\n/**\n * Test the given path to determine whether it represents a file.\n *\n * @param filePath - The path to a (supposed) file on the filesystem.\n * @returns A promise for true if the file exists or false otherwise.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(filePath);\n return stats.isFile();\n } catch (error) {\n if (isErrorWithCode(error) && error.code === 'ENOENT') {\n return false;\n }\n\n throw wrapError(error, `Could not determine if file exists '${filePath}'`);\n }\n}\n\n/**\n * Test the given path to determine whether it represents a directory.\n *\n * @param directoryPath - The path to a (supposed) directory on the filesystem.\n * @returns A promise for true if the file exists or false otherwise.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function directoryExists(directoryPath: string): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(directoryPath);\n return stats.isDirectory();\n } catch (error) {\n if (isErrorWithCode(error) && error.code === 'ENOENT') {\n return false;\n }\n\n throw wrapError(\n error,\n `Could not determine if directory exists '${directoryPath}'`,\n );\n }\n}\n\n/**\n * Create the given directory along with any directories leading up to the\n * directory, or do nothing if the directory already exists.\n *\n * @param directoryPath - The path to the desired directory.\n * @throws An error with a stack trace if reading fails in any way.\n */\nexport async function ensureDirectoryStructureExists(\n directoryPath: string,\n): Promise<void> {\n try {\n await fs.promises.mkdir(directoryPath, { recursive: true });\n } catch (error) {\n throw wrapError(\n error,\n `Could not create directory structure '${directoryPath}'`,\n );\n }\n}\n\n/**\n * Remove the given file or directory if it exists, or do nothing if it does\n * not.\n *\n * @param entryPath - The path to the file or directory.\n * @throws An error with a stack trace if removal fails in any way.\n */\nexport async function forceRemove(entryPath: string): Promise<void> {\n try {\n return await fs.promises.rm(entryPath, {\n recursive: true,\n force: true,\n });\n } catch (error) {\n throw wrapError(error, `Could not remove file or directory '${entryPath}'`);\n }\n}\n\n/**\n * Construct a sandbox object which can be used in tests that need temporary\n * access to the filesystem.\n *\n * @param projectName - The name of the project.\n * @returns The sandbox object. This contains a `withinSandbox` function which\n * can be used in tests (see example).\n * @example\n * ```typescript\n * const { withinSandbox } = createSandbox('utils');\n *\n * // ... later ...\n *\n * it('does something with the filesystem', async () => {\n * await withinSandbox(async ({ directoryPath }) => {\n * await fs.promises.writeFile(\n * path.join(directoryPath, 'some-file'),\n * 'some content',\n * 'utf8'\n * );\n * })\n * });\n * ```\n */\nexport function createSandbox(projectName: string): FileSandbox {\n const directoryPath = path.join(os.tmpdir(), projectName, uuidV4());\n\n return {\n directoryPath,\n async withinSandbox(\n test: (args: { directoryPath: string }) => Promise<void>,\n ): Promise<void> {\n if (await directoryExists(directoryPath)) {\n throw new Error(`${directoryPath} already exists. Cannot continue.`);\n }\n\n await ensureDirectoryStructureExists(directoryPath);\n\n try {\n await test({ directoryPath });\n } finally {\n await forceRemove(directoryPath);\n }\n },\n };\n}\n"]}
|
package/dist/hashing.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hashing.d.ts","sourceRoot":"","sources":["../src/hashing.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"hashing.d.ts","sourceRoot":"","sources":["../src/hashing.ts"],"names":[],"mappings":"AAyBA;;;;;;;GAOG;AACH,wBAAsB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAanE;AAED;;;;;;;GAOG;AACH,wBAAsB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAanE;AAED;;;;;;;GAOG;AACH,wBAAsB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAanE"}
|
package/dist/hashing.js
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
import { sha256 as nobleSha256 } from '@noble/hashes/sha256';
|
|
2
2
|
import { sha512 as nobleSha512, sha384 as nobleSha384, } from '@noble/hashes/sha512';
|
|
3
|
+
/**
|
|
4
|
+
* Check whether a byte array is backed by an `ArrayBuffer` rather than a
|
|
5
|
+
* `SharedArrayBuffer`.
|
|
6
|
+
*
|
|
7
|
+
* `crypto.subtle.digest` takes a `BufferSource`, which excludes views on a
|
|
8
|
+
* `SharedArrayBuffer`: passing one throws `TypeError: 2nd argument is a view
|
|
9
|
+
* on a SharedArrayBuffer`. TypeScript models this correctly, so this guard
|
|
10
|
+
* both satisfies the compiler and keeps the runtime honest. Shared inputs fall
|
|
11
|
+
* through to noble, which handles them and returns an identical digest.
|
|
12
|
+
*
|
|
13
|
+
* @param bytes - A byte array.
|
|
14
|
+
* @returns Whether the array is backed by an `ArrayBuffer`.
|
|
15
|
+
*/
|
|
16
|
+
function isArrayBufferBacked(bytes) {
|
|
17
|
+
return bytes.buffer instanceof ArrayBuffer;
|
|
18
|
+
}
|
|
3
19
|
/**
|
|
4
20
|
* Compute a SHA-256 digest for a given byte array.
|
|
5
21
|
*
|
|
@@ -8,16 +24,12 @@ import { sha512 as nobleSha512, sha384 as nobleSha384, } from '@noble/hashes/sha
|
|
|
8
24
|
* @param bytes - A byte array.
|
|
9
25
|
* @returns The SHA-256 hash as a byte array.
|
|
10
26
|
*/
|
|
11
|
-
// `crypto.subtle.digest` takes a `BufferSource`, which TypeScript 7 will not
|
|
12
|
-
// accept a plain `Uint8Array` for: it is now generic over the buffer, so it
|
|
13
|
-
// could be backed by a `SharedArrayBuffer`. Runtimes accept those, and
|
|
14
|
-
// narrowing the exported signatures below would break callers, so the
|
|
15
|
-
// assertion is kept at the call sites.
|
|
16
27
|
export async function sha256(bytes) {
|
|
17
28
|
// Use crypto.subtle.digest whenever possible as it is faster.
|
|
18
29
|
if ('crypto' in globalThis &&
|
|
19
30
|
typeof globalThis.crypto === 'object' &&
|
|
20
|
-
globalThis.crypto.subtle?.digest
|
|
31
|
+
globalThis.crypto.subtle?.digest &&
|
|
32
|
+
isArrayBufferBacked(bytes)) {
|
|
21
33
|
return new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes));
|
|
22
34
|
}
|
|
23
35
|
return nobleSha256(bytes);
|
|
@@ -34,7 +46,8 @@ export async function sha512(bytes) {
|
|
|
34
46
|
// Use crypto.subtle.digest whenever possible as it is faster.
|
|
35
47
|
if ('crypto' in globalThis &&
|
|
36
48
|
typeof globalThis.crypto === 'object' &&
|
|
37
|
-
globalThis.crypto.subtle?.digest
|
|
49
|
+
globalThis.crypto.subtle?.digest &&
|
|
50
|
+
isArrayBufferBacked(bytes)) {
|
|
38
51
|
return new Uint8Array(await globalThis.crypto.subtle.digest('SHA-512', bytes));
|
|
39
52
|
}
|
|
40
53
|
return nobleSha512(bytes);
|
|
@@ -51,7 +64,8 @@ export async function sha384(bytes) {
|
|
|
51
64
|
// Use crypto.subtle.digest whenever possible as it is faster.
|
|
52
65
|
if ('crypto' in globalThis &&
|
|
53
66
|
typeof globalThis.crypto === 'object' &&
|
|
54
|
-
globalThis.crypto.subtle?.digest
|
|
67
|
+
globalThis.crypto.subtle?.digest &&
|
|
68
|
+
isArrayBufferBacked(bytes)) {
|
|
55
69
|
return new Uint8Array(await globalThis.crypto.subtle.digest('SHA-384', bytes));
|
|
56
70
|
}
|
|
57
71
|
return nobleSha384(bytes);
|
package/dist/hashing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hashing.js","sourceRoot":"","sources":["../src/hashing.ts"],"names":[],"mappings":"AAAA,OAA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AAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,CACxD,CAAC;IACJ,CAAC;IACD,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC;AAC5B,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,KAAiB;IAC5C,8DAA8D;IAC9D,IACE,QAAQ,IAAI,UAAU;QACtB,OAAO,UAAU,CAAC,MAAM,KAAK,QAAQ;QACrC,UAAU,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM;QAChC,mBAAmB,CAAC,KAAK,CAAC,EAC1B,CAAC;QACD,OAAO,IAAI,UAAU,CACnB,MAAM,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,CACxD,CAAC;IACJ,CAAC;IACD,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { sha256 as nobleSha256 } from '@noble/hashes/sha256';\nimport {\n sha512 as nobleSha512,\n sha384 as nobleSha384,\n} from '@noble/hashes/sha512';\n\n/**\n * Check whether a byte array is backed by an `ArrayBuffer` rather than a\n * `SharedArrayBuffer`.\n *\n * `crypto.subtle.digest` takes a `BufferSource`, which excludes views on a\n * `SharedArrayBuffer`: passing one throws `TypeError: 2nd argument is a view\n * on a SharedArrayBuffer`. TypeScript models this correctly, so this guard\n * both satisfies the compiler and keeps the runtime honest. Shared inputs fall\n * through to noble, which handles them and returns an identical digest.\n *\n * @param bytes - A byte array.\n * @returns Whether the array is backed by an `ArrayBuffer`.\n */\nfunction isArrayBufferBacked(\n bytes: Uint8Array,\n): bytes is Uint8Array & { buffer: ArrayBuffer } {\n return bytes.buffer instanceof ArrayBuffer;\n}\n\n/**\n * Compute a SHA-256 digest for a given byte array.\n *\n * Uses the native crypto implementation and falls back to noble.\n *\n * @param bytes - A byte array.\n * @returns The SHA-256 hash as a byte array.\n */\nexport async function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n // Use crypto.subtle.digest whenever possible as it is faster.\n if (\n 'crypto' in globalThis &&\n typeof globalThis.crypto === 'object' &&\n globalThis.crypto.subtle?.digest &&\n isArrayBufferBacked(bytes)\n ) {\n return new Uint8Array(\n await globalThis.crypto.subtle.digest('SHA-256', bytes),\n );\n }\n return nobleSha256(bytes);\n}\n\n/**\n * Compute a SHA-512 digest for a given byte array.\n *\n * Uses the native crypto implementation and falls back to noble.\n *\n * @param bytes - A byte array.\n * @returns The SHA-512 hash as a byte array.\n */\nexport async function sha512(bytes: Uint8Array): Promise<Uint8Array> {\n // Use crypto.subtle.digest whenever possible as it is faster.\n if (\n 'crypto' in globalThis &&\n typeof globalThis.crypto === 'object' &&\n globalThis.crypto.subtle?.digest &&\n isArrayBufferBacked(bytes)\n ) {\n return new Uint8Array(\n await globalThis.crypto.subtle.digest('SHA-512', bytes),\n );\n }\n return nobleSha512(bytes);\n}\n\n/**\n * Compute a SHA-384 digest for a given byte array.\n *\n * Uses the native crypto implementation and falls back to noble.\n *\n * @param bytes - A byte array.\n * @returns The SHA-384 hash as a byte array.\n */\nexport async function sha384(bytes: Uint8Array): Promise<Uint8Array> {\n // Use crypto.subtle.digest whenever possible as it is faster.\n if (\n 'crypto' in globalThis &&\n typeof globalThis.crypto === 'object' &&\n globalThis.crypto.subtle?.digest &&\n isArrayBufferBacked(bytes)\n ) {\n return new Uint8Array(\n await globalThis.crypto.subtle.digest('SHA-384', bytes),\n );\n }\n return nobleSha384(bytes);\n}\n"]}
|
package/dist/hex.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hex.d.ts","sourceRoot":"","sources":["../src/hex.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAMpD,MAAM,MAAM,GAAG,GAAG,KAAK,MAAM,EAAE,CAAC;AAShC,eAAO,MAAM,SAAS,sBAA+B,CAAC;AACtD,eAAO,MAAM,eAAe,EAA0C,MAA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;IACvC,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACjC,OAAO,WAAkB,CAAC;IAC5B,CAAC;IAED,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACjC,OAAO,KAAK,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;IACzC,CAAC;IAED,OAAO,KAAK,WAAW,EAAE,CAAC;AAC5B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAAC,WAAmB;IAC1C,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACjE,OAAO,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAClC,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { pattern, string } from '@metamask/superstruct';\nimport type { Struct } from '@metamask/superstruct';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport memoize from 'lodash/memoize.js';\n\nimport { assert } from './assert.js';\n\nexport type Hex = `0x${string}`;\n\n// Use native regexes instead of superstruct for maximum performance.\n// Pre-compiled regex for maximum performance - avoids recompilation on each call\nconst HEX_REGEX = /^(?:0x)?[0-9a-f]+$/iu;\nconst STRICT_HEX_REGEX = /^0x[0-9a-f]+$/iu;\nconst HEX_ADDRESS_REGEX = /^0x[0-9a-f]{40}$/u;\nconst HEX_CHECKSUM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/u;\n\nexport const HexStruct = pattern(string(), HEX_REGEX);\nexport const StrictHexStruct = pattern(string(), STRICT_HEX_REGEX) as Struct<\n Hex,\n null\n>;\nexport const HexAddressStruct = pattern(string(), HEX_ADDRESS_REGEX) as Struct<\n Hex,\n null\n>;\nexport const HexChecksumAddressStruct = pattern(\n string(),\n HEX_CHECKSUM_ADDRESS_REGEX,\n) as Struct<Hex, null>;\n\nconst isString = (value: unknown): value is string => typeof value === 'string';\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 isString(value) && HEX_REGEX.test(value);\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 isString(value) && STRICT_HEX_REGEX.test(value);\n}\n\n/**\n * Check if a string is a valid hex address.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex address.\n */\nexport function isHexAddress(value: unknown): value is Hex {\n return isString(value) && HEX_ADDRESS_REGEX.test(value);\n}\n\n/**\n * Check if a string is a valid hex checksum address.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex checksum address.\n */\nexport function isHexChecksumAddress(value: unknown): value is Hex {\n return isString(value) && HEX_CHECKSUM_ADDRESS_REGEX.test(value);\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 * Encode a passed hex string as an ERC-55 mixed-case checksum address.\n * This is the unmemoized version, primarily used for testing.\n *\n * @param hexAddress - The hex address to encode.\n * @returns The address encoded according to ERC-55.\n * @see https://eips.ethereum.org/EIPS/eip-55\n */\nexport function getChecksumAddressUnmemoized(hexAddress: Hex): Hex {\n assert(isHexChecksumAddress(hexAddress), 'Invalid hex address.');\n const address = remove0x(hexAddress).toLowerCase();\n\n const hashBytes = keccak256(address);\n const { length } = address;\n const result = new Array(length); // Pre-allocate array\n\n for (let i = 0; i < length; i++) {\n /* eslint-disable no-bitwise */\n const byteIndex = i >> 1; // Faster than Math.floor(i / 2)\n const nibbleIndex = i & 1; // Faster than i % 2\n const byte = hashBytes[byteIndex] as number;\n const nibble = nibbleIndex === 0 ? byte >> 4 : byte & 0x0f;\n /* eslint-enable no-bitwise */\n\n result[i] = nibble >= 8 ? (address[i] as string).toUpperCase() : address[i];\n }\n\n return `0x${result.join('')}`;\n}\n\n/**\n * Encode a passed hex string as an ERC-55 mixed-case checksum address.\n * This function is memoized for performance.\n *\n * @param hexAddress - The hex address to encode.\n * @returns The address encoded according to ERC-55.\n * @see https://eips.ethereum.org/EIPS/eip-55\n */\nexport const getChecksumAddress = memoize(getChecksumAddressUnmemoized);\n\n/**\n * Validate that the passed hex string is a valid ERC-55 mixed-case\n * checksum address.\n *\n * @param possibleChecksum - The hex address to check.\n * @returns True if the address is a checksum address.\n */\nexport function isValidChecksumAddressUnmemoized(possibleChecksum: Hex) {\n if (!isHexChecksumAddress(possibleChecksum)) {\n return false;\n }\n\n return getChecksumAddress(possibleChecksum) === possibleChecksum;\n}\n\n/**\n * Validate that the passed hex string is a valid ERC-55 mixed-case\n * checksum address.\n *\n * @param possibleChecksum - The hex address to check.\n * @returns True if the address is a checksum address.\n */\nexport const isValidChecksumAddress = memoize(isValidChecksumAddressUnmemoized);\n\n/**\n * Validate that the passed prefixed hex string is an all-lowercase\n * hex address, or a valid mixed-case checksum address.\n *\n * @param possibleAddress - Input parameter to check against.\n * @returns Whether or not the input is a valid hex address.\n */\nexport function isValidHexAddressUnmemoized(possibleAddress: Hex) {\n return (\n isHexAddress(possibleAddress) || isValidChecksumAddress(possibleAddress)\n );\n}\n\n/**\n * Validate that the passed prefixed hex string is an all-lowercase\n * hex address, or a valid mixed-case checksum address.\n *\n * @param possibleAddress - Input parameter to check against.\n * @returns Whether or not the input is a valid hex address.\n */\nexport const isValidHexAddress = memoize(isValidHexAddressUnmemoized);\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"]}
|
|
1
|
+
{"version":3,"file":"hex.js","sourceRoot":"","sources":["../src/hex.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAE,UAAU,IAAI,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,OAAO,MAAM,mBAAmB,CAAC;AAExC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAIrC,qEAAqE;AACrE,iFAAiF;AACjF,MAAM,SAAS,GAAG,sBAAsB,CAAC;AACzC,MAAM,gBAAgB,GAAG,iBAAiB,CAAC;AAC3C,MAAM,iBAAiB,GAAG,mBAAmB,CAAC;AAC9C,MAAM,0BAA0B,GAAG,sBAAsB,CAAC;AAE1D,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,EAAE,EAAE,SAAS,CAAC,CAAC;AACtD,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,EAAE,EAAE,gBAAgB,CAGhE,CAAC;AACF,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,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C;AACnE,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,OAAO,CAAC,gCAAgC,CAAC,CAAC;AAEhF;;;;;;GAMG;AACH,MAAM,UAAU,2BAA2B,CAAC,eAAoB;IAC9D,OAAO,CACL,YAAY,CAAC,eAAe,CAAC,IAAI,sBAAsB,CAAC,eAAe,CAAC,CACzE,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,UAAU,KAAK,CAAC,WAAmB;IACvC,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACjC,OAAO,WAAkB,CAAC;IAC5B,CAAC;IAED,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACjC,OAAO,KAAK,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;IACzC,CAAC;IAED,OAAO,KAAK,WAAW,EAAE,CAAC;AAC5B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAAC,WAAmB;IAC1C,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACjE,OAAO,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAClC,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { pattern, string } from '@metamask/superstruct';\nimport type { Struct } from '@metamask/superstruct';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport memoize from 'lodash/memoize.js';\n\nimport { assert } from './assert.js';\n\nexport type Hex = `0x${string}`;\n\n// Use native regexes instead of superstruct for maximum performance.\n// Pre-compiled regex for maximum performance - avoids recompilation on each call\nconst HEX_REGEX = /^(?:0x)?[0-9a-f]+$/iu;\nconst STRICT_HEX_REGEX = /^0x[0-9a-f]+$/iu;\nconst HEX_ADDRESS_REGEX = /^0x[0-9a-f]{40}$/u;\nconst HEX_CHECKSUM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/u;\n\nexport const HexStruct = pattern(string(), HEX_REGEX);\nexport const StrictHexStruct = pattern(string(), STRICT_HEX_REGEX) as Struct<\n Hex,\n null\n>;\nexport const HexAddressStruct = pattern(string(), HEX_ADDRESS_REGEX) as Struct<\n Hex,\n null\n>;\nexport const HexChecksumAddressStruct = pattern(\n string(),\n HEX_CHECKSUM_ADDRESS_REGEX,\n) as Struct<Hex, null>;\n\nconst isString = (value: unknown): value is string => typeof value === 'string';\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 isString(value) && HEX_REGEX.test(value);\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 isString(value) && STRICT_HEX_REGEX.test(value);\n}\n\n/**\n * Check if a string is a valid hex address.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex address.\n */\nexport function isHexAddress(value: unknown): value is Hex {\n return isString(value) && HEX_ADDRESS_REGEX.test(value);\n}\n\n/**\n * Check if a string is a valid hex checksum address.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid hex checksum address.\n */\nexport function isHexChecksumAddress(value: unknown): value is Hex {\n return isString(value) && HEX_CHECKSUM_ADDRESS_REGEX.test(value);\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 * Encode a passed hex string as an ERC-55 mixed-case checksum address.\n * This is the unmemoized version, primarily used for testing.\n *\n * @param hexAddress - The hex address to encode.\n * @returns The address encoded according to ERC-55.\n * @see https://eips.ethereum.org/EIPS/eip-55\n */\nexport function getChecksumAddressUnmemoized(hexAddress: Hex): Hex {\n assert(isHexChecksumAddress(hexAddress), 'Invalid hex address.');\n const address = remove0x(hexAddress).toLowerCase();\n\n const hashBytes = keccak256(address);\n const { length } = address;\n const result = new Array(length); // Pre-allocate array\n\n for (let i = 0; i < length; i++) {\n /* eslint-disable no-bitwise */\n const byteIndex = i >> 1; // Faster than Math.floor(i / 2)\n const nibbleIndex = i & 1; // Faster than i % 2\n const byte = hashBytes[byteIndex] as number;\n const nibble = nibbleIndex === 0 ? byte >> 4 : byte & 0x0f;\n /* eslint-enable no-bitwise */\n\n result[i] = nibble >= 8 ? (address[i] as string).toUpperCase() : address[i];\n }\n\n return `0x${result.join('')}`;\n}\n\n/**\n * Encode a passed hex string as an ERC-55 mixed-case checksum address.\n * This function is memoized for performance.\n *\n * @param hexAddress - The hex address to encode.\n * @returns The address encoded according to ERC-55.\n * @see https://eips.ethereum.org/EIPS/eip-55\n */\nexport const getChecksumAddress = memoize(getChecksumAddressUnmemoized);\n\n/**\n * Validate that the passed hex string is a valid ERC-55 mixed-case\n * checksum address.\n *\n * @param possibleChecksum - The hex address to check.\n * @returns True if the address is a checksum address.\n */\nexport function isValidChecksumAddressUnmemoized(\n possibleChecksum: Hex,\n): boolean {\n if (!isHexChecksumAddress(possibleChecksum)) {\n return false;\n }\n\n return getChecksumAddress(possibleChecksum) === possibleChecksum;\n}\n\n/**\n * Validate that the passed hex string is a valid ERC-55 mixed-case\n * checksum address.\n *\n * @param possibleChecksum - The hex address to check.\n * @returns True if the address is a checksum address.\n */\nexport const isValidChecksumAddress = memoize(isValidChecksumAddressUnmemoized);\n\n/**\n * Validate that the passed prefixed hex string is an all-lowercase\n * hex address, or a valid mixed-case checksum address.\n *\n * @param possibleAddress - Input parameter to check against.\n * @returns Whether or not the input is a valid hex address.\n */\nexport function isValidHexAddressUnmemoized(possibleAddress: Hex): boolean {\n return (\n isHexAddress(possibleAddress) || isValidChecksumAddress(possibleAddress)\n );\n}\n\n/**\n * Validate that the passed prefixed hex string is an all-lowercase\n * hex address, or a valid mixed-case checksum address.\n *\n * @param possibleAddress - Input parameter to check against.\n * @returns Whether or not the input is a valid hex address.\n */\nexport const isValidHexAddress = memoize(isValidHexAddressUnmemoized);\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/json.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,EAiBL,MAAM,EAEP,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAEV,KAAK,EACL,YAAY,EACZ,QAAQ,EACR,WAAW,EACZ,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,E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AAG,KAAK,IAAI,cAAc,CAExE;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EACd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,cAAc,CAOjC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAExE;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EACd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,cAAc,CAOjC;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,EACd,YAAY,CAAC,EAAE,yBAAyB,GACvC,OAAO,CAAC,KAAK,IAAI,YAAY,CAO/B;AAED,KAAK,uBAAuB,GAAG;IAC7B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,CAAC,EAAE,uBAAuB,GAChC,CAAC,EAAE,EAAE,OAAO,KAAK,EAAE,IAAI,SAAS,CAwBlC"}
|
package/dist/json.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,KAAK,EACL,MAAM,EACN,MAAM,EACN,MAAM,EACN,OAAO,EACP,EAAE,EACF,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,IAAI,iBAAiB,EAC3B,QAAQ,EACR,MAAM,EACN,MAAM,EACN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AK;QACtB,UAAU,EAAE,IAAI;QAChB,GAAG,OAAO;KACX,CAAC;IAEF;;;;;;OAMG;IACH,MAAM,gBAAgB,GAAG,CAAC,EAAW,EAAmB,EAAE;QACxD,OAAO,OAAO,CACZ,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,eAAe,IAAI,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;YACrE,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAChE,CAAC,UAAU,IAAI,EAAE,KAAK,IAAI,CAAC,CAC5B,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import {\n any,\n array,\n coerce,\n create,\n define,\n integer,\n is,\n literal,\n nullable,\n number,\n object as superstructObject,\n optional,\n record,\n string,\n union,\n unknown,\n Struct,\n refine,\n} from '@metamask/superstruct';\nimport type {\n Context,\n Infer,\n ObjectSchema,\n Simplify,\n Optionalize,\n} from '@metamask/superstruct';\n\nimport type { AssertionErrorConstructor } from './assert.js';\nimport { assertStruct } from './assert.js';\nimport { hasProperty } from './misc.js';\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 * A helper type to make properties with `undefined` in their type optional, but\n * not `undefined` itself.\n *\n * @deprecated Use `ObjectType` and/or `ExactOptionalize` from `@metamask/superstruct@>=3.2.0` instead.\n * @example\n * ```ts\n * type Foo = ObjectOptional<{ foo: string | undefined }>;\n * // Foo is equivalent to { foo?: string }\n * ```\n */\nexport type ObjectOptional<Schema extends Record<string, unknown>> = {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? Key\n : never]?: Schema[Key] extends ExactOptionalGuard & (infer Original)\n ? Original\n : never;\n} & {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? never\n : Key]: Schema[Key];\n};\n\n/**\n * An object type with support for exact optionals. This is used by the `object`\n * struct. This uses the {@link ObjectOptional} helper to make properties with\n * `undefined` in their type optional, but not `undefined` itself.\n *\n * @deprecated Use `ObjectType` from `@metamask/superstruct@>=3.2.0` instead.\n */\nexport type ObjectType<Schema extends ObjectSchema> = Simplify<\n ObjectOptional<\n Optionalize<{\n [Key in keyof Schema]: Infer<Schema[Key]>;\n }>\n >\n>;\n\n/**\n * A struct to check if the given value is a valid object, with support for\n * {@link exactOptional} types.\n *\n * @deprecated Use `exactOptional` and `object` from `@metamask/superstruct@>=3.2.0` instead.\n * @param schema - The schema of the object.\n * @returns A struct to check if the given value is an object.\n */\nexport const object = <Schema extends ObjectSchema>(\n schema: Schema,\n): Struct<ObjectType<Schema>> =>\n // The type is slightly different from a regular object struct, because we\n // want to make properties with `undefined` in their type optional, but not\n // `undefined` itself. This means that we need a type cast.\n superstructObject(schema) as unknown as Struct<ObjectType<Schema>>;\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Branding symbol for the opaque guard type; used only via `typeof`.\ndeclare const exactOptionalSymbol: unique symbol;\ntype ExactOptionalGuard = {\n _exactOptionalGuard?: typeof exactOptionalSymbol;\n};\n\n/**\n * Check the last field of a path is present.\n *\n * @param context - The context to check.\n * @param context.path - The path to check.\n * @param context.branch - The branch to check.\n * @returns Whether the last field of a path is present.\n */\nfunction hasOptional({ path, branch }: Context): boolean {\n const field = path[path.length - 1];\n return hasProperty(branch[branch.length - 2], field);\n}\n\n/**\n * A struct which allows the property of an object to be absent, or to be present\n * as long as it's valid and not set to `undefined`.\n *\n * This struct should be used in conjunction with the {@link object} from this\n * library, to get proper type inference.\n *\n * @deprecated Use `exactOptional` and `object` from `@metamask/superstruct@>=3.2.0` instead.\n * @param struct - The struct to check the value against, if present.\n * @returns A struct to check if the given value is valid, or not present.\n * @example\n * ```ts\n * const struct = object({\n * foo: exactOptional(string()),\n * bar: exactOptional(number()),\n * baz: optional(boolean()),\n * qux: unknown(),\n * });\n *\n * type Type = Infer<typeof struct>;\n * // Type is equivalent to:\n * // {\n * // foo?: string;\n * // bar?: number;\n * // baz?: boolean | undefined;\n * // qux: unknown;\n * // }\n * ```\n */\nexport function exactOptional<Type, Schema>(\n struct: Struct<Type, Schema>,\n): Struct<Type & ExactOptionalGuard, Schema> {\n return new Struct<Type & ExactOptionalGuard, Schema>({\n ...struct,\n\n type: `optional ${struct.type}`,\n validator: (value, context) =>\n !hasOptional(context) || struct.validator(value, context),\n\n refiner: (value, context) =>\n !hasOptional(context) || struct.refiner(value, context),\n });\n}\n\n/**\n * Validate an unknown input to be valid JSON.\n *\n * Useful for constructing JSON structs.\n *\n * @param json - An unknown value.\n * @returns True if the value is valid JSON, otherwise false.\n */\nfunction validateJson(json: unknown): boolean {\n if (json === null || typeof json === 'boolean' || typeof json === 'string') {\n return true;\n }\n\n if (typeof json === 'number' && Number.isFinite(json)) {\n return true;\n }\n\n if (typeof json === 'object') {\n let every = true;\n if (Array.isArray(json)) {\n // Ignoring linting error since for-of is significantly slower than a normal for-loop\n // and performance is important in this specific function.\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < json.length; i++) {\n if (!validateJson(json[i])) {\n every = false;\n break;\n }\n }\n return every;\n }\n\n const entries = Object.entries(json);\n // Ignoring linting errors since for-of is significantly slower than a normal for-loop\n // and performance is important in this specific function.\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < entries.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (typeof entries[i]![0] !== 'string' || !validateJson(entries[i]![1])) {\n every = false;\n break;\n }\n }\n return every;\n }\n\n return false;\n}\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\nexport const UnsafeJsonStruct: Struct<Json> = define('JSON', (json) =>\n validateJson(json),\n);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(\n UnsafeJsonStruct,\n refine(any(), 'JSON', (value) => is(value, UnsafeJsonStruct)),\n (value) =>\n JSON.parse(\n JSON.stringify(value, (propKey, propValue) => {\n // Strip __proto__ and constructor properties to prevent prototype pollution.\n if (propKey === '__proto__' || propKey === 'constructor') {\n return undefined;\n }\n return propValue;\n }),\n ),\n);\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 try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\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: exactOptional(JsonStruct),\n stack: exactOptional(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: Struct<Json[] | Record<string, Json>, null> =\n union([record(string(), JsonStruct), array(JsonStruct)]);\n\nexport type JsonRpcParams = Json[] | Record<string, Json>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Infer<Type> & {\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 = object({\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\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 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 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 = superstructObject({\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 = 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 = 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- The assertion does not change assignability, but it does pin the emitted declaration to the named `JsonRpcError`. Without it TypeScript inlines the structure and leaks the unexported `ExactOptionalGuard` into the published types.\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 = 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 {\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 {\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 {\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 {\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(value: unknown): value is JsonRpcSuccess {\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 {\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"]}
|
|
1
|
+
{"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,KAAK,EACL,MAAM,EACN,MAAM,EACN,MAAM,EACN,OAAO,EACP,EAAE,EACF,OAAO,EACP,QAAQ,EACR,MAAM,EACN,MAAM,IAAI,iBAAiB,EAC3B,QAAQ,EACR,MAAM,EACN,MAAM,EACN,KAAK,EACL,OAAO,EACP,MAAM,EACN,MAAM,GACP,MAAM,uBAAuB,CAAC;AAU/B,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAmDxC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,MAAc,EACc,EAAE;AAC9B,0EAA0E;AAC1E,2EAA2E;AAC3E,2DAA2D;AAC3D,iBAAiB,CAAC,MAAM,CAA0C,CAAC;AAQrE;;;;;;;GAOG;AACH,SAAS,WAAW,CAAC,EAAE,IAAI,EAAE,MAAM,EAAW;IAC5C,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACpC,OAAO,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;AACvD,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,UAAU,aAAa,CAC3B,MAA4B;IAE5B,OAAO,IAAI,MAAM,CAAoC;QACnD,GAAG,MAAM;Q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pB,mCAAmC,EACnC,YAAY,CACb,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,EAAE,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;AACvC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,oBAAoB,CAClC,KAAc,EACd,YAAwC;IAExC,YAAY,CACV,KAAK,EACL,kBAAkB,EAClB,wBAAwB,EACxB,YAAY,CACb,CAAC;AACJ,CAAC;AAQD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,qBAAqB,CACnC,OAAiC;IAEjC,MAAM,EAAE,iBAAiB,EAAE,eAAe,EAAE,UAAU,EAAE,GAAG;QACzD,iBAAiB,EAAE,IAAI;QACvB,eAAe,EAAE,KAAK;QACtB,UAAU,EAAE,IAAI;QAChB,GAAG,OAAO;KACX,CAAC;IAEF;;;;;;OAMG;IACH,MAAM,gBAAgB,GAAG,CAAC,EAAW,EAAmB,EAAE;QACxD,OAAO,OAAO,CACZ,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,eAAe,IAAI,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;YACrE,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAChE,CAAC,UAAU,IAAI,EAAE,KAAK,IAAI,CAAC,CAC5B,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import {\n any,\n array,\n coerce,\n create,\n define,\n integer,\n is,\n literal,\n nullable,\n number,\n object as superstructObject,\n optional,\n record,\n string,\n union,\n unknown,\n Struct,\n refine,\n} from '@metamask/superstruct';\nimport type {\n Context,\n Infer,\n ObjectSchema,\n Simplify,\n Optionalize,\n} from '@metamask/superstruct';\n\nimport type { AssertionErrorConstructor } from './assert.js';\nimport { assertStruct } from './assert.js';\nimport { hasProperty } from './misc.js';\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 * A helper type to make properties with `undefined` in their type optional, but\n * not `undefined` itself.\n *\n * @deprecated Use `ObjectType` and/or `ExactOptionalize` from `@metamask/superstruct@>=3.2.0` instead.\n * @example\n * ```ts\n * type Foo = ObjectOptional<{ foo: string | undefined }>;\n * // Foo is equivalent to { foo?: string }\n * ```\n */\nexport type ObjectOptional<Schema extends Record<string, unknown>> = {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? Key\n : never]?: Schema[Key] extends ExactOptionalGuard & (infer Original)\n ? Original\n : never;\n} & {\n [Key in keyof Schema as Schema[Key] extends ExactOptionalGuard\n ? never\n : Key]: Schema[Key];\n};\n\n/**\n * An object type with support for exact optionals. This is used by the `object`\n * struct. This uses the {@link ObjectOptional} helper to make properties with\n * `undefined` in their type optional, but not `undefined` itself.\n *\n * @deprecated Use `ObjectType` from `@metamask/superstruct@>=3.2.0` instead.\n */\nexport type ObjectType<Schema extends ObjectSchema> = Simplify<\n ObjectOptional<\n Optionalize<{\n [Key in keyof Schema]: Infer<Schema[Key]>;\n }>\n >\n>;\n\n/**\n * A struct to check if the given value is a valid object, with support for\n * {@link exactOptional} types.\n *\n * @deprecated Use `exactOptional` and `object` from `@metamask/superstruct@>=3.2.0` instead.\n * @param schema - The schema of the object.\n * @returns A struct to check if the given value is an object.\n */\nexport const object = <Schema extends ObjectSchema>(\n schema: Schema,\n): Struct<ObjectType<Schema>> =>\n // The type is slightly different from a regular object struct, because we\n // want to make properties with `undefined` in their type optional, but not\n // `undefined` itself. This means that we need a type cast.\n superstructObject(schema) as unknown as Struct<ObjectType<Schema>>;\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Branding symbol for the opaque guard type; used only via `typeof`.\ndeclare const exactOptionalSymbol: unique symbol;\ntype ExactOptionalGuard = {\n _exactOptionalGuard?: typeof exactOptionalSymbol;\n};\n\n/**\n * Check the last field of a path is present.\n *\n * @param context - The context to check.\n * @param context.path - The path to check.\n * @param context.branch - The branch to check.\n * @returns Whether the last field of a path is present.\n */\nfunction hasOptional({ path, branch }: Context): boolean {\n const field = path[path.length - 1];\n return hasProperty(branch[branch.length - 2], field);\n}\n\n/**\n * A struct which allows the property of an object to be absent, or to be present\n * as long as it's valid and not set to `undefined`.\n *\n * This struct should be used in conjunction with the {@link object} from this\n * library, to get proper type inference.\n *\n * @deprecated Use `exactOptional` and `object` from `@metamask/superstruct@>=3.2.0` instead.\n * @param struct - The struct to check the value against, if present.\n * @returns A struct to check if the given value is valid, or not present.\n * @example\n * ```ts\n * const struct = object({\n * foo: exactOptional(string()),\n * bar: exactOptional(number()),\n * baz: optional(boolean()),\n * qux: unknown(),\n * });\n *\n * type Type = Infer<typeof struct>;\n * // Type is equivalent to:\n * // {\n * // foo?: string;\n * // bar?: number;\n * // baz?: boolean | undefined;\n * // qux: unknown;\n * // }\n * ```\n */\nexport function exactOptional<Type, Schema>(\n struct: Struct<Type, Schema>,\n): Struct<Type & ExactOptionalGuard, Schema> {\n return new Struct<Type & ExactOptionalGuard, Schema>({\n ...struct,\n\n type: `optional ${struct.type}`,\n validator: (value, context) =>\n !hasOptional(context) || struct.validator(value, context),\n\n refiner: (value, context) =>\n !hasOptional(context) || struct.refiner(value, context),\n });\n}\n\n/**\n * Validate an unknown input to be valid JSON.\n *\n * Useful for constructing JSON structs.\n *\n * @param json - An unknown value.\n * @returns True if the value is valid JSON, otherwise false.\n */\nfunction validateJson(json: unknown): boolean {\n if (json === null || typeof json === 'boolean' || typeof json === 'string') {\n return true;\n }\n\n if (typeof json === 'number' && Number.isFinite(json)) {\n return true;\n }\n\n if (typeof json === 'object') {\n let every = true;\n if (Array.isArray(json)) {\n // Ignoring linting error since for-of is significantly slower than a normal for-loop\n // and performance is important in this specific function.\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < json.length; i++) {\n if (!validateJson(json[i])) {\n every = false;\n break;\n }\n }\n return every;\n }\n\n const entries = Object.entries(json);\n // Ignoring linting errors since for-of is significantly slower than a normal for-loop\n // and performance is important in this specific function.\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < entries.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (typeof entries[i]![0] !== 'string' || !validateJson(entries[i]![1])) {\n every = false;\n break;\n }\n }\n return every;\n }\n\n return false;\n}\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\nexport const UnsafeJsonStruct: Struct<Json> = define('JSON', (json) =>\n validateJson(json),\n);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(\n UnsafeJsonStruct,\n refine(any(), 'JSON', (value) => is(value, UnsafeJsonStruct)),\n (value) =>\n JSON.parse(\n JSON.stringify(value, (propKey, propValue) => {\n // Strip __proto__ and constructor properties to prevent prototype pollution.\n if (propKey === '__proto__' || propKey === 'constructor') {\n return undefined;\n }\n return propValue;\n }),\n ),\n);\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 try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\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: exactOptional(JsonStruct),\n stack: exactOptional(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: Struct<Json[] | Record<string, Json>, null> =\n union([record(string(), JsonStruct), array(JsonStruct)]);\n\nexport type JsonRpcParams = Json[] | Record<string, Json>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Infer<Type> & {\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 = object({\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: exactOptional(JsonRpcParamsStruct),\n});\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 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 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 = superstructObject({\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 = 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 = 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- The assertion does not change assignability, but it does pin the emitted declaration to the named `JsonRpcError`. Without it TypeScript inlines the structure and leaks the unexported `ExactOptionalGuard` into the published types.\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 = 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 {\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 {\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 {\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 {\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(value: unknown): value is JsonRpcSuccess {\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 {\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(\n options?: JsonRpcValidatorOptions,\n): (id: unknown) => id is JsonRpcId {\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"]}
|
package/dist/misc.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"misc.d.ts","sourceRoot":"","sources":["../src/misc.ts"],"names":[],"mappings":"AAIA;;;;;GAKG;AACH,MAAM,MAAM,OAAO,CACjB,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC3C,SAAS,SAAS,MAAM,WAAW,IACjC;IACF,CAAC,UAAU,GAAG,IAAI,MAAM,IAAI,CAAC,WAAW,EAAE,SAAS,CAAC,GAAG,WAAW,CAAC,GAAG,CAAC;CACxE,GAAG;KACD,GAAG,IAAI,MAAM,IAAI,CAAC,WAAW,EAAE,SAAS,CAAC,GAAG,WAAW,CAAC,GAA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,GAAG,CAAC,CAAC;IACnB,CAAC,EAAE,CAAC,CAAC,CAAC;IAEN,oDAAoD;IACpD,OAAO,IAAI,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,wBAAwB,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;AACrE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC;AACjC,CAAC","sourcesContent":["//\n// Types\n//\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template ObjectValue - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n ObjectValue extends Record<string, unknown>,\n TargetKey extends keyof ObjectValue,\n> = {\n -readonly [Key in keyof Pick<ObjectValue, TargetKey>]: ObjectValue[Key];\n} & {\n [Key in keyof Omit<ObjectValue, TargetKey>]: ObjectValue[Key];\n};\n\n/**\n * Get a type representing the public interface of the given type. The\n * returned type will have all public properties, but will omit private\n * properties.\n *\n * @template Interface - The interface to return a public representation of.\n */\nexport type PublicInterface<Interface> = Pick<Interface, keyof Interface>;\n\n/**\n * Useful for representing some value that _might_ be present and / or complete.\n *\n * @template Value - The value that might be present or complete.\n */\nexport type PartialOrAbsent<Value> = Partial<Value> | null | undefined;\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template Element - The non-empty array member type.\n */\nexport type NonEmptyArray<Element> = [Element, ...Element[]];\n\n/**\n * A JavaScript object that is not `null`, a function, or an array.\n */\nexport type RuntimeObject = Record<PropertyKey, unknown>;\n\n//\n// Type Guards\n//\n\n/**\n * A {@link NonEmptyArray} type guard.\n *\n * @template Element - The non-empty array member type.\n * @param value - The value to check.\n * @returns Whether the value is a non-empty array.\n */\nexport function isNonEmptyArray<Element>(\n value: Element[],\n): value is NonEmptyArray<Element> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for \"nullishness\".\n *\n * @param value - Any value.\n * @returns `true` if the value is null or undefined, `false` otherwise.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * A type guard for {@link RuntimeObject}.\n *\n * @param value - The value to check.\n * @returns Whether the specified value has a runtime type of `object` and is\n * neither `null` nor an `Array`.\n */\nexport function isObject(value: unknown): value is RuntimeObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n//\n// Other utility functions\n//\n\n/**\n * A type guard for ensuring an object has a property.\n *\n * @param objectToCheck - The object to check.\n * @param name - The property name to check for.\n * @returns Whether the specified object has an own property with the specified\n * name, regardless of whether it is enumerable or not.\n */\nexport const hasProperty = <\n // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types -- `Object` is deliberate: it accepts boxed primitives, so callers can pass a string or number. Narrowing to `object` would be a breaking change.\n ObjectToCheck extends Object,\n Property extends PropertyKey,\n>(\n objectToCheck: ObjectToCheck,\n name: Property,\n): objectToCheck is ObjectToCheck &\n Record<\n Property,\n Property extends keyof ObjectToCheck ? ObjectToCheck[Property] : unknown\n > => Object.hasOwnProperty.call(objectToCheck, name);\n\n/**\n * `Object.getOwnPropertyNames()` is intentionally generic: it returns the\n * immediate property names of an object, but it cannot make guarantees about\n * the contents of that object, so the type of the property names is merely\n * `string[]`. While this is technically accurate, it is also unnecessary if we\n * have an object with a type that we own (such as an enum).\n *\n * @param object - The plain object.\n * @returns The own property names of the object which are assigned a type\n * derived from the object itself.\n */\nexport function getKnownPropertyNames<Key extends PropertyKey>(\n object: Partial<Record<Key, any>>,\n): Key[] {\n return Object.getOwnPropertyNames(object) as Key[];\n}\n\nexport type PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Predefined sizes (in Bytes) of specific parts of JSON structure.\n */\n/* eslint-disable @typescript-eslint/no-duplicate-enum-values --\n These are byte sizes, so collisions are meaningful rather than mistakes:\n a comma, a brace, a quote and a colon are all one byte, and `null` and\n `true` are both four characters. */\nexport enum JsonSize {\n Null = 4,\n Comma = 1,\n Wrapper = 1,\n True = 4,\n False = 5,\n Quote = 1,\n Colon = 1,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Date = 24,\n}\n/* eslint-enable @typescript-eslint/no-duplicate-enum-values */\n\n/**\n * Regular expression with pattern matching for (special) escaped characters.\n */\nexport const ESCAPE_CHARACTERS_REGEXP = /\"|\\\\|\\n|\\r|\\t/gu;\n\n/**\n * Check if the value is plain object.\n *\n * @param value - Value to be checked.\n * @returns True if an object is the plain JavaScript object,\n * false if the object is not plain (e.g. function).\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n try {\n let proto = value;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(value) === proto;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if character is ASCII.\n *\n * @param character - Character.\n * @returns True if a character code is ASCII, false if not.\n */\nexport function isASCII(character: string) {\n return character.charCodeAt(0) <= 127;\n}\n\n/**\n * Calculate string size.\n *\n * @param value - String value to calculate size.\n * @returns Number of bytes used to store whole string value.\n */\nexport function calculateStringSize(value: string): number {\n const size = value.split('').reduce((total, character) => {\n if (isASCII(character)) {\n return total + 1;\n }\n return total + 2;\n }, 0);\n\n // Also detect characters that need backslash escape\n return size + (value.match(ESCAPE_CHARACTERS_REGEXP) ?? []).length;\n}\n\n/**\n * Calculate size of a number ofter JSON serialization.\n *\n * @param value - Number value to calculate size.\n * @returns Number of bytes used to store whole number in JSON.\n */\nexport function calculateNumberSize(value: number): number {\n return value.toString().length;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"misc.js","sourceRoot":"","sources":["../src/misc.ts"],"names":[],"mappings":"AAAA,EAAE;AACF,QAAQ;AACR,EAAE;AA6CF,EAAE;AACF,cAAc;AACd,EAAE;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,KAAgB;IAEhB,OAAO,KAAK,CAAC,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O,KAAK,CAAC;IACf,CAAC;IAED,IAAI,CAAC;QACH,IAAI,KAAK,GAAG,KAAK,CAAC;QAClB,OAAO,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;YAC7C,KAAK,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC;IAChD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,OAAO,CAAC,SAAiB;IACvC,OAAO,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC;AACxC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE;QACvD,IAAI,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;YACvB,OAAO,KAAK,GAAG,CAAC,CAAC;QACnB,CAAC;QACD,OAAO,KAAK,GAAG,CAAC,CAAC;IACnB,CAAC,EAAE,CAAC,CAAC,CAAC;IAEN,oDAAoD;IACpD,OAAO,IAAI,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,wBAAwB,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;AACrE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC;AACjC,CAAC","sourcesContent":["//\n// Types\n//\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template ObjectValue - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n ObjectValue extends Record<string, unknown>,\n TargetKey extends keyof ObjectValue,\n> = {\n -readonly [Key in keyof Pick<ObjectValue, TargetKey>]: ObjectValue[Key];\n} & {\n [Key in keyof Omit<ObjectValue, TargetKey>]: ObjectValue[Key];\n};\n\n/**\n * Get a type representing the public interface of the given type. The\n * returned type will have all public properties, but will omit private\n * properties.\n *\n * @template Interface - The interface to return a public representation of.\n */\nexport type PublicInterface<Interface> = Pick<Interface, keyof Interface>;\n\n/**\n * Useful for representing some value that _might_ be present and / or complete.\n *\n * @template Value - The value that might be present or complete.\n */\nexport type PartialOrAbsent<Value> = Partial<Value> | null | undefined;\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template Element - The non-empty array member type.\n */\nexport type NonEmptyArray<Element> = [Element, ...Element[]];\n\n/**\n * A JavaScript object that is not `null`, a function, or an array.\n */\nexport type RuntimeObject = Record<PropertyKey, unknown>;\n\n//\n// Type Guards\n//\n\n/**\n * A {@link NonEmptyArray} type guard.\n *\n * @template Element - The non-empty array member type.\n * @param value - The value to check.\n * @returns Whether the value is a non-empty array.\n */\nexport function isNonEmptyArray<Element>(\n value: Element[],\n): value is NonEmptyArray<Element> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for \"nullishness\".\n *\n * @param value - Any value.\n * @returns `true` if the value is null or undefined, `false` otherwise.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * A type guard for {@link RuntimeObject}.\n *\n * @param value - The value to check.\n * @returns Whether the specified value has a runtime type of `object` and is\n * neither `null` nor an `Array`.\n */\nexport function isObject(value: unknown): value is RuntimeObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n//\n// Other utility functions\n//\n\n/**\n * A type guard for ensuring an object has a property.\n *\n * @param objectToCheck - The object to check.\n * @param name - The property name to check for.\n * @returns Whether the specified object has an own property with the specified\n * name, regardless of whether it is enumerable or not.\n */\nexport const hasProperty = <\n // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types -- `Object` is deliberate: it accepts boxed primitives, so callers can pass a string or number. Narrowing to `object` would be a breaking change.\n ObjectToCheck extends Object,\n Property extends PropertyKey,\n>(\n objectToCheck: ObjectToCheck,\n name: Property,\n): objectToCheck is ObjectToCheck &\n Record<\n Property,\n Property extends keyof ObjectToCheck ? ObjectToCheck[Property] : unknown\n > => Object.hasOwnProperty.call(objectToCheck, name);\n\n/**\n * `Object.getOwnPropertyNames()` is intentionally generic: it returns the\n * immediate property names of an object, but it cannot make guarantees about\n * the contents of that object, so the type of the property names is merely\n * `string[]`. While this is technically accurate, it is also unnecessary if we\n * have an object with a type that we own (such as an enum).\n *\n * @param object - The plain object.\n * @returns The own property names of the object which are assigned a type\n * derived from the object itself.\n */\nexport function getKnownPropertyNames<Key extends PropertyKey>(\n object: Partial<Record<Key, any>>,\n): Key[] {\n return Object.getOwnPropertyNames(object) as Key[];\n}\n\nexport type PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Predefined sizes (in Bytes) of specific parts of JSON structure.\n */\n/* eslint-disable @typescript-eslint/no-duplicate-enum-values --\n These are byte sizes, so collisions are meaningful rather than mistakes:\n a comma, a brace, a quote and a colon are all one byte, and `null` and\n `true` are both four characters. */\nexport enum JsonSize {\n Null = 4,\n Comma = 1,\n Wrapper = 1,\n True = 4,\n False = 5,\n Quote = 1,\n Colon = 1,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Date = 24,\n}\n/* eslint-enable @typescript-eslint/no-duplicate-enum-values */\n\n/**\n * Regular expression with pattern matching for (special) escaped characters.\n */\nexport const ESCAPE_CHARACTERS_REGEXP = /\"|\\\\|\\n|\\r|\\t/gu;\n\n/**\n * Check if the value is plain object.\n *\n * @param value - Value to be checked.\n * @returns True if an object is the plain JavaScript object,\n * false if the object is not plain (e.g. function).\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n try {\n let proto = value;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(value) === proto;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if character is ASCII.\n *\n * @param character - Character.\n * @returns True if a character code is ASCII, false if not.\n */\nexport function isASCII(character: string): boolean {\n return character.charCodeAt(0) <= 127;\n}\n\n/**\n * Calculate string size.\n *\n * @param value - String value to calculate size.\n * @returns Number of bytes used to store whole string value.\n */\nexport function calculateStringSize(value: string): number {\n const size = value.split('').reduce((total, character) => {\n if (isASCII(character)) {\n return total + 1;\n }\n return total + 2;\n }, 0);\n\n // Also detect characters that need backslash escape\n return size + (value.match(ESCAPE_CHARACTERS_REGEXP) ?? []).length;\n}\n\n/**\n * Calculate size of a number ofter JSON serialization.\n *\n * @param value - Number value to calculate size.\n * @returns Number of bytes used to store whole number in JSON.\n */\nexport function calculateNumberSize(value: number): number {\n return value.toString().length;\n}\n"]}
|
package/dist/time.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"time.js","sourceRoot":"","sources":["../src/time.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAN,IAAY,QAmCX;AAnCD,WAAY,QAAQ;IAClB;;OAEG;IACH,qDAAe,CAAA;IAEf;;OAEG;IACH,8CAAa,CAAA;IAEb;;OAEG;IACH,+CAAe,CAAA;IAEf;;OAEG;IACH,6CAAgB,CAAA;IAEhB;;OAEG;IACH,4CAAgB,CAAA;IAEhB;;OAEG;IACH,+CAAkB,CAAA;IAElB;;OAEG;IACH,iDAAqB,CAAA;AACvB,CAAC,EAnCW,QAAQ,KAAR,QAAQ,QAmCnB;AAED,MAAM,oBAAoB,GAAG,CAAC,MAAc,
|
|
1
|
+
{"version":3,"file":"time.js","sourceRoot":"","sources":["../src/time.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAN,IAAY,QAmCX;AAnCD,WAAY,QAAQ;IAClB;;OAEG;IACH,qDAAe,CAAA;IAEf;;OAEG;IACH,8CAAa,CAAA;IAEb;;OAEG;IACH,+CAAe,CAAA;IAEf;;OAEG;IACH,6CAAgB,CAAA;IAEhB;;OAEG;IACH,4CAAgB,CAAA;IAEhB;;OAEG;IACH,+CAAkB,CAAA;IAElB;;OAEG;IACH,iDAAqB,CAAA;AACvB,CAAC,EAnCW,QAAQ,KAAR,QAAQ,QAmCnB;AAED,MAAM,oBAAoB,GAAG,CAAC,MAAc,EAAW,EAAE,CACvD,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC,CAAC;AAE1C,MAAM,0BAA0B,GAAG,CAAC,MAAc,EAAE,IAAY,EAAQ,EAAE;IACxE,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CACb,IAAI,IAAI,gDAAgD,MAAM,IAAI,CACnE,CAAC;IACJ,CAAC;AACH,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,KAAa,EAAE,QAAkB;IAC9D,0BAA0B,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC3C,OAAO,KAAK,GAAG,QAAQ,CAAC;AAC1B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,SAAiB;IACzC,0BAA0B,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IACnD,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;AAChC,CAAC","sourcesContent":["/**\n * Common duration constants, in milliseconds.\n */\nexport enum Duration {\n /**\n * A millisecond.\n */\n Millisecond = 1,\n\n /**\n * A second, in milliseconds.\n */\n Second = 1000, // Millisecond * 1000\n\n /**\n * A minute, in milliseconds.\n */\n Minute = 60_000, // Second * 60\n\n /**\n * An hour, in milliseconds.\n */\n Hour = 3_600_000, // Minute * 60\n\n /**\n * A day, in milliseconds.\n */\n Day = 86_400_000, // Hour * 24\n\n /**\n * A week, in milliseconds.\n */\n Week = 604_800_000, // Day * 7\n\n /**\n * A year, in milliseconds.\n */\n Year = 31_536_000_000, // Day * 365\n}\n\nconst isNonNegativeInteger = (number: number): boolean =>\n Number.isInteger(number) && number >= 0;\n\nconst assertIsNonNegativeInteger = (number: number, name: string): void => {\n if (!isNonNegativeInteger(number)) {\n throw new Error(\n `\"${name}\" must be a non-negative integer. Received: \"${number}\".`,\n );\n }\n};\n\n/**\n * Calculates the millisecond value of the specified number of units of time.\n *\n * @param count - The number of units of time.\n * @param duration - The unit of time to count.\n * @returns The count multiplied by the specified duration.\n */\nexport function inMilliseconds(count: number, duration: Duration): number {\n assertIsNonNegativeInteger(count, 'count');\n return count * duration;\n}\n\n/**\n * Gets the milliseconds since a particular Unix epoch timestamp.\n *\n * @param timestamp - A Unix millisecond timestamp.\n * @returns The number of milliseconds elapsed since the specified timestamp.\n */\nexport function timeSince(timestamp: number): number {\n assertIsNonNegativeInteger(timestamp, 'timestamp');\n return Date.now() - timestamp;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unitsConversion.d.ts","sourceRoot":"","sources":["../src/unitsConversion.ts"],"names":[],"mappings":"AAYA;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAYrE;AAGD,eAAO,MAAM,OAAO;aAClB,OAAO,EAAE,GAAG;aACZ,GAAG,EAAE,GAAG;aACR,IAAI,EAAE,MAAM;aACZ,IAAI,EAAE,MAAM;aACZ,OAAO,EAAE,MAAM;aACf,UAAU,EAAE,MAAM;aAClB,IAAI,EAAE,SAAS;aACf,IAAI,EAAE,SAAS;aACf,QAAQ,EAAE,SAAS;aACnB,SAAS,EAAE,SAAS;aACpB,IAAI,EAAE,YAAY;aAClB,IAAI,EAAE,YAAY;aAClB,OAAO,EAAE,YAAY;aACrB,SAAS,EAAE,YAAY;aACvB,IAAI,EAAE,YAAY;aAClB,KAAK,EAAE,eAAe;aACtB,UAAU,EAAE,eAAe;aA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AAE,qBAAqB;aAC5B,MAAM,EAAE,wBAAwB;aAChC,KAAK,EAAE,wBAAwB;aAC/B,MAAM,EAAE,2BAA2B;aACnC,MAAM,EAAE,8BAA8B;aACtC,MAAM,EAAE,iCAAiC;CACjC,CAAC;AAeX,KAAK,YAAY,GAAG,MAAM,OAAO,OAAO,CAAC;AAEzC;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,SAAS,GAAE,YAAsB,GAAG,MAAM,CAexE;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAoBpE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,OAAO,CACrB,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAClC,IAAI,EAAE,YAAY,EAClB,YAAY,CAAC,EAAE;IAAE,GAAG,CAAC,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,GAClD,MAAM,CAkDR;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CACnB,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EACpC,IAAI,EAAE,YAAY,GACjB,MAAM,CAiFR"}
|
package/dist/unitsConversion.js
CHANGED
|
@@ -188,10 +188,13 @@ export function toWei(etherInput, unit) {
|
|
|
188
188
|
}
|
|
189
189
|
let whole = comps[0];
|
|
190
190
|
let fraction = comps[1];
|
|
191
|
-
|
|
191
|
+
// Both halves are missing when the input has no decimal point, and empty
|
|
192
|
+
// when it starts or ends with one (`.5`, `5.`). Nullish coalescing would
|
|
193
|
+
// only cover the former.
|
|
194
|
+
if (whole === undefined || whole === '') {
|
|
192
195
|
whole = '0';
|
|
193
196
|
}
|
|
194
|
-
if (
|
|
197
|
+
if (fraction === undefined || fraction === '') {
|
|
195
198
|
fraction = '0';
|
|
196
199
|
}
|
|
197
200
|
if (fraction.length > baseLength) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
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AAG,CAAC;IACjB,CAAC;IACD,IAAI,QAAQ,CAAC,MAAM,GAAG,UAAU,EAAE,CAAC;QACjC,MAAM,IAAI,KAAK,CACb,2BAA2B,UAAU,kCAAkC,CACxE,CAAC;IACJ,CAAC;IAED,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;IAE5C,MAAM,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAClC,MAAM,cAAc,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;IACxC,IAAI,GAAG,GAAG,WAAW,GAAG,IAAI,GAAG,cAAc,CAAC;IAE9C,IAAI,QAAQ,EAAE,CAAC;QACb,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC;IACxB,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/* eslint-disable operator-assignment */\n/*\nPrimary Attribution\nRichard Moore <ricmoo@me.com>\nhttps://github.com/ethers-io\n\nNote, Richard is a god of ether gods. Follow and respect him, and use Ethers.io!\n*/\n\nconst zero = BigInt(0);\nconst negative1 = BigInt(-1);\n\n/**\n * Converts a string, number, or bigint to a bigint.\n *\n * @param arg - The value to convert to bigint.\n * @returns The bigint representation of the input.\n * @throws Error if the input type cannot be converted to bigint.\n */\nexport function numericToBigInt(arg: string | number | bigint): bigint {\n if (typeof arg === 'string') {\n return BigInt(arg);\n }\n if (typeof arg === 'number') {\n return BigInt(arg);\n }\n if (typeof arg === 'bigint') {\n return arg;\n }\n\n throw new Error(`Cannot convert ${typeof arg} to BigInt`);\n}\n\n// complete ethereum unit map\nexport const unitMap = {\n noether: '0',\n wei: '1',\n kwei: '1000',\n Kwei: '1000',\n babbage: '1000',\n femtoether: '1000',\n mwei: '1000000',\n Mwei: '1000000',\n lovelace: '1000000',\n picoether: '1000000',\n gwei: '1000000000',\n Gwei: '1000000000',\n shannon: '1000000000',\n nanoether: '1000000000',\n nano: '1000000000',\n szabo: '1000000000000',\n microether: '1000000000000',\n micro: '1000000000000',\n finney: '1000000000000000',\n milliether: '1000000000000000',\n milli: '1000000000000000',\n ether: '1000000000000000000',\n kether: '1000000000000000000000',\n grand: '1000000000000000000000',\n mether: '1000000000000000000000000',\n gether: '1000000000000000000000000000',\n tether: '1000000000000000000000000000000',\n} as const;\n\n// Pre-computed unit values as BigInt for performance\nconst unitMapBigInt = Object.fromEntries(\n Object.entries(unitMap).map(([key, value]) => [key, BigInt(value)]),\n) as Record<EthereumUnit, bigint>;\n\nconst unitLengths = Object.fromEntries(\n Object.entries(unitMap).map(([key, value]) => [key, value.length - 1 || 1]),\n) as Record<EthereumUnit, number>;\n\nconst NUMBER_REGEX = /^-?[0-9.]+$/u;\nconst FRACTION_REGEX = /^([0-9]*[1-9]|0)(0*)/u;\nconst COMMIFY_REGEX = /\\B(?=(\\d{3})+(?!\\d))/gu;\n\ntype EthereumUnit = keyof typeof unitMap;\n\n/**\n * Returns value of unit in Wei.\n *\n * @param unitInput - The unit to convert to, default ether.\n * @returns Value of the unit (in Wei).\n * @throws Error if the unit is not correct.\n */\nexport function getValueOfUnit(unitInput: EthereumUnit = 'ether'): bigint {\n const unit = unitInput.toLowerCase() as EthereumUnit;\n const unitValue = unitMapBigInt[unit];\n\n if (unitValue === undefined) {\n throw new Error(\n `The unit provided ${unitInput} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n return unitValue;\n}\n\n/**\n * Converts a number to a string.\n *\n * @param arg - The number to convert to a string.\n * @returns The string representation of the number.\n * @throws Error if the number is invalid.\n */\nexport function numberToString(arg: string | number | bigint) {\n if (typeof arg === 'string') {\n if (!NUMBER_REGEX.test(arg)) {\n throw new Error(\n `while converting number to string, invalid number value '${arg}', should be a number matching (^-?[0-9.]+).`,\n );\n }\n return arg;\n }\n if (typeof arg === 'number') {\n return String(arg);\n }\n if (typeof arg === 'bigint') {\n return arg.toString();\n }\n throw new Error(\n `while converting number to string, invalid number value '${String(\n arg,\n )}' type ${typeof arg}.`,\n );\n}\n\n/**\n * Converts a number from Wei to a string.\n *\n * @param weiInput - The number to convert from Wei.\n * @param unit - The unit to convert to, default ether.\n * @param optionsInput - The options to use for the conversion.\n * @param optionsInput.pad - Whether to pad the fractional part with zeros.\n * @param optionsInput.commify - Whether to add commas to separate thousands.\n * @returns The string representation of the number.\n * @throws Error if the number is invalid.\n */\nexport function fromWei(\n weiInput: string | number | bigint,\n unit: EthereumUnit,\n optionsInput?: { pad?: boolean; commify?: boolean },\n) {\n let wei = numericToBigInt(weiInput);\n const negative = wei < zero;\n const unitLower = unit.toLowerCase() as EthereumUnit;\n const base = unitMapBigInt[unitLower];\n const baseLength = unitLengths[unitLower];\n const options = optionsInput ?? {};\n\n if (base === undefined) {\n throw new Error(\n `The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n // Handle special case of noether (base = 0)\n if (base === zero) {\n return negative ? '-0' : '0';\n }\n\n if (negative) {\n wei = wei * negative1;\n }\n\n let fraction = (wei % base).toString();\n\n fraction = fraction.padStart(baseLength, '0');\n\n if (!options.pad) {\n const fractionMatch = fraction.match(FRACTION_REGEX);\n // istanbul ignore next: defensive fallback that's never reachable but necessary to satisfy TS\n fraction = fractionMatch?.[1] ?? '0';\n }\n\n let whole = (wei / base).toString();\n\n if (options.commify) {\n whole = whole.replace(COMMIFY_REGEX, ',');\n }\n\n let value = `${whole}${fraction === '0' ? '' : `.${fraction}`}`;\n\n if (negative) {\n value = `-${value}`;\n }\n\n return value;\n}\n\n/**\n * Converts a number to Wei.\n *\n * @param etherInput - The number to convert to Wei.\n * @param unit - The unit to convert to, default ether.\n * @returns The number in Wei.\n * @throws Error if the number is invalid.\n */\nexport function toWei(\n etherInput: string | number | bigint,\n unit: EthereumUnit,\n): bigint {\n const unitLower = unit.toLowerCase() as EthereumUnit;\n const base = unitMapBigInt[unitLower];\n const baseLength = unitLengths[unitLower];\n\n if (base === undefined) {\n throw new Error(\n `The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n // Handle special case of noether (base = 0)\n if (base === zero) {\n return zero;\n }\n\n // Fast path for bigint inputs when unit is wei (no conversion needed)\n if (typeof etherInput === 'bigint' && unitLower === 'wei') {\n return etherInput;\n }\n\n // Fast path for bigint inputs with whole units (no fractional part)\n if (typeof etherInput === 'bigint') {\n return etherInput * base;\n }\n\n let ether = numberToString(etherInput);\n\n // Is it negative?\n const negative = ether.startsWith('-');\n if (negative) {\n ether = ether.substring(1);\n }\n\n if (ether === '.') {\n throw new Error(\n `While converting number ${etherInput} to wei, invalid value`,\n );\n }\n\n // Split it into a whole and fractional part\n const comps = ether.split('.');\n if (comps.length > 2) {\n throw new Error(\n `While converting number ${etherInput} to wei, too many decimal points`,\n );\n }\n\n let whole = comps[0];\n let fraction = comps[1];\n\n if (!whole) {\n whole = '0';\n }\n if (!fraction) {\n fraction = '0';\n }\n if (fraction.length > baseLength) {\n throw new Error(\n `While converting number ${etherInput} to wei, too many decimal places`,\n );\n }\n\n fraction = fraction.padEnd(baseLength, '0');\n\n const wholeBigInt = BigInt(whole);\n const fractionBigInt = BigInt(fraction);\n let wei = wholeBigInt * base + fractionBigInt;\n\n if (negative) {\n wei = wei * negative1;\n }\n\n return wei;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"unitsConversion.js","sourceRoot":"","sources":["../src/unitsConversion.ts"],"names":[],"mappings":"AAAA,wCAAwC;AACxC;;;;;;EAME;AAEF,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACvB,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAE7B;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,GAA6B;IAC3D,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD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AAC,CAAC;IAClC,MAAM,cAAc,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;IACxC,IAAI,GAAG,GAAG,WAAW,GAAG,IAAI,GAAG,cAAc,CAAC;IAE9C,IAAI,QAAQ,EAAE,CAAC;QACb,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC;IACxB,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/* eslint-disable operator-assignment */\n/*\nPrimary Attribution\nRichard Moore <ricmoo@me.com>\nhttps://github.com/ethers-io\n\nNote, Richard is a god of ether gods. Follow and respect him, and use Ethers.io!\n*/\n\nconst zero = BigInt(0);\nconst negative1 = BigInt(-1);\n\n/**\n * Converts a string, number, or bigint to a bigint.\n *\n * @param arg - The value to convert to bigint.\n * @returns The bigint representation of the input.\n * @throws Error if the input type cannot be converted to bigint.\n */\nexport function numericToBigInt(arg: string | number | bigint): bigint {\n if (typeof arg === 'string') {\n return BigInt(arg);\n }\n if (typeof arg === 'number') {\n return BigInt(arg);\n }\n if (typeof arg === 'bigint') {\n return arg;\n }\n\n throw new Error(`Cannot convert ${typeof arg} to BigInt`);\n}\n\n// complete ethereum unit map\nexport const unitMap = {\n noether: '0',\n wei: '1',\n kwei: '1000',\n Kwei: '1000',\n babbage: '1000',\n femtoether: '1000',\n mwei: '1000000',\n Mwei: '1000000',\n lovelace: '1000000',\n picoether: '1000000',\n gwei: '1000000000',\n Gwei: '1000000000',\n shannon: '1000000000',\n nanoether: '1000000000',\n nano: '1000000000',\n szabo: '1000000000000',\n microether: '1000000000000',\n micro: '1000000000000',\n finney: '1000000000000000',\n milliether: '1000000000000000',\n milli: '1000000000000000',\n ether: '1000000000000000000',\n kether: '1000000000000000000000',\n grand: '1000000000000000000000',\n mether: '1000000000000000000000000',\n gether: '1000000000000000000000000000',\n tether: '1000000000000000000000000000000',\n} as const;\n\n// Pre-computed unit values as BigInt for performance\nconst unitMapBigInt = Object.fromEntries(\n Object.entries(unitMap).map(([key, value]) => [key, BigInt(value)]),\n) as Record<EthereumUnit, bigint>;\n\nconst unitLengths = Object.fromEntries(\n Object.entries(unitMap).map(([key, value]) => [key, value.length - 1 || 1]),\n) as Record<EthereumUnit, number>;\n\nconst NUMBER_REGEX = /^-?[0-9.]+$/u;\nconst FRACTION_REGEX = /^([0-9]*[1-9]|0)(0*)/u;\nconst COMMIFY_REGEX = /\\B(?=(\\d{3})+(?!\\d))/gu;\n\ntype EthereumUnit = keyof typeof unitMap;\n\n/**\n * Returns value of unit in Wei.\n *\n * @param unitInput - The unit to convert to, default ether.\n * @returns Value of the unit (in Wei).\n * @throws Error if the unit is not correct.\n */\nexport function getValueOfUnit(unitInput: EthereumUnit = 'ether'): bigint {\n const unit = unitInput.toLowerCase() as EthereumUnit;\n const unitValue = unitMapBigInt[unit];\n\n if (unitValue === undefined) {\n throw new Error(\n `The unit provided ${unitInput} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n return unitValue;\n}\n\n/**\n * Converts a number to a string.\n *\n * @param arg - The number to convert to a string.\n * @returns The string representation of the number.\n * @throws Error if the number is invalid.\n */\nexport function numberToString(arg: string | number | bigint): string {\n if (typeof arg === 'string') {\n if (!NUMBER_REGEX.test(arg)) {\n throw new Error(\n `while converting number to string, invalid number value '${arg}', should be a number matching (^-?[0-9.]+).`,\n );\n }\n return arg;\n }\n if (typeof arg === 'number') {\n return String(arg);\n }\n if (typeof arg === 'bigint') {\n return arg.toString();\n }\n throw new Error(\n `while converting number to string, invalid number value '${String(\n arg,\n )}' type ${typeof arg}.`,\n );\n}\n\n/**\n * Converts a number from Wei to a string.\n *\n * @param weiInput - The number to convert from Wei.\n * @param unit - The unit to convert to, default ether.\n * @param optionsInput - The options to use for the conversion.\n * @param optionsInput.pad - Whether to pad the fractional part with zeros.\n * @param optionsInput.commify - Whether to add commas to separate thousands.\n * @returns The string representation of the number.\n * @throws Error if the number is invalid.\n */\nexport function fromWei(\n weiInput: string | number | bigint,\n unit: EthereumUnit,\n optionsInput?: { pad?: boolean; commify?: boolean },\n): string {\n let wei = numericToBigInt(weiInput);\n const negative = wei < zero;\n const unitLower = unit.toLowerCase() as EthereumUnit;\n const base = unitMapBigInt[unitLower];\n const baseLength = unitLengths[unitLower];\n const options = optionsInput ?? {};\n\n if (base === undefined) {\n throw new Error(\n `The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n // Handle special case of noether (base = 0)\n if (base === zero) {\n return negative ? '-0' : '0';\n }\n\n if (negative) {\n wei = wei * negative1;\n }\n\n let fraction = (wei % base).toString();\n\n fraction = fraction.padStart(baseLength, '0');\n\n if (!options.pad) {\n const fractionMatch = fraction.match(FRACTION_REGEX);\n // istanbul ignore next: defensive fallback that's never reachable but necessary to satisfy TS\n fraction = fractionMatch?.[1] ?? '0';\n }\n\n let whole = (wei / base).toString();\n\n if (options.commify) {\n whole = whole.replace(COMMIFY_REGEX, ',');\n }\n\n let value = `${whole}${fraction === '0' ? '' : `.${fraction}`}`;\n\n if (negative) {\n value = `-${value}`;\n }\n\n return value;\n}\n\n/**\n * Converts a number to Wei.\n *\n * @param etherInput - The number to convert to Wei.\n * @param unit - The unit to convert to, default ether.\n * @returns The number in Wei.\n * @throws Error if the number is invalid.\n */\nexport function toWei(\n etherInput: string | number | bigint,\n unit: EthereumUnit,\n): bigint {\n const unitLower = unit.toLowerCase() as EthereumUnit;\n const base = unitMapBigInt[unitLower];\n const baseLength = unitLengths[unitLower];\n\n if (base === undefined) {\n throw new Error(\n `The unit provided ${unit} doesn't exist, please use the one of the following units ${JSON.stringify(\n unitMap,\n null,\n 2,\n )}`,\n );\n }\n\n // Handle special case of noether (base = 0)\n if (base === zero) {\n return zero;\n }\n\n // Fast path for bigint inputs when unit is wei (no conversion needed)\n if (typeof etherInput === 'bigint' && unitLower === 'wei') {\n return etherInput;\n }\n\n // Fast path for bigint inputs with whole units (no fractional part)\n if (typeof etherInput === 'bigint') {\n return etherInput * base;\n }\n\n let ether = numberToString(etherInput);\n\n // Is it negative?\n const negative = ether.startsWith('-');\n if (negative) {\n ether = ether.substring(1);\n }\n\n if (ether === '.') {\n throw new Error(\n `While converting number ${etherInput} to wei, invalid value`,\n );\n }\n\n // Split it into a whole and fractional part\n const comps = ether.split('.');\n if (comps.length > 2) {\n throw new Error(\n `While converting number ${etherInput} to wei, too many decimal points`,\n );\n }\n\n let whole = comps[0];\n let fraction = comps[1];\n\n // Both halves are missing when the input has no decimal point, and empty\n // when it starts or ends with one (`.5`, `5.`). Nullish coalescing would\n // only cover the former.\n if (whole === undefined || whole === '') {\n whole = '0';\n }\n if (fraction === undefined || fraction === '') {\n fraction = '0';\n }\n if (fraction.length > baseLength) {\n throw new Error(\n `While converting number ${etherInput} to wei, too many decimal places`,\n );\n }\n\n fraction = fraction.padEnd(baseLength, '0');\n\n const wholeBigInt = BigInt(whole);\n const fractionBigInt = BigInt(fraction);\n let wei = wholeBigInt * base + fractionBigInt;\n\n if (negative) {\n wei = wei * negative1;\n }\n\n return wei;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/utils",
|
|
3
|
-
"version": "11.12.1-preview-
|
|
3
|
+
"version": "11.12.1-preview-4bb3dbb",
|
|
4
4
|
"description": "Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase",
|
|
5
5
|
"homepage": "https://github.com/MetaMask/utils#readme",
|
|
6
6
|
"bugs": {
|