@metamask/utils 6.2.0 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/dist/cjs/assert.js +116 -0
- package/dist/cjs/assert.js.map +1 -0
- package/dist/cjs/base64.js +32 -0
- package/dist/cjs/base64.js.map +1 -0
- package/dist/cjs/bytes.js +255 -0
- package/dist/cjs/bytes.js.map +1 -0
- package/dist/cjs/checksum.js +17 -0
- package/dist/cjs/checksum.js.map +1 -0
- package/dist/cjs/coercers.js +96 -0
- package/dist/cjs/coercers.js.map +1 -0
- package/dist/cjs/collections.js +157 -0
- package/dist/cjs/collections.js.map +1 -0
- package/dist/cjs/encryption-types.js +6 -0
- package/dist/cjs/encryption-types.js.map +1 -0
- package/dist/cjs/hex.js +107 -0
- package/dist/cjs/hex.js.map +1 -0
- package/dist/cjs/index.js +36 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/json.js +263 -0
- package/dist/cjs/json.js.map +1 -0
- package/dist/cjs/keyring.js +6 -0
- package/dist/cjs/keyring.js.map +1 -0
- package/dist/cjs/logging.js +33 -0
- package/dist/cjs/logging.js.map +1 -0
- package/dist/cjs/misc.js +111 -0
- package/dist/cjs/misc.js.map +1 -0
- package/dist/cjs/number.js +52 -0
- package/dist/cjs/number.js.map +1 -0
- package/dist/cjs/opaque.js +8 -0
- package/dist/cjs/opaque.js.map +1 -0
- package/dist/cjs/time.js +63 -0
- package/dist/cjs/time.js.map +1 -0
- package/dist/cjs/transaction-types.js +6 -0
- package/dist/cjs/transaction-types.js.map +1 -0
- package/dist/cjs/versions.js +79 -0
- package/dist/cjs/versions.js.map +1 -0
- package/dist/{assert.js → esm/assert.js} +30 -35
- package/dist/esm/assert.js.map +1 -0
- package/dist/{base64.js → esm/base64.js} +10 -16
- package/dist/esm/base64.js.map +1 -0
- package/dist/{bytes.js → esm/bytes.js} +50 -93
- package/dist/esm/bytes.js.map +1 -0
- package/dist/esm/checksum.js +7 -0
- package/dist/esm/checksum.js.map +1 -0
- package/dist/{coercers.js → esm/coercers.js} +43 -52
- package/dist/esm/coercers.js.map +1 -0
- package/dist/esm/collections.js +140 -0
- package/dist/esm/collections.js.map +1 -0
- package/dist/esm/encryption-types.js +3 -0
- package/dist/esm/encryption-types.js.map +1 -0
- package/dist/esm/hex.js +108 -0
- package/dist/esm/hex.js.map +1 -0
- package/dist/{index.d.ts → esm/index.js} +2 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/json.js +301 -0
- package/dist/esm/json.js.map +1 -0
- package/dist/esm/keyring.js +3 -0
- package/dist/esm/keyring.js.map +1 -0
- package/dist/{logging.js → esm/logging.js} +5 -14
- package/dist/esm/logging.js.map +1 -0
- package/dist/{misc.js → esm/misc.js} +37 -42
- package/dist/esm/misc.js.map +1 -0
- package/dist/{number.js → esm/number.js} +18 -28
- package/dist/esm/number.js.map +1 -0
- package/dist/esm/opaque.js +5 -0
- package/dist/esm/opaque.js.map +1 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/time.js +53 -0
- package/dist/esm/time.js.map +1 -0
- package/dist/esm/transaction-types.js +3 -0
- package/dist/esm/transaction-types.js.map +1 -0
- package/dist/esm/versions.js +78 -0
- package/dist/esm/versions.js.map +1 -0
- package/dist/{assert.d.ts → types/assert.d.ts} +3 -2
- package/dist/types/assert.d.ts.map +1 -0
- package/dist/{base64.d.ts → types/base64.d.ts} +3 -2
- package/dist/types/base64.d.ts.map +1 -0
- package/dist/{bytes.d.ts → types/bytes.d.ts} +2 -1
- package/dist/types/bytes.d.ts.map +1 -0
- package/dist/{checksum.d.ts → types/checksum.d.ts} +1 -0
- package/dist/types/checksum.d.ts.map +1 -0
- package/dist/{coercers.d.ts → types/coercers.d.ts} +3 -2
- package/dist/types/coercers.d.ts.map +1 -0
- package/dist/{collections.d.ts → types/collections.d.ts} +1 -0
- package/dist/types/collections.d.ts.map +1 -0
- package/dist/{encryption-types.d.ts → types/encryption-types.d.ts} +1 -0
- package/dist/types/encryption-types.d.ts.map +1 -0
- package/dist/{hex.d.ts → types/hex.d.ts} +2 -1
- package/dist/types/hex.d.ts.map +1 -0
- package/dist/types/hex.test-d.d.ts +2 -0
- package/dist/types/hex.test-d.d.ts.map +1 -0
- package/dist/types/index.d.ts +18 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/{json.d.ts → types/json.d.ts} +3 -2
- package/dist/types/json.d.ts.map +1 -0
- package/dist/types/json.test-d.d.ts +2 -0
- package/dist/types/json.test-d.d.ts.map +1 -0
- package/dist/{keyring.d.ts → types/keyring.d.ts} +3 -2
- package/dist/types/keyring.d.ts.map +1 -0
- package/dist/{logging.d.ts → types/logging.d.ts} +2 -1
- package/dist/types/logging.d.ts.map +1 -0
- package/dist/{misc.d.ts → types/misc.d.ts} +13 -0
- package/dist/types/misc.d.ts.map +1 -0
- package/dist/types/misc.test-d.d.ts +2 -0
- package/dist/types/misc.test-d.d.ts.map +1 -0
- package/dist/{number.d.ts → types/number.d.ts} +1 -0
- package/dist/types/number.d.ts.map +1 -0
- package/dist/{opaque.d.ts → types/opaque.d.ts} +1 -0
- package/dist/types/opaque.d.ts.map +1 -0
- package/dist/{time.d.ts → types/time.d.ts} +1 -0
- package/dist/types/time.d.ts.map +1 -0
- package/dist/{transaction-types.d.ts → types/transaction-types.d.ts} +3 -2
- package/dist/types/transaction-types.d.ts.map +1 -0
- package/dist/{versions.d.ts → types/versions.d.ts} +3 -2
- package/dist/types/versions.d.ts.map +1 -0
- package/package.json +40 -20
- package/dist/__fixtures__/bytes.d.ts +0 -25
- package/dist/__fixtures__/bytes.js +0 -234
- package/dist/__fixtures__/bytes.js.map +0 -1
- package/dist/__fixtures__/coercions.d.ts +0 -5
- package/dist/__fixtures__/coercions.js +0 -22
- package/dist/__fixtures__/coercions.js.map +0 -1
- package/dist/__fixtures__/index.d.ts +0 -4
- package/dist/__fixtures__/index.js +0 -21
- package/dist/__fixtures__/index.js.map +0 -1
- package/dist/__fixtures__/json.d.ts +0 -1226
- package/dist/__fixtures__/json.js +0 -1491
- package/dist/__fixtures__/json.js.map +0 -1
- package/dist/__fixtures__/numbers.d.ts +0 -5
- package/dist/__fixtures__/numbers.js +0 -56
- package/dist/__fixtures__/numbers.js.map +0 -1
- package/dist/assert.js.map +0 -1
- package/dist/base64.js.map +0 -1
- package/dist/bytes.js.map +0 -1
- package/dist/checksum.js +0 -7
- package/dist/checksum.js.map +0 -1
- package/dist/coercers.js.map +0 -1
- package/dist/collections.js +0 -109
- package/dist/collections.js.map +0 -1
- package/dist/encryption-types.js +0 -3
- package/dist/encryption-types.js.map +0 -1
- package/dist/hex.js +0 -134
- package/dist/hex.js.map +0 -1
- package/dist/hex.test-d.d.ts +0 -1
- package/dist/hex.test-d.js +0 -16
- package/dist/hex.test-d.js.map +0 -1
- package/dist/index.js +0 -34
- package/dist/index.js.map +0 -1
- package/dist/json.js +0 -346
- package/dist/json.js.map +0 -1
- package/dist/json.test-d.d.ts +0 -1
- package/dist/json.test-d.js +0 -62
- package/dist/json.test-d.js.map +0 -1
- package/dist/keyring.js +0 -3
- package/dist/keyring.js.map +0 -1
- package/dist/logging.js.map +0 -1
- package/dist/misc.js.map +0 -1
- package/dist/misc.test-d.d.ts +0 -1
- package/dist/misc.test-d.js +0 -97
- package/dist/misc.test-d.js.map +0 -1
- package/dist/number.js.map +0 -1
- package/dist/opaque.js +0 -3
- package/dist/opaque.js.map +0 -1
- package/dist/time.js +0 -67
- package/dist/time.js.map +0 -1
- package/dist/transaction-types.js +0 -3
- package/dist/transaction-types.js.map +0 -1
- package/dist/versions.js +0 -95
- package/dist/versions.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/keyring.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
createProjectLogger: function() {
|
|
13
|
+
return createProjectLogger;
|
|
14
|
+
},
|
|
15
|
+
createModuleLogger: function() {
|
|
16
|
+
return createModuleLogger;
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
const _debug = /*#__PURE__*/ _interop_require_default(require("debug"));
|
|
20
|
+
function _interop_require_default(obj) {
|
|
21
|
+
return obj && obj.__esModule ? obj : {
|
|
22
|
+
default: obj
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
const globalLogger = (0, _debug.default)('metamask');
|
|
26
|
+
function createProjectLogger(projectName) {
|
|
27
|
+
return globalLogger.extend(projectName);
|
|
28
|
+
}
|
|
29
|
+
function createModuleLogger(projectLogger, moduleName) {
|
|
30
|
+
return projectLogger.extend(moduleName);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=logging.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/logging.ts"],"sourcesContent":["import type { Debugger } from 'debug';\nimport debug from 'debug';\n\nconst globalLogger = debug('metamask');\n\n/**\n * Creates a logger via the `debug` library whose log messages will be tagged\n * using the name of your project. By default, such messages will be\n * suppressed, but you can reveal them by setting the `DEBUG` environment\n * variable to `metamask:<projectName>`. You can also set this variable to\n * `metamask:*` if you want to see log messages from all MetaMask projects that\n * are also using this function to create their loggers.\n *\n * @param projectName - The name of your project. This should be the name of\n * your NPM package if you're developing one.\n * @returns An instance of `debug`.\n */\nexport function createProjectLogger(projectName: string): Debugger {\n return globalLogger.extend(projectName);\n}\n\n/**\n * Creates a logger via the `debug` library which is derived from the logger for\n * the whole project whose log messages will be tagged using the name of your\n * module. By default, such messages will be suppressed, but you can reveal them\n * by setting the `DEBUG` environment variable to\n * `metamask:<projectName>:<moduleName>`. You can also set this variable to\n * `metamask:<projectName>:*` if you want to see log messages from the project,\n * or `metamask:*` if you want to see log messages from all MetaMask projects.\n *\n * @param projectLogger - The logger created via {@link createProjectLogger}.\n * @param moduleName - The name of your module. You could use the name of the\n * file where you're using this logger or some other name.\n * @returns An instance of `debug`.\n */\nexport function createModuleLogger(\n projectLogger: Debugger,\n moduleName: string,\n): Debugger {\n return projectLogger.extend(moduleName);\n}\n"],"names":["createProjectLogger","createModuleLogger","globalLogger","debug","projectName","extend","projectLogger","moduleName"],"mappings":";;;;;;;;;;;IAiBgBA,mBAAmB;eAAnBA;;IAkBAC,kBAAkB;eAAlBA;;;8DAlCE;;;;;;AAElB,MAAMC,eAAeC,IAAAA,cAAK,EAAC;AAcpB,SAASH,oBAAoBI,WAAmB;IACrD,OAAOF,aAAaG,MAAM,CAACD;AAC7B;AAgBO,SAASH,mBACdK,aAAuB,EACvBC,UAAkB;IAElB,OAAOD,cAAcD,MAAM,CAACE;AAC9B"}
|
package/dist/cjs/misc.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Types
|
|
3
|
+
//
|
|
4
|
+
/**
|
|
5
|
+
* Makes every specified property of the specified object type mutable.
|
|
6
|
+
*
|
|
7
|
+
* @template ObjectValue - The object whose readonly properties to make mutable.
|
|
8
|
+
* @template TargetKey - The property key(s) to make mutable.
|
|
9
|
+
*/ "use strict";
|
|
10
|
+
Object.defineProperty(exports, "__esModule", {
|
|
11
|
+
value: true
|
|
12
|
+
});
|
|
13
|
+
function _export(target, all) {
|
|
14
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
15
|
+
enumerable: true,
|
|
16
|
+
get: all[name]
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
_export(exports, {
|
|
20
|
+
JsonSize: function() {
|
|
21
|
+
return JsonSize;
|
|
22
|
+
},
|
|
23
|
+
isNonEmptyArray: function() {
|
|
24
|
+
return isNonEmptyArray;
|
|
25
|
+
},
|
|
26
|
+
isNullOrUndefined: function() {
|
|
27
|
+
return isNullOrUndefined;
|
|
28
|
+
},
|
|
29
|
+
isObject: function() {
|
|
30
|
+
return isObject;
|
|
31
|
+
},
|
|
32
|
+
hasProperty: function() {
|
|
33
|
+
return hasProperty;
|
|
34
|
+
},
|
|
35
|
+
getKnownPropertyNames: function() {
|
|
36
|
+
return getKnownPropertyNames;
|
|
37
|
+
},
|
|
38
|
+
ESCAPE_CHARACTERS_REGEXP: function() {
|
|
39
|
+
return ESCAPE_CHARACTERS_REGEXP;
|
|
40
|
+
},
|
|
41
|
+
isPlainObject: function() {
|
|
42
|
+
return isPlainObject;
|
|
43
|
+
},
|
|
44
|
+
isASCII: function() {
|
|
45
|
+
return isASCII;
|
|
46
|
+
},
|
|
47
|
+
calculateStringSize: function() {
|
|
48
|
+
return calculateStringSize;
|
|
49
|
+
},
|
|
50
|
+
calculateNumberSize: function() {
|
|
51
|
+
return calculateNumberSize;
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
function isNonEmptyArray(value) {
|
|
55
|
+
return Array.isArray(value) && value.length > 0;
|
|
56
|
+
}
|
|
57
|
+
function isNullOrUndefined(value) {
|
|
58
|
+
return value === null || value === undefined;
|
|
59
|
+
}
|
|
60
|
+
function isObject(value) {
|
|
61
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
62
|
+
}
|
|
63
|
+
const hasProperty = (objectToCheck, name)=>Object.hasOwnProperty.call(objectToCheck, name);
|
|
64
|
+
function getKnownPropertyNames(object) {
|
|
65
|
+
return Object.getOwnPropertyNames(object);
|
|
66
|
+
}
|
|
67
|
+
var JsonSize;
|
|
68
|
+
(function(JsonSize) {
|
|
69
|
+
JsonSize[JsonSize["Null"] = 4] = "Null";
|
|
70
|
+
JsonSize[JsonSize["Comma"] = 1] = "Comma";
|
|
71
|
+
JsonSize[JsonSize["Wrapper"] = 1] = "Wrapper";
|
|
72
|
+
JsonSize[JsonSize["True"] = 4] = "True";
|
|
73
|
+
JsonSize[JsonSize["False"] = 5] = "False";
|
|
74
|
+
JsonSize[JsonSize["Quote"] = 1] = "Quote";
|
|
75
|
+
JsonSize[JsonSize["Colon"] = 1] = "Colon";
|
|
76
|
+
JsonSize[JsonSize[// eslint-disable-next-line @typescript-eslint/no-shadow
|
|
77
|
+
"Date"] = 24] = "Date";
|
|
78
|
+
})(JsonSize || (JsonSize = {}));
|
|
79
|
+
const ESCAPE_CHARACTERS_REGEXP = /"|\\|\n|\r|\t/gu;
|
|
80
|
+
function isPlainObject(value) {
|
|
81
|
+
if (typeof value !== 'object' || value === null) {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
let proto = value;
|
|
86
|
+
while(Object.getPrototypeOf(proto) !== null){
|
|
87
|
+
proto = Object.getPrototypeOf(proto);
|
|
88
|
+
}
|
|
89
|
+
return Object.getPrototypeOf(value) === proto;
|
|
90
|
+
} catch (_) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function isASCII(character) {
|
|
95
|
+
return character.charCodeAt(0) <= 127;
|
|
96
|
+
}
|
|
97
|
+
function calculateStringSize(value) {
|
|
98
|
+
const size = value.split('').reduce((total, character)=>{
|
|
99
|
+
if (isASCII(character)) {
|
|
100
|
+
return total + 1;
|
|
101
|
+
}
|
|
102
|
+
return total + 2;
|
|
103
|
+
}, 0);
|
|
104
|
+
// Also detect characters that need backslash escape
|
|
105
|
+
return size + (value.match(ESCAPE_CHARACTERS_REGEXP) ?? []).length;
|
|
106
|
+
}
|
|
107
|
+
function calculateNumberSize(value) {
|
|
108
|
+
return value.toString().length;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
//# sourceMappingURL=misc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/misc.ts"],"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 * 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/ban-types\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 */\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\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"],"names":["isNonEmptyArray","isNullOrUndefined","isObject","hasProperty","getKnownPropertyNames","ESCAPE_CHARACTERS_REGEXP","isPlainObject","isASCII","calculateStringSize","calculateNumberSize","value","Array","isArray","length","undefined","Boolean","objectToCheck","name","Object","hasOwnProperty","call","object","getOwnPropertyNames","JsonSize","Null","Comma","Wrapper","True","False","Quote","Colon","Date","proto","getPrototypeOf","_","character","charCodeAt","size","split","reduce","total","match","toString"],"mappings":"AAAA,EAAE;AACF,QAAQ;AACR,EAAE;AAEF;;;;;CAKC;;;;;;;;;;;;;;IAwCeA,eAAe;eAAfA;;IAYAC,iBAAiB;eAAjBA;;IAWAC,QAAQ;eAARA;;IAgBHC,WAAW;eAAXA;;IAwBGC,qBAAqB;eAArBA;;IA0BHC,wBAAwB;eAAxBA;;IASGC,aAAa;eAAbA;;IAuBAC,OAAO;eAAPA;;IAUAC,mBAAmB;eAAnBA;;IAkBAC,mBAAmB;eAAnBA;;;AArJT,SAAST,gBACdU,KAAgB;IAEhB,OAAOC,MAAMC,OAAO,CAACF,UAAUA,MAAMG,MAAM,GAAG;AAChD;AAQO,SAASZ,kBAAkBS,KAAc;IAC9C,OAAOA,UAAU,QAAQA,UAAUI;AACrC;AASO,SAASZ,SAASQ,KAAc;IACrC,OAAOK,QAAQL,UAAU,OAAOA,UAAU,YAAY,CAACC,MAAMC,OAAO,CAACF;AACvE;AAcO,MAAMP,cAAc,CAKzBa,eACAC,OAKKC,OAAOC,cAAc,CAACC,IAAI,CAACJ,eAAeC;AAa1C,SAASb,sBACdiB,MAAiC;IAEjC,OAAOH,OAAOI,mBAAmB,CAACD;AACpC;IAOO;UAAKE,QAAQ;IAARA,SAAAA,SACVC,UAAO,KAAPA;IADUD,SAAAA,SAEVE,WAAQ,KAARA;IAFUF,SAAAA,SAGVG,aAAU,KAAVA;IAHUH,SAAAA,SAIVI,UAAO,KAAPA;IAJUJ,SAAAA,SAKVK,WAAQ,KAARA;IALUL,SAAAA,SAMVM,WAAQ,KAARA;IANUN,SAAAA,SAOVO,WAAQ,KAARA;IAPUP,SAAAA,SAQV,wDAAwD;IACxDQ,UAAO,MAAPA;GATUR,aAAAA;AAeL,MAAMlB,2BAA2B;AASjC,SAASC,cAAcI,KAAc;IAC1C,IAAI,OAAOA,UAAU,YAAYA,UAAU,MAAM;QAC/C,OAAO;IACT;IAEA,IAAI;QACF,IAAIsB,QAAQtB;QACZ,MAAOQ,OAAOe,cAAc,CAACD,WAAW,KAAM;YAC5CA,QAAQd,OAAOe,cAAc,CAACD;QAChC;QAEA,OAAOd,OAAOe,cAAc,CAACvB,WAAWsB;IAC1C,EAAE,OAAOE,GAAG;QACV,OAAO;IACT;AACF;AAQO,SAAS3B,QAAQ4B,SAAiB;IACvC,OAAOA,UAAUC,UAAU,CAAC,MAAM;AACpC;AAQO,SAAS5B,oBAAoBE,KAAa;IAC/C,MAAM2B,OAAO3B,MAAM4B,KAAK,CAAC,IAAIC,MAAM,CAAC,CAACC,OAAOL;QAC1C,IAAI5B,QAAQ4B,YAAY;YACtB,OAAOK,QAAQ;QACjB;QACA,OAAOA,QAAQ;IACjB,GAAG;IAEH,oDAAoD;IACpD,OAAOH,OAAO,AAAC3B,CAAAA,MAAM+B,KAAK,CAACpC,6BAA6B,EAAE,AAAD,EAAGQ,MAAM;AACpE;AAQO,SAASJ,oBAAoBC,KAAa;IAC/C,OAAOA,MAAMgC,QAAQ,GAAG7B,MAAM;AAChC"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
numberToHex: function() {
|
|
13
|
+
return numberToHex;
|
|
14
|
+
},
|
|
15
|
+
bigIntToHex: function() {
|
|
16
|
+
return bigIntToHex;
|
|
17
|
+
},
|
|
18
|
+
hexToNumber: function() {
|
|
19
|
+
return hexToNumber;
|
|
20
|
+
},
|
|
21
|
+
hexToBigInt: function() {
|
|
22
|
+
return hexToBigInt;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
const _assert = require("./assert");
|
|
26
|
+
const _hex = require("./hex");
|
|
27
|
+
const numberToHex = (value)=>{
|
|
28
|
+
(0, _assert.assert)(typeof value === 'number', 'Value must be a number.');
|
|
29
|
+
(0, _assert.assert)(value >= 0, 'Value must be a non-negative number.');
|
|
30
|
+
(0, _assert.assert)(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToHex` instead.');
|
|
31
|
+
return (0, _hex.add0x)(value.toString(16));
|
|
32
|
+
};
|
|
33
|
+
const bigIntToHex = (value)=>{
|
|
34
|
+
(0, _assert.assert)(typeof value === 'bigint', 'Value must be a bigint.');
|
|
35
|
+
(0, _assert.assert)(value >= 0, 'Value must be a non-negative bigint.');
|
|
36
|
+
return (0, _hex.add0x)(value.toString(16));
|
|
37
|
+
};
|
|
38
|
+
const hexToNumber = (value)=>{
|
|
39
|
+
(0, _hex.assertIsHexString)(value);
|
|
40
|
+
// `parseInt` accepts values without the "0x"-prefix, whereas `Number` does
|
|
41
|
+
// not. Using this is slightly faster than `Number(add0x(value))`.
|
|
42
|
+
const numberValue = parseInt(value, 16);
|
|
43
|
+
(0, _assert.assert)(Number.isSafeInteger(numberValue), 'Value is not a safe integer. Use `hexToBigInt` instead.');
|
|
44
|
+
return numberValue;
|
|
45
|
+
};
|
|
46
|
+
const hexToBigInt = (value)=>{
|
|
47
|
+
(0, _hex.assertIsHexString)(value);
|
|
48
|
+
// The `BigInt` constructor requires the "0x"-prefix to parse a hex string.
|
|
49
|
+
return BigInt((0, _hex.add0x)(value));
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=number.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/number.ts"],"sourcesContent":["import { assert } from './assert';\nimport { add0x, assertIsHexString } from './hex';\n\n/**\n * Convert a number to a hexadecimal string. This verifies that the number is a\n * non-negative safe integer.\n *\n * To convert a `bigint` to a hexadecimal string instead, use\n * {@link bigIntToHex}.\n *\n * @example\n * ```typescript\n * numberToHex(0); // '0x0'\n * numberToHex(1); // '0x1'\n * numberToHex(16); // '0x10'\n * ```\n * @param value - The number to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the number is not a non-negative safe integer.\n */\nexport const numberToHex = (value: number): string => {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToHex` instead.',\n );\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a `bigint` to a hexadecimal string. This verifies that the `bigint`\n * is a non-negative integer.\n *\n * To convert a number to a hexadecimal string instead, use {@link numberToHex}.\n *\n * @example\n * ```typescript\n * bigIntToHex(0n); // '0x0'\n * bigIntToHex(1n); // '0x1'\n * bigIntToHex(16n); // '0x10'\n * ```\n * @param value - The `bigint` to convert to a hexadecimal string.\n * @returns The hexadecimal string, with the \"0x\"-prefix.\n * @throws If the `bigint` is not a non-negative integer.\n */\nexport const bigIntToHex = (value: bigint): string => {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= 0, 'Value must be a non-negative bigint.');\n\n return add0x(value.toString(16));\n};\n\n/**\n * Convert a hexadecimal string to a number. This verifies that the string is a\n * valid hex string, and that the resulting number is a safe integer. Both\n * \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a `bigint` instead, use\n * {@link hexToBigInt}.\n *\n * @example\n * ```typescript\n * hexToNumber('0x0'); // 0\n * hexToNumber('0x1'); // 1\n * hexToNumber('0x10'); // 16\n * ```\n * @param value - The hexadecimal string to convert to a number.\n * @returns The number.\n * @throws If the value is not a valid hexadecimal string, or if the resulting\n * number is not a safe integer.\n */\nexport const hexToNumber = (value: string): number => {\n assertIsHexString(value);\n\n // `parseInt` accepts values without the \"0x\"-prefix, whereas `Number` does\n // not. Using this is slightly faster than `Number(add0x(value))`.\n const numberValue = parseInt(value, 16);\n\n assert(\n Number.isSafeInteger(numberValue),\n 'Value is not a safe integer. Use `hexToBigInt` instead.',\n );\n\n return numberValue;\n};\n\n/**\n * Convert a hexadecimal string to a `bigint`. This verifies that the string is\n * a valid hex string. Both \"0x\"-prefixed and unprefixed strings are supported.\n *\n * To convert a hexadecimal string to a number instead, use {@link hexToNumber}.\n *\n * @example\n * ```typescript\n * hexToBigInt('0x0'); // 0n\n * hexToBigInt('0x1'); // 1n\n * hexToBigInt('0x10'); // 16n\n * ```\n * @param value - The hexadecimal string to convert to a `bigint`.\n * @returns The `bigint`.\n * @throws If the value is not a valid hexadecimal string.\n */\nexport const hexToBigInt = (value: string): bigint => {\n assertIsHexString(value);\n\n // The `BigInt` constructor requires the \"0x\"-prefix to parse a hex string.\n return BigInt(add0x(value));\n};\n"],"names":["numberToHex","bigIntToHex","hexToNumber","hexToBigInt","value","assert","Number","isSafeInteger","add0x","toString","assertIsHexString","numberValue","parseInt","BigInt"],"mappings":";;;;;;;;;;;IAoBaA,WAAW;eAAXA;;IA2BAC,WAAW;eAAXA;;IA0BAC,WAAW;eAAXA;;IA+BAC,WAAW;eAAXA;;;wBAxGU;qBACkB;AAmBlC,MAAMH,cAAc,CAACI;IAC1BC,IAAAA,cAAM,EAAC,OAAOD,UAAU,UAAU;IAClCC,IAAAA,cAAM,EAACD,SAAS,GAAG;IACnBC,IAAAA,cAAM,EACJC,OAAOC,aAAa,CAACH,QACrB;IAGF,OAAOI,IAAAA,UAAK,EAACJ,MAAMK,QAAQ,CAAC;AAC9B;AAkBO,MAAMR,cAAc,CAACG;IAC1BC,IAAAA,cAAM,EAAC,OAAOD,UAAU,UAAU;IAClCC,IAAAA,cAAM,EAACD,SAAS,GAAG;IAEnB,OAAOI,IAAAA,UAAK,EAACJ,MAAMK,QAAQ,CAAC;AAC9B;AAqBO,MAAMP,cAAc,CAACE;IAC1BM,IAAAA,sBAAiB,EAACN;IAElB,2EAA2E;IAC3E,kEAAkE;IAClE,MAAMO,cAAcC,SAASR,OAAO;IAEpCC,IAAAA,cAAM,EACJC,OAAOC,aAAa,CAACI,cACrB;IAGF,OAAOA;AACT;AAkBO,MAAMR,cAAc,CAACC;IAC1BM,IAAAA,sBAAiB,EAACN;IAElB,2EAA2E;IAC3E,OAAOS,OAAOL,IAAAA,UAAK,EAACJ;AACtB"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// We use a symbol property name instead of { _type: Brand }, because that would show up in IDE suggestions,
|
|
2
|
+
// while internal symbols do not.
|
|
3
|
+
"use strict";
|
|
4
|
+
Object.defineProperty(exports, "__esModule", {
|
|
5
|
+
value: true
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
//# sourceMappingURL=opaque.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/opaque.ts"],"sourcesContent":["// We use a symbol property name instead of { _type: Brand }, because that would show up in IDE suggestions,\n// while internal symbols do not.\ndeclare const brand: unique symbol;\nexport type Opaque<Base, Brand extends symbol> = Base & { [brand]: Brand };\n"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,iCAAiC"}
|
package/dist/cjs/time.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Common duration constants, in milliseconds.
|
|
3
|
+
*/ "use strict";
|
|
4
|
+
Object.defineProperty(exports, "__esModule", {
|
|
5
|
+
value: true
|
|
6
|
+
});
|
|
7
|
+
function _export(target, all) {
|
|
8
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
9
|
+
enumerable: true,
|
|
10
|
+
get: all[name]
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
_export(exports, {
|
|
14
|
+
Duration: function() {
|
|
15
|
+
return Duration;
|
|
16
|
+
},
|
|
17
|
+
inMilliseconds: function() {
|
|
18
|
+
return inMilliseconds;
|
|
19
|
+
},
|
|
20
|
+
timeSince: function() {
|
|
21
|
+
return timeSince;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
var Duration;
|
|
25
|
+
(function(Duration) {
|
|
26
|
+
Duration[Duration[/**
|
|
27
|
+
* A millisecond.
|
|
28
|
+
*/ "Millisecond"] = 1] = "Millisecond";
|
|
29
|
+
Duration[Duration[/**
|
|
30
|
+
* A second, in milliseconds.
|
|
31
|
+
*/ "Second"] = 1000] = "Second";
|
|
32
|
+
Duration[Duration[/**
|
|
33
|
+
* A minute, in milliseconds.
|
|
34
|
+
*/ "Minute"] = 60000] = "Minute";
|
|
35
|
+
Duration[Duration[/**
|
|
36
|
+
* An hour, in milliseconds.
|
|
37
|
+
*/ "Hour"] = 3600000] = "Hour";
|
|
38
|
+
Duration[Duration[/**
|
|
39
|
+
* A day, in milliseconds.
|
|
40
|
+
*/ "Day"] = 86400000] = "Day";
|
|
41
|
+
Duration[Duration[/**
|
|
42
|
+
* A week, in milliseconds.
|
|
43
|
+
*/ "Week"] = 604800000] = "Week";
|
|
44
|
+
Duration[Duration[/**
|
|
45
|
+
* A year, in milliseconds.
|
|
46
|
+
*/ "Year"] = 31536000000] = "Year";
|
|
47
|
+
})(Duration || (Duration = {}));
|
|
48
|
+
const isNonNegativeInteger = (number)=>Number.isInteger(number) && number >= 0;
|
|
49
|
+
const assertIsNonNegativeInteger = (number, name)=>{
|
|
50
|
+
if (!isNonNegativeInteger(number)) {
|
|
51
|
+
throw new Error(`"${name}" must be a non-negative integer. Received: "${number}".`);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
function inMilliseconds(count, duration) {
|
|
55
|
+
assertIsNonNegativeInteger(count, 'count');
|
|
56
|
+
return count * duration;
|
|
57
|
+
}
|
|
58
|
+
function timeSince(timestamp) {
|
|
59
|
+
assertIsNonNegativeInteger(timestamp, 'timestamp');
|
|
60
|
+
return Date.now() - timestamp;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=time.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/time.ts"],"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) =>\n Number.isInteger(number) && number >= 0;\n\nconst assertIsNonNegativeInteger = (number: number, name: string) => {\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"],"names":["inMilliseconds","timeSince","Duration","Millisecond","Second","Minute","Hour","Day","Week","Year","isNonNegativeInteger","number","Number","isInteger","assertIsNonNegativeInteger","name","Error","count","duration","timestamp","Date","now"],"mappings":"AAAA;;CAEC;;;;;;;;;;;;;;IAwDeA,cAAc;eAAdA;;IAWAC,SAAS;eAATA;;;IAlET;UAAKC,QAAQ;IAARA,SAAAA,SACV;;GAEC,GACDC,iBAAc,KAAdA;IAJUD,SAAAA,SAMV;;GAEC,GACDE,YAAS,QAATA;IATUF,SAAAA,SAWV;;GAEC,GACDG,YAAS,SAATA;IAdUH,SAAAA,SAgBV;;GAEC,GACDI,UAAO,WAAPA;IAnBUJ,SAAAA,SAqBV;;GAEC,GACDK,SAAM,YAANA;IAxBUL,SAAAA,SA0BV;;GAEC,GACDM,UAAO,aAAPA;IA7BUN,SAAAA,SA+BV;;GAEC,GACDO,UAAO,eAAPA;GAlCUP,aAAAA;AAqCZ,MAAMQ,uBAAuB,CAACC,SAC5BC,OAAOC,SAAS,CAACF,WAAWA,UAAU;AAExC,MAAMG,6BAA6B,CAACH,QAAgBI;IAClD,IAAI,CAACL,qBAAqBC,SAAS;QACjC,MAAM,IAAIK,MACR,CAAC,CAAC,EAAED,KAAK,6CAA6C,EAAEJ,OAAO,EAAE,CAAC;IAEtE;AACF;AASO,SAASX,eAAeiB,KAAa,EAAEC,QAAkB;IAC9DJ,2BAA2BG,OAAO;IAClC,OAAOA,QAAQC;AACjB;AAQO,SAASjB,UAAUkB,SAAiB;IACzCL,2BAA2BK,WAAW;IACtC,OAAOC,KAAKC,GAAG,KAAKF;AACtB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/transaction-types.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
VersionStruct: function() {
|
|
13
|
+
return VersionStruct;
|
|
14
|
+
},
|
|
15
|
+
VersionRangeStruct: function() {
|
|
16
|
+
return VersionRangeStruct;
|
|
17
|
+
},
|
|
18
|
+
isValidSemVerVersion: function() {
|
|
19
|
+
return isValidSemVerVersion;
|
|
20
|
+
},
|
|
21
|
+
isValidSemVerRange: function() {
|
|
22
|
+
return isValidSemVerRange;
|
|
23
|
+
},
|
|
24
|
+
assertIsSemVerVersion: function() {
|
|
25
|
+
return assertIsSemVerVersion;
|
|
26
|
+
},
|
|
27
|
+
assertIsSemVerRange: function() {
|
|
28
|
+
return assertIsSemVerRange;
|
|
29
|
+
},
|
|
30
|
+
gtVersion: function() {
|
|
31
|
+
return gtVersion;
|
|
32
|
+
},
|
|
33
|
+
gtRange: function() {
|
|
34
|
+
return gtRange;
|
|
35
|
+
},
|
|
36
|
+
satisfiesVersionRange: function() {
|
|
37
|
+
return satisfiesVersionRange;
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
const _semver = require("semver");
|
|
41
|
+
const _superstruct = require("superstruct");
|
|
42
|
+
const _assert = require("./assert");
|
|
43
|
+
const VersionStruct = (0, _superstruct.refine)((0, _superstruct.string)(), 'Version', (value)=>{
|
|
44
|
+
if ((0, _semver.valid)(value) === null) {
|
|
45
|
+
return `Expected SemVer version, got "${value}"`;
|
|
46
|
+
}
|
|
47
|
+
return true;
|
|
48
|
+
});
|
|
49
|
+
const VersionRangeStruct = (0, _superstruct.refine)((0, _superstruct.string)(), 'Version range', (value)=>{
|
|
50
|
+
if ((0, _semver.validRange)(value) === null) {
|
|
51
|
+
return `Expected SemVer range, got "${value}"`;
|
|
52
|
+
}
|
|
53
|
+
return true;
|
|
54
|
+
});
|
|
55
|
+
function isValidSemVerVersion(version) {
|
|
56
|
+
return (0, _superstruct.is)(version, VersionStruct);
|
|
57
|
+
}
|
|
58
|
+
function isValidSemVerRange(versionRange) {
|
|
59
|
+
return (0, _superstruct.is)(versionRange, VersionRangeStruct);
|
|
60
|
+
}
|
|
61
|
+
function assertIsSemVerVersion(version) {
|
|
62
|
+
(0, _assert.assertStruct)(version, VersionStruct);
|
|
63
|
+
}
|
|
64
|
+
function assertIsSemVerRange(range) {
|
|
65
|
+
(0, _assert.assertStruct)(range, VersionRangeStruct);
|
|
66
|
+
}
|
|
67
|
+
function gtVersion(version1, version2) {
|
|
68
|
+
return (0, _semver.gt)(version1, version2);
|
|
69
|
+
}
|
|
70
|
+
function gtRange(version, range) {
|
|
71
|
+
return (0, _semver.gtr)(version, range);
|
|
72
|
+
}
|
|
73
|
+
function satisfiesVersionRange(version, versionRange) {
|
|
74
|
+
return (0, _semver.satisfies)(version, versionRange, {
|
|
75
|
+
includePrerelease: true
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
//# sourceMappingURL=versions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/versions.ts"],"sourcesContent":["import {\n gt as gtSemver,\n gtr as gtrSemver,\n satisfies as satisfiesSemver,\n valid as validSemVerVersion,\n validRange as validSemVerRange,\n} from 'semver';\nimport type { Struct } from 'superstruct';\nimport { is, refine, string } from 'superstruct';\n\nimport { assertStruct } from './assert';\nimport type { Opaque } from './opaque';\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for SemVer ranges.\n *\n * @example Use {@link assertIsSemVerRange} and {@link isValidSemVerRange} to cast to proper type.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * assertIsSemVerRange(unsafeRange);\n * unsafeRange\n * // ^? SemVerRange\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeRange: string = dataFromUser();\n * unsafeRange as SemVerRange;\n * // ^? SemVerRange\n * ```\n * @see {@link assertIsSemVerRange}\n * @see {@link isValidSemVerRange}\n */\nexport type SemVerRange = Opaque<string, typeof semVerRange>;\ndeclare const semVerRange: unique symbol;\n\n/**\n * {@link https://codemix.com/opaque-types-in-javascript/ Opaque} type for singular SemVer version.\n *\n * @example Use {@link assertIsSemVerVersion} and {@link isValidSemVerVersion} to cast to proper type.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * assertIsSemVerVersion(unsafeRange);\n * unsafeVersion\n * // ^? SemVerVersion\n * ```\n * @example If you know what you're doing and want to side-step type safety, casting from a string works correctly.\n * ```typescript\n * const unsafeVersion: string = dataFromUser();\n * unsafeRange as SemVerVersion;\n * // ^? SemVerVersion\n * ```\n * @see {@link assertIsSemVerVersion}\n * @see {@link isValidSemVerVersion}\n */\nexport type SemVerVersion = Opaque<string, typeof semVerVersion>;\ndeclare const semVerVersion: unique symbol;\n\n/**\n * A struct for validating a version string.\n */\nexport const VersionStruct = refine<SemVerVersion, null>(\n string() as unknown as Struct<SemVerVersion, null>,\n 'Version',\n (value) => {\n if (validSemVerVersion(value) === null) {\n return `Expected SemVer version, got \"${value}\"`;\n }\n return true;\n },\n);\n\nexport const VersionRangeStruct = refine<SemVerRange, null>(\n string() as unknown as Struct<SemVerRange, null>,\n 'Version range',\n (value) => {\n if (validSemVerRange(value) === null) {\n return `Expected SemVer range, got \"${value}\"`;\n }\n return true;\n },\n);\n\n/**\n * Checks whether a SemVer version is valid.\n *\n * @param version - A potential version.\n * @returns `true` if the version is valid, and `false` otherwise.\n */\nexport function isValidSemVerVersion(\n version: unknown,\n): version is SemVerVersion {\n return is(version, VersionStruct);\n}\n\n/**\n * Checks whether a SemVer version range is valid.\n *\n * @param versionRange - A potential version range.\n * @returns `true` if the version range is valid, and `false` otherwise.\n */\nexport function isValidSemVerRange(\n versionRange: unknown,\n): versionRange is SemVerRange {\n return is(versionRange, VersionRangeStruct);\n}\n\n/**\n * Asserts that a value is a valid concrete SemVer version.\n *\n * @param version - A potential SemVer concrete version.\n */\nexport function assertIsSemVerVersion(\n version: unknown,\n): asserts version is SemVerVersion {\n assertStruct(version, VersionStruct);\n}\n\n/**\n * Asserts that a value is a valid SemVer range.\n *\n * @param range - A potential SemVer range.\n */\nexport function assertIsSemVerRange(\n range: unknown,\n): asserts range is SemVerRange {\n assertStruct(range, VersionRangeStruct);\n}\n\n/**\n * Checks whether a SemVer version is greater than another.\n *\n * @param version1 - The left-hand version.\n * @param version2 - The right-hand version.\n * @returns `version1 > version2`.\n */\nexport function gtVersion(\n version1: SemVerVersion,\n version2: SemVerVersion,\n): boolean {\n return gtSemver(version1, version2);\n}\n\n/**\n * Checks whether a SemVer version is greater than all possibilities in a range.\n *\n * @param version - A SemvVer version.\n * @param range - The range to check against.\n * @returns `version > range`.\n */\nexport function gtRange(version: SemVerVersion, range: SemVerRange): boolean {\n return gtrSemver(version, range);\n}\n\n/**\n * Returns whether a SemVer version satisfies a SemVer range.\n *\n * @param version - The SemVer version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns Whether the version satisfied the version range.\n */\nexport function satisfiesVersionRange(\n version: SemVerVersion,\n versionRange: SemVerRange,\n): boolean {\n return satisfiesSemver(version, versionRange, {\n includePrerelease: true,\n });\n}\n"],"names":["VersionStruct","VersionRangeStruct","isValidSemVerVersion","isValidSemVerRange","assertIsSemVerVersion","assertIsSemVerRange","gtVersion","gtRange","satisfiesVersionRange","refine","string","value","validSemVerVersion","validSemVerRange","version","is","versionRange","assertStruct","range","version1","version2","gtSemver","gtrSemver","satisfiesSemver","includePrerelease"],"mappings":";;;;;;;;;;;IA4DaA,aAAa;eAAbA;;IAWAC,kBAAkB;eAAlBA;;IAiBGC,oBAAoB;eAApBA;;IAYAC,kBAAkB;eAAlBA;;IAWAC,qBAAqB;eAArBA;;IAWAC,mBAAmB;eAAnBA;;IAaAC,SAAS;eAATA;;IAcAC,OAAO;eAAPA;;IAWAC,qBAAqB;eAArBA;;;wBA1JT;6BAE4B;wBAEN;AAkDtB,MAAMR,gBAAgBS,IAAAA,mBAAM,EACjCC,IAAAA,mBAAM,KACN,WACA,CAACC;IACC,IAAIC,IAAAA,aAAkB,EAACD,WAAW,MAAM;QACtC,OAAO,CAAC,8BAA8B,EAAEA,MAAM,CAAC,CAAC;IAClD;IACA,OAAO;AACT;AAGK,MAAMV,qBAAqBQ,IAAAA,mBAAM,EACtCC,IAAAA,mBAAM,KACN,iBACA,CAACC;IACC,IAAIE,IAAAA,kBAAgB,EAACF,WAAW,MAAM;QACpC,OAAO,CAAC,4BAA4B,EAAEA,MAAM,CAAC,CAAC;IAChD;IACA,OAAO;AACT;AASK,SAAST,qBACdY,OAAgB;IAEhB,OAAOC,IAAAA,eAAE,EAACD,SAASd;AACrB;AAQO,SAASG,mBACda,YAAqB;IAErB,OAAOD,IAAAA,eAAE,EAACC,cAAcf;AAC1B;AAOO,SAASG,sBACdU,OAAgB;IAEhBG,IAAAA,oBAAY,EAACH,SAASd;AACxB;AAOO,SAASK,oBACda,KAAc;IAEdD,IAAAA,oBAAY,EAACC,OAAOjB;AACtB;AASO,SAASK,UACda,QAAuB,EACvBC,QAAuB;IAEvB,OAAOC,IAAAA,UAAQ,EAACF,UAAUC;AAC5B;AASO,SAASb,QAAQO,OAAsB,EAAEI,KAAkB;IAChE,OAAOI,IAAAA,WAAS,EAACR,SAASI;AAC5B;AASO,SAASV,sBACdM,OAAsB,EACtBE,YAAyB;IAEzB,OAAOO,IAAAA,iBAAe,EAACT,SAASE,cAAc;QAC5CQ,mBAAmB;IACrB;AACF"}
|
|
@@ -1,15 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
function _define_property(obj, key, value) {
|
|
2
|
+
if (key in obj) {
|
|
3
|
+
Object.defineProperty(obj, key, {
|
|
4
|
+
value: value,
|
|
5
|
+
enumerable: true,
|
|
6
|
+
configurable: true,
|
|
7
|
+
writable: true
|
|
8
|
+
});
|
|
9
|
+
} else {
|
|
10
|
+
obj[key] = value;
|
|
11
|
+
}
|
|
12
|
+
return obj;
|
|
13
|
+
}
|
|
14
|
+
import { assert as assertSuperstruct } from 'superstruct';
|
|
5
15
|
/**
|
|
6
16
|
* Type guard for determining whether the given value is an error object with a
|
|
7
17
|
* `message` property, such as an instance of Error.
|
|
8
18
|
*
|
|
9
19
|
* @param error - The object to check.
|
|
10
20
|
* @returns True or false, depending on the result.
|
|
11
|
-
*/
|
|
12
|
-
function isErrorWithMessage(error) {
|
|
21
|
+
*/ function isErrorWithMessage(error) {
|
|
13
22
|
return typeof error === 'object' && error !== null && 'message' in error;
|
|
14
23
|
}
|
|
15
24
|
/**
|
|
@@ -18,10 +27,8 @@ function isErrorWithMessage(error) {
|
|
|
18
27
|
*
|
|
19
28
|
* @param fn - The value to check.
|
|
20
29
|
* @returns `true` if the value is a constructor, or `false` otherwise.
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
/* istanbul ignore next */
|
|
24
|
-
return Boolean(typeof fn?.prototype?.constructor?.name === 'string');
|
|
30
|
+
*/ function isConstructable(fn) {
|
|
31
|
+
/* istanbul ignore next */ return Boolean(typeof fn?.prototype?.constructor?.name === 'string');
|
|
25
32
|
}
|
|
26
33
|
/**
|
|
27
34
|
* Get the error message from an unknown error object. If the error object has
|
|
@@ -30,8 +37,7 @@ function isConstructable(fn) {
|
|
|
30
37
|
*
|
|
31
38
|
* @param error - The error object to get the message from.
|
|
32
39
|
* @returns The error message.
|
|
33
|
-
*/
|
|
34
|
-
function getErrorMessage(error) {
|
|
40
|
+
*/ function getErrorMessage(error) {
|
|
35
41
|
const message = isErrorWithMessage(error) ? error.message : String(error);
|
|
36
42
|
// If the error ends with a period, remove it, as we'll add our own period.
|
|
37
43
|
if (message.endsWith('.')) {
|
|
@@ -45,28 +51,25 @@ function getErrorMessage(error) {
|
|
|
45
51
|
* @param ErrorWrapper - The error class to use.
|
|
46
52
|
* @param message - The error message.
|
|
47
53
|
* @returns The error object.
|
|
48
|
-
*/
|
|
49
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
54
|
+
*/ // eslint-disable-next-line @typescript-eslint/naming-convention
|
|
50
55
|
function getError(ErrorWrapper, message) {
|
|
51
56
|
if (isConstructable(ErrorWrapper)) {
|
|
52
57
|
return new ErrorWrapper({
|
|
53
|
-
message
|
|
58
|
+
message
|
|
54
59
|
});
|
|
55
60
|
}
|
|
56
61
|
return ErrorWrapper({
|
|
57
|
-
message
|
|
62
|
+
message
|
|
58
63
|
});
|
|
59
64
|
}
|
|
60
65
|
/**
|
|
61
66
|
* The default error class that is thrown if an assertion fails.
|
|
62
|
-
*/
|
|
63
|
-
|
|
64
|
-
constructor(options) {
|
|
67
|
+
*/ export class AssertionError extends Error {
|
|
68
|
+
constructor(options){
|
|
65
69
|
super(options.message);
|
|
66
|
-
this
|
|
70
|
+
_define_property(this, "code", 'ERR_ASSERTION');
|
|
67
71
|
}
|
|
68
72
|
}
|
|
69
|
-
exports.AssertionError = AssertionError;
|
|
70
73
|
/**
|
|
71
74
|
* Same as Node.js assert.
|
|
72
75
|
* If the value is falsy, throws an error, does nothing otherwise.
|
|
@@ -78,9 +81,7 @@ exports.AssertionError = AssertionError;
|
|
|
78
81
|
* @param ErrorWrapper - The error class to throw if the assertion fails.
|
|
79
82
|
* Defaults to {@link AssertionError}. If a custom error class is provided for
|
|
80
83
|
* the `message` argument, this argument is ignored.
|
|
81
|
-
*/
|
|
82
|
-
function assert(value, message = 'Assertion failed.',
|
|
83
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
84
|
+
*/ export function assert(value, message = 'Assertion failed.', // eslint-disable-next-line @typescript-eslint/naming-convention
|
|
84
85
|
ErrorWrapper = AssertionError) {
|
|
85
86
|
if (!value) {
|
|
86
87
|
if (message instanceof Error) {
|
|
@@ -89,7 +90,6 @@ ErrorWrapper = AssertionError) {
|
|
|
89
90
|
throw getError(ErrorWrapper, message);
|
|
90
91
|
}
|
|
91
92
|
}
|
|
92
|
-
exports.assert = assert;
|
|
93
93
|
/**
|
|
94
94
|
* Assert a value against a Superstruct struct.
|
|
95
95
|
*
|
|
@@ -100,18 +100,14 @@ exports.assert = assert;
|
|
|
100
100
|
* @param ErrorWrapper - The error class to throw if the assertion fails.
|
|
101
101
|
* Defaults to {@link AssertionError}.
|
|
102
102
|
* @throws If the value is not valid.
|
|
103
|
-
*/
|
|
104
|
-
function assertStruct(value, struct, errorPrefix = 'Assertion failed',
|
|
105
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
103
|
+
*/ export function assertStruct(value, struct, errorPrefix = 'Assertion failed', // eslint-disable-next-line @typescript-eslint/naming-convention
|
|
106
104
|
ErrorWrapper = AssertionError) {
|
|
107
105
|
try {
|
|
108
|
-
(
|
|
109
|
-
}
|
|
110
|
-
catch (error) {
|
|
106
|
+
assertSuperstruct(value, struct);
|
|
107
|
+
} catch (error) {
|
|
111
108
|
throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessage(error)}.`);
|
|
112
109
|
}
|
|
113
110
|
}
|
|
114
|
-
exports.assertStruct = assertStruct;
|
|
115
111
|
/**
|
|
116
112
|
* Use in the default case of a switch that you want to be fully exhaustive.
|
|
117
113
|
* Using this function forces the compiler to enforce exhaustivity during
|
|
@@ -130,9 +126,8 @@ exports.assertStruct = assertStruct;
|
|
|
130
126
|
* }
|
|
131
127
|
* ```
|
|
132
128
|
* @param _object - The object on which the switch is being operated.
|
|
133
|
-
*/
|
|
134
|
-
function assertExhaustive(_object) {
|
|
129
|
+
*/ export function assertExhaustive(_object) {
|
|
135
130
|
throw new Error('Invalid branch reached. Should be detected during compilation.');
|
|
136
131
|
}
|
|
137
|
-
|
|
132
|
+
|
|
138
133
|
//# sourceMappingURL=assert.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/assert.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\nimport { assert as assertSuperstruct } from 'superstruct';\n\nexport type AssertionErrorConstructor =\n | (new (args: { message: string }) => Error)\n | ((args: { message: string }) => Error);\n\n/**\n * Type guard for determining whether the given value is an error object with a\n * `message` property, such as an instance of Error.\n *\n * @param error - The object to check.\n * @returns True or false, depending on the result.\n */\nfunction isErrorWithMessage(error: unknown): error is { message: string } {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n\n/**\n * Check if a value is a constructor, i.e., a function that can be called with\n * the `new` keyword.\n *\n * @param fn - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nfunction isConstructable(\n fn: AssertionErrorConstructor,\n): fn is new (args: { message: string }) => Error {\n /* istanbul ignore next */\n return Boolean(typeof fn?.prototype?.constructor?.name === 'string');\n}\n\n/**\n * Get the error message from an unknown error object. If the error object has\n * a `message` property, that property is returned. Otherwise, the stringified\n * error object is returned.\n *\n * @param error - The error object to get the message from.\n * @returns The error message.\n */\nfunction getErrorMessage(error: unknown): string {\n const message = isErrorWithMessage(error) ? error.message : String(error);\n\n // If the error ends with a period, remove it, as we'll add our own period.\n if (message.endsWith('.')) {\n return message.slice(0, -1);\n }\n\n return message;\n}\n\n/**\n * Initialise an {@link AssertionErrorConstructor} error.\n *\n * @param ErrorWrapper - The error class to use.\n * @param message - The error message.\n * @returns The error object.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction getError(ErrorWrapper: AssertionErrorConstructor, message: string) {\n if (isConstructable(ErrorWrapper)) {\n return new ErrorWrapper({\n message,\n });\n }\n return ErrorWrapper({\n message,\n });\n}\n\n/**\n * The default error class that is thrown if an assertion fails.\n */\nexport class AssertionError extends Error {\n readonly code = 'ERR_ASSERTION';\n\n constructor(options: { message: string }) {\n super(options.message);\n }\n}\n\n/**\n * Same as Node.js assert.\n * If the value is falsy, throws an error, does nothing otherwise.\n *\n * @throws {@link AssertionError} If value is falsy.\n * @param value - The test that should be truthy to pass.\n * @param message - Message to be passed to {@link AssertionError} or an\n * {@link Error} instance to throw.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}. If a custom error class is provided for\n * the `message` argument, this argument is ignored.\n */\nexport function assert(\n value: any,\n message: string | Error = 'Assertion failed.',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value {\n if (!value) {\n if (message instanceof Error) {\n throw message;\n }\n\n throw getError(ErrorWrapper, message);\n }\n}\n\n/**\n * Assert a value against a Superstruct struct.\n *\n * @param value - The value to validate.\n * @param struct - The struct to validate against.\n * @param errorPrefix - A prefix to add to the error message. Defaults to\n * \"Assertion failed\".\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the value is not valid.\n */\nexport function assertStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n errorPrefix = 'Assertion failed',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper: AssertionErrorConstructor = AssertionError,\n): asserts value is Type {\n try {\n assertSuperstruct(value, struct);\n } catch (error) {\n throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessage(error)}.`);\n }\n}\n\n/**\n * Use in the default case of a switch that you want to be fully exhaustive.\n * Using this function forces the compiler to enforce exhaustivity during\n * compile-time.\n *\n * @example\n * ```\n * const number = 1;\n * switch (number) {\n * case 0:\n * ...\n * case 1:\n * ...\n * default:\n * assertExhaustive(snapPrefix);\n * }\n * ```\n * @param _object - The object on which the switch is being operated.\n */\nexport function assertExhaustive(_object: never): never {\n throw new Error(\n 'Invalid branch reached. Should be detected during compilation.',\n );\n}\n"],"names":["assert","assertSuperstruct","isErrorWithMessage","error","isConstructable","fn","Boolean","prototype","constructor","name","getErrorMessage","message","String","endsWith","slice","getError","ErrorWrapper","AssertionError","Error","options","code","value","assertStruct","struct","errorPrefix","assertExhaustive","_object"],"mappings":";;;;;;;;;;;;;AACA,SAASA,UAAUC,iBAAiB,QAAQ,cAAc;AAM1D;;;;;;CAMC,GACD,SAASC,mBAAmBC,KAAc;IACxC,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,aAAaA;AACrE;AAEA;;;;;;CAMC,GACD,SAASC,gBACPC,EAA6B;IAE7B,wBAAwB,GACxB,OAAOC,QAAQ,OAAOD,IAAIE,WAAWC,aAAaC,SAAS;AAC7D;AAEA;;;;;;;CAOC,GACD,SAASC,gBAAgBP,KAAc;IACrC,MAAMQ,UAAUT,mBAAmBC,SAASA,MAAMQ,OAAO,GAAGC,OAAOT;IAEnE,2EAA2E;IAC3E,IAAIQ,QAAQE,QAAQ,CAAC,MAAM;QACzB,OAAOF,QAAQG,KAAK,CAAC,GAAG,CAAC;IAC3B;IAEA,OAAOH;AACT;AAEA;;;;;;CAMC,GACD,gEAAgE;AAChE,SAASI,SAASC,YAAuC,EAAEL,OAAe;IACxE,IAAIP,gBAAgBY,eAAe;QACjC,OAAO,IAAIA,aAAa;YACtBL;QACF;IACF;IACA,OAAOK,aAAa;QAClBL;IACF;AACF;AAEA;;CAEC,GACD,OAAO,MAAMM,uBAAuBC;IAGlCV,YAAYW,OAA4B,CAAE;QACxC,KAAK,CAACA,QAAQR,OAAO;QAHvB,uBAASS,QAAO;IAIhB;AACF;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASpB,OACdqB,KAAU,EACVV,UAA0B,mBAAmB,EAC7C,gEAAgE;AAChEK,eAA0CC,cAAc;IAExD,IAAI,CAACI,OAAO;QACV,IAAIV,mBAAmBO,OAAO;YAC5B,MAAMP;QACR;QAEA,MAAMI,SAASC,cAAcL;IAC/B;AACF;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASW,aACdD,KAAc,EACdE,MAA4B,EAC5BC,cAAc,kBAAkB,EAChC,gEAAgE;AAChER,eAA0CC,cAAc;IAExD,IAAI;QACFhB,kBAAkBoB,OAAOE;IAC3B,EAAE,OAAOpB,OAAO;QACd,MAAMY,SAASC,cAAc,CAAC,EAAEQ,YAAY,EAAE,EAAEd,gBAAgBP,OAAO,CAAC,CAAC;IAC3E;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASsB,iBAAiBC,OAAc;IAC7C,MAAM,IAAIR,MACR;AAEJ"}
|
|
@@ -1,34 +1,28 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
exports.base64 = void 0;
|
|
4
|
-
const superstruct_1 = require("superstruct");
|
|
5
|
-
const assert_1 = require("./assert");
|
|
1
|
+
import { pattern } from 'superstruct';
|
|
2
|
+
import { assert } from './assert';
|
|
6
3
|
/**
|
|
7
4
|
* Ensure that a provided string-based struct is valid base64.
|
|
8
5
|
*
|
|
9
6
|
* @param struct - The string based struct.
|
|
10
7
|
* @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.
|
|
11
8
|
* @returns A superstruct validating base64.
|
|
12
|
-
*/
|
|
13
|
-
const base64 = (struct, options = {}) => {
|
|
9
|
+
*/ export const base64 = (struct, options = {})=>{
|
|
14
10
|
const paddingRequired = options.paddingRequired ?? false;
|
|
15
11
|
const characterSet = options.characterSet ?? 'base64';
|
|
16
12
|
let letters;
|
|
17
13
|
if (characterSet === 'base64') {
|
|
18
|
-
letters = String.raw
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
letters = String.raw `[-_A-Za-z0-9]`;
|
|
14
|
+
letters = String.raw`[A-Za-z0-9+\/]`;
|
|
15
|
+
} else {
|
|
16
|
+
assert(characterSet === 'base64url');
|
|
17
|
+
letters = String.raw`[-_A-Za-z0-9]`;
|
|
23
18
|
}
|
|
24
19
|
let re;
|
|
25
20
|
if (paddingRequired) {
|
|
26
21
|
re = new RegExp(`^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`, 'u');
|
|
27
|
-
}
|
|
28
|
-
else {
|
|
22
|
+
} else {
|
|
29
23
|
re = new RegExp(`^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`, 'u');
|
|
30
24
|
}
|
|
31
|
-
return
|
|
25
|
+
return pattern(struct, re);
|
|
32
26
|
};
|
|
33
|
-
|
|
27
|
+
|
|
34
28
|
//# sourceMappingURL=base64.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/base64.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\nimport { pattern } from 'superstruct';\n\nimport { assert } from './assert';\n\nexport type Base64Options = {\n /**\n * Is the `=` padding at the end required or not.\n *\n * @default false\n */\n // Padding is optional in RFC 4648, that's why the default value is false\n paddingRequired?: boolean;\n /**\n * Which character set should be used.\n * The sets are based on {@link https://datatracker.ietf.org/doc/html/rfc4648 RFC 4648}.\n *\n * @default 'base64'\n */\n characterSet?: 'base64' | 'base64url';\n};\n\n/**\n * Ensure that a provided string-based struct is valid base64.\n *\n * @param struct - The string based struct.\n * @param options - Optional options to specialize base64 validation. See {@link Base64Options} documentation.\n * @returns A superstruct validating base64.\n */\nexport const base64 = <Type extends string, Schema>(\n struct: Struct<Type, Schema>,\n options: Base64Options = {},\n) => {\n const paddingRequired = options.paddingRequired ?? false;\n const characterSet = options.characterSet ?? 'base64';\n\n let letters: string;\n if (characterSet === 'base64') {\n letters = String.raw`[A-Za-z0-9+\\/]`;\n } else {\n assert(characterSet === 'base64url');\n letters = String.raw`[-_A-Za-z0-9]`;\n }\n\n let re: RegExp;\n if (paddingRequired) {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n } else {\n re = new RegExp(\n `^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`,\n 'u',\n );\n }\n\n return pattern(struct, re);\n};\n"],"names":["pattern","assert","base64","struct","options","paddingRequired","characterSet","letters","String","raw","re","RegExp"],"mappings":"AACA,SAASA,OAAO,QAAQ,cAAc;AAEtC,SAASC,MAAM,QAAQ,WAAW;AAmBlC;;;;;;CAMC,GACD,OAAO,MAAMC,SAAS,CACpBC,QACAC,UAAyB,CAAC,CAAC;IAE3B,MAAMC,kBAAkBD,QAAQC,eAAe,IAAI;IACnD,MAAMC,eAAeF,QAAQE,YAAY,IAAI;IAE7C,IAAIC;IACJ,IAAID,iBAAiB,UAAU;QAC7BC,UAAUC,OAAOC,GAAG,CAAC,cAAc,CAAC;IACtC,OAAO;QACLR,OAAOK,iBAAiB;QACxBC,UAAUC,OAAOC,GAAG,CAAC,aAAa,CAAC;IACrC;IAEA,IAAIC;IACJ,IAAIL,iBAAiB;QACnBK,KAAK,IAAIC,OACP,CAAC,IAAI,EAAEJ,QAAQ,QAAQ,EAAEA,QAAQ,KAAK,EAAEA,QAAQ,QAAQ,CAAC,EACzD;IAEJ,OAAO;QACLG,KAAK,IAAIC,OACP,CAAC,IAAI,EAAEJ,QAAQ,QAAQ,EAAEA,QAAQ,MAAM,EAAEA,QAAQ,KAAK,EAAEA,QAAQ,QAAQ,CAAC,EACzE;IAEJ;IAEA,OAAOP,QAAQG,QAAQO;AACzB,EAAE"}
|