@metamask/utils 6.1.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.
Files changed (170) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/cjs/assert.js +116 -0
  3. package/dist/cjs/assert.js.map +1 -0
  4. package/dist/cjs/base64.js +32 -0
  5. package/dist/cjs/base64.js.map +1 -0
  6. package/dist/cjs/bytes.js +255 -0
  7. package/dist/cjs/bytes.js.map +1 -0
  8. package/dist/cjs/checksum.js +17 -0
  9. package/dist/cjs/checksum.js.map +1 -0
  10. package/dist/cjs/coercers.js +96 -0
  11. package/dist/cjs/coercers.js.map +1 -0
  12. package/dist/cjs/collections.js +157 -0
  13. package/dist/cjs/collections.js.map +1 -0
  14. package/dist/cjs/encryption-types.js +6 -0
  15. package/dist/cjs/encryption-types.js.map +1 -0
  16. package/dist/cjs/hex.js +107 -0
  17. package/dist/cjs/hex.js.map +1 -0
  18. package/dist/cjs/index.js +36 -0
  19. package/dist/cjs/index.js.map +1 -0
  20. package/dist/cjs/json.js +263 -0
  21. package/dist/cjs/json.js.map +1 -0
  22. package/dist/cjs/keyring.js +6 -0
  23. package/dist/cjs/keyring.js.map +1 -0
  24. package/dist/cjs/logging.js +33 -0
  25. package/dist/cjs/logging.js.map +1 -0
  26. package/dist/cjs/misc.js +111 -0
  27. package/dist/cjs/misc.js.map +1 -0
  28. package/dist/cjs/number.js +52 -0
  29. package/dist/cjs/number.js.map +1 -0
  30. package/dist/cjs/opaque.js +8 -0
  31. package/dist/cjs/opaque.js.map +1 -0
  32. package/dist/cjs/time.js +63 -0
  33. package/dist/cjs/time.js.map +1 -0
  34. package/dist/cjs/transaction-types.js +6 -0
  35. package/dist/cjs/transaction-types.js.map +1 -0
  36. package/dist/cjs/versions.js +79 -0
  37. package/dist/cjs/versions.js.map +1 -0
  38. package/dist/{assert.js → esm/assert.js} +30 -35
  39. package/dist/esm/assert.js.map +1 -0
  40. package/dist/{base64.js → esm/base64.js} +10 -16
  41. package/dist/esm/base64.js.map +1 -0
  42. package/dist/{bytes.js → esm/bytes.js} +50 -93
  43. package/dist/esm/bytes.js.map +1 -0
  44. package/dist/esm/checksum.js +7 -0
  45. package/dist/esm/checksum.js.map +1 -0
  46. package/dist/{coercers.js → esm/coercers.js} +43 -52
  47. package/dist/esm/coercers.js.map +1 -0
  48. package/dist/esm/collections.js +140 -0
  49. package/dist/esm/collections.js.map +1 -0
  50. package/dist/esm/encryption-types.js +3 -0
  51. package/dist/esm/encryption-types.js.map +1 -0
  52. package/dist/esm/hex.js +108 -0
  53. package/dist/esm/hex.js.map +1 -0
  54. package/dist/{index.d.ts → esm/index.js} +2 -0
  55. package/dist/esm/index.js.map +1 -0
  56. package/dist/esm/json.js +301 -0
  57. package/dist/esm/json.js.map +1 -0
  58. package/dist/esm/keyring.js +3 -0
  59. package/dist/esm/keyring.js.map +1 -0
  60. package/dist/{logging.js → esm/logging.js} +5 -14
  61. package/dist/esm/logging.js.map +1 -0
  62. package/dist/{misc.js → esm/misc.js} +37 -42
  63. package/dist/esm/misc.js.map +1 -0
  64. package/dist/{number.js → esm/number.js} +18 -28
  65. package/dist/esm/number.js.map +1 -0
  66. package/dist/esm/opaque.js +5 -0
  67. package/dist/esm/opaque.js.map +1 -0
  68. package/dist/esm/package.json +1 -0
  69. package/dist/esm/time.js +53 -0
  70. package/dist/esm/time.js.map +1 -0
  71. package/dist/esm/transaction-types.js +3 -0
  72. package/dist/esm/transaction-types.js.map +1 -0
  73. package/dist/esm/versions.js +78 -0
  74. package/dist/esm/versions.js.map +1 -0
  75. package/dist/{assert.d.ts → types/assert.d.ts} +3 -2
  76. package/dist/types/assert.d.ts.map +1 -0
  77. package/dist/{base64.d.ts → types/base64.d.ts} +3 -2
  78. package/dist/types/base64.d.ts.map +1 -0
  79. package/dist/{bytes.d.ts → types/bytes.d.ts} +2 -1
  80. package/dist/types/bytes.d.ts.map +1 -0
  81. package/dist/{checksum.d.ts → types/checksum.d.ts} +1 -0
  82. package/dist/types/checksum.d.ts.map +1 -0
  83. package/dist/{coercers.d.ts → types/coercers.d.ts} +3 -2
  84. package/dist/types/coercers.d.ts.map +1 -0
  85. package/dist/{collections.d.ts → types/collections.d.ts} +1 -0
  86. package/dist/types/collections.d.ts.map +1 -0
  87. package/dist/{encryption-types.d.ts → types/encryption-types.d.ts} +1 -0
  88. package/dist/types/encryption-types.d.ts.map +1 -0
  89. package/dist/{hex.d.ts → types/hex.d.ts} +28 -1
  90. package/dist/types/hex.d.ts.map +1 -0
  91. package/dist/types/hex.test-d.d.ts +2 -0
  92. package/dist/types/hex.test-d.d.ts.map +1 -0
  93. package/dist/types/index.d.ts +18 -0
  94. package/dist/types/index.d.ts.map +1 -0
  95. package/dist/{json.d.ts → types/json.d.ts} +3 -2
  96. package/dist/types/json.d.ts.map +1 -0
  97. package/dist/types/json.test-d.d.ts +2 -0
  98. package/dist/types/json.test-d.d.ts.map +1 -0
  99. package/dist/{keyring.d.ts → types/keyring.d.ts} +3 -2
  100. package/dist/types/keyring.d.ts.map +1 -0
  101. package/dist/{logging.d.ts → types/logging.d.ts} +2 -1
  102. package/dist/types/logging.d.ts.map +1 -0
  103. package/dist/{misc.d.ts → types/misc.d.ts} +13 -0
  104. package/dist/types/misc.d.ts.map +1 -0
  105. package/dist/types/misc.test-d.d.ts +2 -0
  106. package/dist/types/misc.test-d.d.ts.map +1 -0
  107. package/dist/{number.d.ts → types/number.d.ts} +1 -0
  108. package/dist/types/number.d.ts.map +1 -0
  109. package/dist/{opaque.d.ts → types/opaque.d.ts} +1 -0
  110. package/dist/types/opaque.d.ts.map +1 -0
  111. package/dist/{time.d.ts → types/time.d.ts} +1 -0
  112. package/dist/types/time.d.ts.map +1 -0
  113. package/dist/{transaction-types.d.ts → types/transaction-types.d.ts} +3 -2
  114. package/dist/types/transaction-types.d.ts.map +1 -0
  115. package/dist/{versions.d.ts → types/versions.d.ts} +3 -2
  116. package/dist/types/versions.d.ts.map +1 -0
  117. package/package.json +41 -20
  118. package/dist/__fixtures__/bytes.d.ts +0 -25
  119. package/dist/__fixtures__/bytes.js +0 -234
  120. package/dist/__fixtures__/bytes.js.map +0 -1
  121. package/dist/__fixtures__/coercions.d.ts +0 -5
  122. package/dist/__fixtures__/coercions.js +0 -22
  123. package/dist/__fixtures__/coercions.js.map +0 -1
  124. package/dist/__fixtures__/index.d.ts +0 -4
  125. package/dist/__fixtures__/index.js +0 -21
  126. package/dist/__fixtures__/index.js.map +0 -1
  127. package/dist/__fixtures__/json.d.ts +0 -1226
  128. package/dist/__fixtures__/json.js +0 -1491
  129. package/dist/__fixtures__/json.js.map +0 -1
  130. package/dist/__fixtures__/numbers.d.ts +0 -5
  131. package/dist/__fixtures__/numbers.js +0 -56
  132. package/dist/__fixtures__/numbers.js.map +0 -1
  133. package/dist/assert.js.map +0 -1
  134. package/dist/base64.js.map +0 -1
  135. package/dist/bytes.js.map +0 -1
  136. package/dist/checksum.js +0 -7
  137. package/dist/checksum.js.map +0 -1
  138. package/dist/coercers.js.map +0 -1
  139. package/dist/collections.js +0 -109
  140. package/dist/collections.js.map +0 -1
  141. package/dist/encryption-types.js +0 -3
  142. package/dist/encryption-types.js.map +0 -1
  143. package/dist/hex.js +0 -81
  144. package/dist/hex.js.map +0 -1
  145. package/dist/hex.test-d.d.ts +0 -1
  146. package/dist/hex.test-d.js +0 -16
  147. package/dist/hex.test-d.js.map +0 -1
  148. package/dist/index.js +0 -34
  149. package/dist/index.js.map +0 -1
  150. package/dist/json.js +0 -346
  151. package/dist/json.js.map +0 -1
  152. package/dist/json.test-d.d.ts +0 -1
  153. package/dist/json.test-d.js +0 -62
  154. package/dist/json.test-d.js.map +0 -1
  155. package/dist/keyring.js +0 -3
  156. package/dist/keyring.js.map +0 -1
  157. package/dist/logging.js.map +0 -1
  158. package/dist/misc.js.map +0 -1
  159. package/dist/misc.test-d.d.ts +0 -1
  160. package/dist/misc.test-d.js +0 -97
  161. package/dist/misc.test-d.js.map +0 -1
  162. package/dist/number.js.map +0 -1
  163. package/dist/opaque.js +0 -3
  164. package/dist/opaque.js.map +0 -1
  165. package/dist/time.js +0 -67
  166. package/dist/time.js.map +0 -1
  167. package/dist/transaction-types.js +0 -3
  168. package/dist/transaction-types.js.map +0 -1
  169. package/dist/versions.js +0 -95
  170. package/dist/versions.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -6,6 +6,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [7.0.0]
10
+ ### Added
11
+ - Add `getKnownPropertyNames` function ([#111](https://github.com/MetaMask/utils/pull/111))
12
+
13
+ ### Changed
14
+ - **BREAKING:** Build the package as both CJS and ESM ([#115](https://github.com/MetaMask/utils/pull/115), [#124](https://github.com/MetaMask/utils/pull/124))
15
+ - It's no longer possible to import from the `dist` folder. Everything must be imported from `@metamask/utils`.
16
+ - Bump `semver` to `^7.5.4` ([#123](https://github.com/MetaMask/utils/pull/123))
17
+
18
+ ## [6.2.0]
19
+ ### Added
20
+ - Add address related utils ([#112](https://github.com/MetaMask/utils/pull/112))
21
+ - `isValidHexAddress` has been added to check the validity of an hex address
22
+ - `getChecksumAddress` has been added to calculate the ERC-55 mixed-case checksum of an hex address
23
+ - `isValidChecksumAddress` has been added to check the validity of an ERC-55 mixed-case checksum address
24
+
9
25
  ## [6.1.0]
10
26
  ### Added
11
27
  - Add optional `destroy` method to `Keyring` type ([#108](https://github.com/MetaMask/utils/pull/108))
@@ -158,7 +174,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
158
174
  ### Added
159
175
  - Initial release
160
176
 
161
- [Unreleased]: https://github.com/MetaMask/utils/compare/v6.1.0...HEAD
177
+ [Unreleased]: https://github.com/MetaMask/utils/compare/v7.0.0...HEAD
178
+ [7.0.0]: https://github.com/MetaMask/utils/compare/v6.2.0...v7.0.0
179
+ [6.2.0]: https://github.com/MetaMask/utils/compare/v6.1.0...v6.2.0
162
180
  [6.1.0]: https://github.com/MetaMask/utils/compare/v6.0.1...v6.1.0
163
181
  [6.0.1]: https://github.com/MetaMask/utils/compare/v6.0.0...v6.0.1
164
182
  [6.0.0]: https://github.com/MetaMask/utils/compare/v5.0.2...v6.0.0
@@ -0,0 +1,116 @@
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
+ AssertionError: function() {
13
+ return AssertionError;
14
+ },
15
+ assert: function() {
16
+ return assert;
17
+ },
18
+ assertStruct: function() {
19
+ return assertStruct;
20
+ },
21
+ assertExhaustive: function() {
22
+ return assertExhaustive;
23
+ }
24
+ });
25
+ const _superstruct = require("superstruct");
26
+ function _define_property(obj, key, value) {
27
+ if (key in obj) {
28
+ Object.defineProperty(obj, key, {
29
+ value: value,
30
+ enumerable: true,
31
+ configurable: true,
32
+ writable: true
33
+ });
34
+ } else {
35
+ obj[key] = value;
36
+ }
37
+ return obj;
38
+ }
39
+ /**
40
+ * Type guard for determining whether the given value is an error object with a
41
+ * `message` property, such as an instance of Error.
42
+ *
43
+ * @param error - The object to check.
44
+ * @returns True or false, depending on the result.
45
+ */ function isErrorWithMessage(error) {
46
+ return typeof error === 'object' && error !== null && 'message' in error;
47
+ }
48
+ /**
49
+ * Check if a value is a constructor, i.e., a function that can be called with
50
+ * the `new` keyword.
51
+ *
52
+ * @param fn - The value to check.
53
+ * @returns `true` if the value is a constructor, or `false` otherwise.
54
+ */ function isConstructable(fn) {
55
+ /* istanbul ignore next */ return Boolean(typeof fn?.prototype?.constructor?.name === 'string');
56
+ }
57
+ /**
58
+ * Get the error message from an unknown error object. If the error object has
59
+ * a `message` property, that property is returned. Otherwise, the stringified
60
+ * error object is returned.
61
+ *
62
+ * @param error - The error object to get the message from.
63
+ * @returns The error message.
64
+ */ function getErrorMessage(error) {
65
+ const message = isErrorWithMessage(error) ? error.message : String(error);
66
+ // If the error ends with a period, remove it, as we'll add our own period.
67
+ if (message.endsWith('.')) {
68
+ return message.slice(0, -1);
69
+ }
70
+ return message;
71
+ }
72
+ /**
73
+ * Initialise an {@link AssertionErrorConstructor} error.
74
+ *
75
+ * @param ErrorWrapper - The error class to use.
76
+ * @param message - The error message.
77
+ * @returns The error object.
78
+ */ // eslint-disable-next-line @typescript-eslint/naming-convention
79
+ function getError(ErrorWrapper, message) {
80
+ if (isConstructable(ErrorWrapper)) {
81
+ return new ErrorWrapper({
82
+ message
83
+ });
84
+ }
85
+ return ErrorWrapper({
86
+ message
87
+ });
88
+ }
89
+ class AssertionError extends Error {
90
+ constructor(options){
91
+ super(options.message);
92
+ _define_property(this, "code", 'ERR_ASSERTION');
93
+ }
94
+ }
95
+ function assert(value, message = 'Assertion failed.', // eslint-disable-next-line @typescript-eslint/naming-convention
96
+ ErrorWrapper = AssertionError) {
97
+ if (!value) {
98
+ if (message instanceof Error) {
99
+ throw message;
100
+ }
101
+ throw getError(ErrorWrapper, message);
102
+ }
103
+ }
104
+ function assertStruct(value, struct, errorPrefix = 'Assertion failed', // eslint-disable-next-line @typescript-eslint/naming-convention
105
+ ErrorWrapper = AssertionError) {
106
+ try {
107
+ (0, _superstruct.assert)(value, struct);
108
+ } catch (error) {
109
+ throw getError(ErrorWrapper, `${errorPrefix}: ${getErrorMessage(error)}.`);
110
+ }
111
+ }
112
+ function assertExhaustive(_object) {
113
+ throw new Error('Invalid branch reached. Should be detected during compilation.');
114
+ }
115
+
116
+ //# 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":["AssertionError","assert","assertStruct","assertExhaustive","isErrorWithMessage","error","isConstructable","fn","Boolean","prototype","constructor","name","getErrorMessage","message","String","endsWith","slice","getError","ErrorWrapper","Error","options","code","value","struct","errorPrefix","assertSuperstruct","_object"],"mappings":";;;;;;;;;;;IAyEaA,cAAc;eAAdA;;IAoBGC,MAAM;eAANA;;IA0BAC,YAAY;eAAZA;;IAiCAC,gBAAgB;eAAhBA;;;6BAvJ4B;;;;;;;;;;;;;;AAM5C;;;;;;CAMC,GACD,SAASC,mBAAmBC,KAAc;IACxC,OAAO,OAAOA,UAAU,YAAYA,UAAU,QA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use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "base64", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return base64;
9
+ }
10
+ });
11
+ const _superstruct = require("superstruct");
12
+ const _assert = require("./assert");
13
+ const base64 = (struct, options = {})=>{
14
+ const paddingRequired = options.paddingRequired ?? false;
15
+ const characterSet = options.characterSet ?? 'base64';
16
+ let letters;
17
+ if (characterSet === 'base64') {
18
+ letters = String.raw`[A-Za-z0-9+\/]`;
19
+ } else {
20
+ (0, _assert.assert)(characterSet === 'base64url');
21
+ letters = String.raw`[-_A-Za-z0-9]`;
22
+ }
23
+ let re;
24
+ if (paddingRequired) {
25
+ re = new RegExp(`^(?:${letters}{4})*(?:${letters}{3}=|${letters}{2}==)?$`, 'u');
26
+ } else {
27
+ re = new RegExp(`^(?:${letters}{4})*(?:${letters}{2,3}|${letters}{3}=|${letters}{2}==)?$`, 'u');
28
+ }
29
+ return (0, _superstruct.pattern)(struct, re);
30
+ };
31
+
32
+ //# 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":["base64","struct","options","paddingRequired","characterSet","letters","String","raw","assert","re","RegExp","pattern"],"mappings":";;;;+BA6BaA;;;eAAAA;;;6BA5BW;wBAED;AA0BhB,MAAMA,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;QACLC,IAAAA,cAAM,EAACJ,iBAAiB;QACxBC,UAAUC,OAAOC,GAAG,CAAC,aAAa,CAAC;IACrC;IAEA,IAAIE;IACJ,IAAIN,iBAAiB;QACnBM,KAAK,IAAIC,OACP,CAAC,IAAI,EAAEL,QAAQ,QAAQ,EAAEA,QAAQ,KAAK,EAAEA,QAAQ,QAAQ,CAAC,EACzD;IAEJ,OAAO;QACLI,KAAK,IAAIC,OACP,CAAC,IAAI,EAAEL,QAAQ,QAAQ,EAAEA,QAAQ,MAAM,EAAEA,QAAQ,KAAK,EAAEA,QAAQ,QAAQ,CAAC,EACzE;IAEJ;IAEA,OAAOM,IAAAA,oBAAO,EAACV,QAAQQ;AACzB"}
@@ -0,0 +1,255 @@
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
+ isBytes: function() {
13
+ return isBytes;
14
+ },
15
+ assertIsBytes: function() {
16
+ return assertIsBytes;
17
+ },
18
+ bytesToHex: function() {
19
+ return bytesToHex;
20
+ },
21
+ bytesToBigInt: function() {
22
+ return bytesToBigInt;
23
+ },
24
+ bytesToSignedBigInt: function() {
25
+ return bytesToSignedBigInt;
26
+ },
27
+ bytesToNumber: function() {
28
+ return bytesToNumber;
29
+ },
30
+ bytesToString: function() {
31
+ return bytesToString;
32
+ },
33
+ hexToBytes: function() {
34
+ return hexToBytes;
35
+ },
36
+ bigIntToBytes: function() {
37
+ return bigIntToBytes;
38
+ },
39
+ signedBigIntToBytes: function() {
40
+ return signedBigIntToBytes;
41
+ },
42
+ numberToBytes: function() {
43
+ return numberToBytes;
44
+ },
45
+ stringToBytes: function() {
46
+ return stringToBytes;
47
+ },
48
+ valueToBytes: function() {
49
+ return valueToBytes;
50
+ },
51
+ concatBytes: function() {
52
+ return concatBytes;
53
+ },
54
+ createDataView: function() {
55
+ return createDataView;
56
+ }
57
+ });
58
+ const _assert = require("./assert");
59
+ const _hex = require("./hex");
60
+ // '0'.charCodeAt(0) === 48
61
+ const HEX_MINIMUM_NUMBER_CHARACTER = 48;
62
+ // '9'.charCodeAt(0) === 57
63
+ const HEX_MAXIMUM_NUMBER_CHARACTER = 58;
64
+ const HEX_CHARACTER_OFFSET = 87;
65
+ /**
66
+ * Memoized function that returns an array to be used as a lookup table for
67
+ * converting bytes to hexadecimal values.
68
+ *
69
+ * The array is created lazily and then cached for future use. The benefit of
70
+ * this approach is that the performance of converting bytes to hex is much
71
+ * better than if we were to call `toString(16)` on each byte.
72
+ *
73
+ * The downside is that the array is created once and then never garbage
74
+ * collected. This is not a problem in practice because the array is only 256
75
+ * elements long.
76
+ *
77
+ * @returns A function that returns the lookup table.
78
+ */ function getPrecomputedHexValuesBuilder() {
79
+ // To avoid issues with tree shaking, we need to use a function to return the
80
+ // array. This is because the array is only used in the `bytesToHex` function
81
+ // and if we were to use a global variable, the array might be removed by the
82
+ // tree shaker.
83
+ const lookupTable = [];
84
+ return ()=>{
85
+ if (lookupTable.length === 0) {
86
+ for(let i = 0; i < 256; i++){
87
+ lookupTable.push(i.toString(16).padStart(2, '0'));
88
+ }
89
+ }
90
+ return lookupTable;
91
+ };
92
+ }
93
+ /**
94
+ * Function implementation of the {@link getPrecomputedHexValuesBuilder}
95
+ * function.
96
+ */ const getPrecomputedHexValues = getPrecomputedHexValuesBuilder();
97
+ function isBytes(value) {
98
+ return value instanceof Uint8Array;
99
+ }
100
+ function assertIsBytes(value) {
101
+ (0, _assert.assert)(isBytes(value), 'Value must be a Uint8Array.');
102
+ }
103
+ function bytesToHex(bytes) {
104
+ assertIsBytes(bytes);
105
+ if (bytes.length === 0) {
106
+ return '0x';
107
+ }
108
+ const lookupTable = getPrecomputedHexValues();
109
+ const hexadecimal = new Array(bytes.length);
110
+ for(let i = 0; i < bytes.length; i++){
111
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
112
+ hexadecimal[i] = lookupTable[bytes[i]];
113
+ }
114
+ return (0, _hex.add0x)(hexadecimal.join(''));
115
+ }
116
+ function bytesToBigInt(bytes) {
117
+ assertIsBytes(bytes);
118
+ const hexadecimal = bytesToHex(bytes);
119
+ return BigInt(hexadecimal);
120
+ }
121
+ function bytesToSignedBigInt(bytes) {
122
+ assertIsBytes(bytes);
123
+ let value = BigInt(0);
124
+ for (const byte of bytes){
125
+ // eslint-disable-next-line no-bitwise
126
+ value = (value << BigInt(8)) + BigInt(byte);
127
+ }
128
+ return BigInt.asIntN(bytes.length * 8, value);
129
+ }
130
+ function bytesToNumber(bytes) {
131
+ assertIsBytes(bytes);
132
+ const bigint = bytesToBigInt(bytes);
133
+ (0, _assert.assert)(bigint <= BigInt(Number.MAX_SAFE_INTEGER), 'Number is not a safe integer. Use `bytesToBigInt` instead.');
134
+ return Number(bigint);
135
+ }
136
+ function bytesToString(bytes) {
137
+ assertIsBytes(bytes);
138
+ return new TextDecoder().decode(bytes);
139
+ }
140
+ function hexToBytes(value) {
141
+ // "0x" is often used as empty byte array.
142
+ if (value?.toLowerCase?.() === '0x') {
143
+ return new Uint8Array();
144
+ }
145
+ (0, _hex.assertIsHexString)(value);
146
+ // Remove the `0x` prefix if it exists, and pad the string to have an even
147
+ // number of characters.
148
+ const strippedValue = (0, _hex.remove0x)(value).toLowerCase();
149
+ const normalizedValue = strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;
150
+ const bytes = new Uint8Array(normalizedValue.length / 2);
151
+ for(let i = 0; i < bytes.length; i++){
152
+ // While this is not the prettiest way to convert a hexadecimal string to a
153
+ // `Uint8Array`, it is a lot faster than using `parseInt` to convert each
154
+ // character.
155
+ const c1 = normalizedValue.charCodeAt(i * 2);
156
+ const c2 = normalizedValue.charCodeAt(i * 2 + 1);
157
+ const n1 = c1 - (c1 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET);
158
+ const n2 = c2 - (c2 < HEX_MAXIMUM_NUMBER_CHARACTER ? HEX_MINIMUM_NUMBER_CHARACTER : HEX_CHARACTER_OFFSET);
159
+ bytes[i] = n1 * 16 + n2;
160
+ }
161
+ return bytes;
162
+ }
163
+ function bigIntToBytes(value) {
164
+ (0, _assert.assert)(typeof value === 'bigint', 'Value must be a bigint.');
165
+ (0, _assert.assert)(value >= BigInt(0), 'Value must be a non-negative bigint.');
166
+ const hexadecimal = value.toString(16);
167
+ return hexToBytes(hexadecimal);
168
+ }
169
+ /**
170
+ * Check if a `bigint` fits in a certain number of bytes.
171
+ *
172
+ * @param value - The `bigint` to check.
173
+ * @param bytes - The number of bytes.
174
+ * @returns Whether the `bigint` fits in the number of bytes.
175
+ */ function bigIntFits(value, bytes) {
176
+ (0, _assert.assert)(bytes > 0);
177
+ /* eslint-disable no-bitwise */ const mask = value >> BigInt(31);
178
+ return !((~value & mask) + (value & ~mask) >> BigInt(bytes * 8 + ~0));
179
+ /* eslint-enable no-bitwise */ }
180
+ function signedBigIntToBytes(value, byteLength) {
181
+ (0, _assert.assert)(typeof value === 'bigint', 'Value must be a bigint.');
182
+ (0, _assert.assert)(typeof byteLength === 'number', 'Byte length must be a number.');
183
+ (0, _assert.assert)(byteLength > 0, 'Byte length must be greater than 0.');
184
+ (0, _assert.assert)(bigIntFits(value, byteLength), 'Byte length is too small to represent the given value.');
185
+ // ESLint doesn't like mutating function parameters, so to avoid having to
186
+ // disable the rule, we create a new variable.
187
+ let numberValue = value;
188
+ const bytes = new Uint8Array(byteLength);
189
+ for(let i = 0; i < bytes.length; i++){
190
+ bytes[i] = Number(BigInt.asUintN(8, numberValue));
191
+ // eslint-disable-next-line no-bitwise
192
+ numberValue >>= BigInt(8);
193
+ }
194
+ return bytes.reverse();
195
+ }
196
+ function numberToBytes(value) {
197
+ (0, _assert.assert)(typeof value === 'number', 'Value must be a number.');
198
+ (0, _assert.assert)(value >= 0, 'Value must be a non-negative number.');
199
+ (0, _assert.assert)(Number.isSafeInteger(value), 'Value is not a safe integer. Use `bigIntToBytes` instead.');
200
+ const hexadecimal = value.toString(16);
201
+ return hexToBytes(hexadecimal);
202
+ }
203
+ function stringToBytes(value) {
204
+ (0, _assert.assert)(typeof value === 'string', 'Value must be a string.');
205
+ return new TextEncoder().encode(value);
206
+ }
207
+ function valueToBytes(value) {
208
+ if (typeof value === 'bigint') {
209
+ return bigIntToBytes(value);
210
+ }
211
+ if (typeof value === 'number') {
212
+ return numberToBytes(value);
213
+ }
214
+ if (typeof value === 'string') {
215
+ if (value.startsWith('0x')) {
216
+ return hexToBytes(value);
217
+ }
218
+ return stringToBytes(value);
219
+ }
220
+ if (isBytes(value)) {
221
+ return value;
222
+ }
223
+ throw new TypeError(`Unsupported value type: "${typeof value}".`);
224
+ }
225
+ function concatBytes(values) {
226
+ const normalizedValues = new Array(values.length);
227
+ let byteLength = 0;
228
+ for(let i = 0; i < values.length; i++){
229
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
230
+ const value = valueToBytes(values[i]);
231
+ normalizedValues[i] = value;
232
+ byteLength += value.length;
233
+ }
234
+ const bytes = new Uint8Array(byteLength);
235
+ for(let i = 0, offset = 0; i < normalizedValues.length; i++){
236
+ // While we could simply spread the values into an array and use
237
+ // `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`.
238
+ bytes.set(normalizedValues[i], offset);
239
+ offset += normalizedValues[i].length;
240
+ }
241
+ return bytes;
242
+ }
243
+ function createDataView(bytes) {
244
+ // To maintain compatibility with Node.js, we need to check if the bytes are
245
+ // a Buffer. If so, we need to slice the buffer to get the underlying
246
+ // ArrayBuffer.
247
+ // eslint-disable-next-line no-restricted-globals
248
+ if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {
249
+ const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
250
+ return new DataView(buffer);
251
+ }
252
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
253
+ }
254
+
255
+ //# sourceMappingURL=bytes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/bytes.ts"],"sourcesContent":["import { assert } from './assert';\nimport type { Hex } from './hex';\nimport { add0x, assertIsHexString, remove0x } from './hex';\n\n// '0'.charCodeAt(0) === 48\nconst HEX_MINIMUM_NUMBER_CHARACTER = 48;\n\n// '9'.charCodeAt(0) === 57\nconst HEX_MAXIMUM_NUMBER_CHARACTER = 58;\nconst HEX_CHARACTER_OFFSET = 87;\n\nexport type Bytes = bigint | number | string | Uint8Array;\n\n/**\n * Memoized function that returns an array to be used as a lookup table for\n * converting bytes to hexadecimal values.\n *\n * The array is created lazily and then cached for future use. The benefit of\n * this approach is that the performance of converting bytes to hex is much\n * better than if we were to call `toString(16)` on each byte.\n *\n * The downside is that the array is created once and then never garbage\n * collected. This is not a problem in practice because the array is only 256\n * elements long.\n *\n * @returns A function that returns the lookup table.\n */\nfunction getPrecomputedHexValuesBuilder(): () => string[] {\n // To avoid issues with tree shaking, we need to use a function to return the\n // array. This is because the array is only used in the `bytesToHex` function\n // and if we were to use a global variable, the array might be removed by the\n // tree shaker.\n const lookupTable: string[] = [];\n\n return () => {\n if (lookupTable.length === 0) {\n for (let i = 0; i < 256; i++) {\n lookupTable.push(i.toString(16).padStart(2, '0'));\n }\n }\n\n return lookupTable;\n };\n}\n\n/**\n * Function implementation of the {@link getPrecomputedHexValuesBuilder}\n * function.\n */\nconst getPrecomputedHexValues = getPrecomputedHexValuesBuilder();\n\n/**\n * Check if a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @returns Whether the value is a `Uint8Array`.\n */\nexport function isBytes(value: unknown): value is Uint8Array {\n return value instanceof Uint8Array;\n}\n\n/**\n * Assert that a value is a `Uint8Array`.\n *\n * @param value - The value to check.\n * @throws If the value is not a `Uint8Array`.\n */\nexport function assertIsBytes(value: unknown): asserts value is Uint8Array {\n assert(isBytes(value), 'Value must be a Uint8Array.');\n}\n\n/**\n * Convert a `Uint8Array` to a hexadecimal string.\n *\n * @param bytes - The bytes to convert to a hexadecimal string.\n * @returns The hexadecimal string.\n */\nexport function bytesToHex(bytes: Uint8Array): Hex {\n assertIsBytes(bytes);\n\n if (bytes.length === 0) {\n return '0x';\n }\n\n const lookupTable = getPrecomputedHexValues();\n const hexadecimal = new Array(bytes.length);\n\n for (let i = 0; i < bytes.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n hexadecimal[i] = lookupTable[bytes[i]!];\n }\n\n return add0x(hexadecimal.join(''));\n}\n\n/**\n * Convert a `Uint8Array` to a `bigint`.\n *\n * To convert a `Uint8Array` to a `number` instead, use {@link bytesToNumber}.\n * To convert a two's complement encoded `Uint8Array` to a `bigint`, use\n * {@link bytesToSignedBigInt}.\n *\n * @param bytes - The bytes to convert to a `bigint`.\n * @returns The `bigint`.\n */\nexport function bytesToBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n const hexadecimal = bytesToHex(bytes);\n return BigInt(hexadecimal);\n}\n\n/**\n * Convert a `Uint8Array` to a signed `bigint`. This assumes that the bytes are\n * encoded in two's complement.\n *\n * To convert a `Uint8Array` to an unsigned `bigint` instead, use\n * {@link bytesToBigInt}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param bytes - The bytes to convert to a signed `bigint`.\n * @returns The signed `bigint`.\n */\nexport function bytesToSignedBigInt(bytes: Uint8Array): bigint {\n assertIsBytes(bytes);\n\n let value = BigInt(0);\n for (const byte of bytes) {\n // eslint-disable-next-line no-bitwise\n value = (value << BigInt(8)) + BigInt(byte);\n }\n\n return BigInt.asIntN(bytes.length * 8, value);\n}\n\n/**\n * Convert a `Uint8Array` to a `number`.\n *\n * To convert a `Uint8Array` to a `bigint` instead, use {@link bytesToBigInt}.\n *\n * @param bytes - The bytes to convert to a number.\n * @returns The number.\n * @throws If the resulting number is not a safe integer.\n */\nexport function bytesToNumber(bytes: Uint8Array): number {\n assertIsBytes(bytes);\n\n const bigint = bytesToBigInt(bytes);\n\n assert(\n bigint <= BigInt(Number.MAX_SAFE_INTEGER),\n 'Number is not a safe integer. Use `bytesToBigInt` instead.',\n );\n\n return Number(bigint);\n}\n\n/**\n * Convert a UTF-8 encoded `Uint8Array` to a `string`.\n *\n * @param bytes - The bytes to convert to a string.\n * @returns The string.\n */\nexport function bytesToString(bytes: Uint8Array): string {\n assertIsBytes(bytes);\n\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Convert a hexadecimal string to a `Uint8Array`. The string can optionally be\n * prefixed with `0x`. It accepts even and odd length strings.\n *\n * If the value is \"0x\", an empty `Uint8Array` is returned.\n *\n * @param value - The hexadecimal string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function hexToBytes(value: string): Uint8Array {\n // \"0x\" is often used as empty byte array.\n if (value?.toLowerCase?.() === '0x') {\n return new Uint8Array();\n }\n\n assertIsHexString(value);\n\n // Remove the `0x` prefix if it exists, and pad the string to have an even\n // number of characters.\n const strippedValue = remove0x(value).toLowerCase();\n const normalizedValue =\n strippedValue.length % 2 === 0 ? strippedValue : `0${strippedValue}`;\n const bytes = new Uint8Array(normalizedValue.length / 2);\n\n for (let i = 0; i < bytes.length; i++) {\n // While this is not the prettiest way to convert a hexadecimal string to a\n // `Uint8Array`, it is a lot faster than using `parseInt` to convert each\n // character.\n const c1 = normalizedValue.charCodeAt(i * 2);\n const c2 = normalizedValue.charCodeAt(i * 2 + 1);\n const n1 =\n c1 -\n (c1 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n const n2 =\n c2 -\n (c2 < HEX_MAXIMUM_NUMBER_CHARACTER\n ? HEX_MINIMUM_NUMBER_CHARACTER\n : HEX_CHARACTER_OFFSET);\n\n bytes[i] = n1 * 16 + n2;\n }\n\n return bytes;\n}\n\n/**\n * Convert a `bigint` to a `Uint8Array`.\n *\n * This assumes that the `bigint` is an unsigned integer. To convert a signed\n * `bigint` instead, use {@link signedBigIntToBytes}.\n *\n * @param value - The bigint to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function bigIntToBytes(value: bigint): Uint8Array {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(value >= BigInt(0), 'Value must be a non-negative bigint.');\n\n const hexadecimal = value.toString(16);\n return hexToBytes(hexadecimal);\n}\n\n/**\n * Check if a `bigint` fits in a certain number of bytes.\n *\n * @param value - The `bigint` to check.\n * @param bytes - The number of bytes.\n * @returns Whether the `bigint` fits in the number of bytes.\n */\nfunction bigIntFits(value: bigint, bytes: number): boolean {\n assert(bytes > 0);\n\n /* eslint-disable no-bitwise */\n const mask = value >> BigInt(31);\n return !(((~value & mask) + (value & ~mask)) >> BigInt(bytes * 8 + ~0));\n /* eslint-enable no-bitwise */\n}\n\n/**\n * Convert a signed `bigint` to a `Uint8Array`. This uses two's complement\n * encoding to represent negative numbers.\n *\n * To convert an unsigned `bigint` to a `Uint8Array` instead, use\n * {@link bigIntToBytes}.\n *\n * @see https://en.wikipedia.org/wiki/Two%27s_complement\n * @param value - The number to convert to bytes.\n * @param byteLength - The length of the resulting `Uint8Array`. If the number\n * is larger than the maximum value that can be represented by the given length,\n * an error is thrown.\n * @returns The bytes as `Uint8Array`.\n */\nexport function signedBigIntToBytes(\n value: bigint,\n byteLength: number,\n): Uint8Array {\n assert(typeof value === 'bigint', 'Value must be a bigint.');\n assert(typeof byteLength === 'number', 'Byte length must be a number.');\n assert(byteLength > 0, 'Byte length must be greater than 0.');\n assert(\n bigIntFits(value, byteLength),\n 'Byte length is too small to represent the given value.',\n );\n\n // ESLint doesn't like mutating function parameters, so to avoid having to\n // disable the rule, we create a new variable.\n let numberValue = value;\n const bytes = new Uint8Array(byteLength);\n\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number(BigInt.asUintN(8, numberValue));\n // eslint-disable-next-line no-bitwise\n numberValue >>= BigInt(8);\n }\n\n return bytes.reverse();\n}\n\n/**\n * Convert a `number` to a `Uint8Array`.\n *\n * @param value - The number to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n * @throws If the number is not a safe integer.\n */\nexport function numberToBytes(value: number): Uint8Array {\n assert(typeof value === 'number', 'Value must be a number.');\n assert(value >= 0, 'Value must be a non-negative number.');\n assert(\n Number.isSafeInteger(value),\n 'Value is not a safe integer. Use `bigIntToBytes` instead.',\n );\n\n const hexadecimal = value.toString(16);\n return hexToBytes(hexadecimal);\n}\n\n/**\n * Convert a `string` to a UTF-8 encoded `Uint8Array`.\n *\n * @param value - The string to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function stringToBytes(value: string): Uint8Array {\n assert(typeof value === 'string', 'Value must be a string.');\n\n return new TextEncoder().encode(value);\n}\n\n/**\n * Convert a byte-like value to a `Uint8Array`. The value can be a `Uint8Array`,\n * a `bigint`, a `number`, or a `string`.\n *\n * This will attempt to guess the type of the value based on its type and\n * contents. For more control over the conversion, use the more specific\n * conversion functions, such as {@link hexToBytes} or {@link stringToBytes}.\n *\n * If the value is a `string`, and it is prefixed with `0x`, it will be\n * interpreted as a hexadecimal string. Otherwise, it will be interpreted as a\n * UTF-8 string. To convert a hexadecimal string to bytes without interpreting\n * it as a UTF-8 string, use {@link hexToBytes} instead.\n *\n * If the value is a `bigint`, it is assumed to be unsigned. To convert a signed\n * `bigint` to bytes, use {@link signedBigIntToBytes} instead.\n *\n * If the value is a `Uint8Array`, it will be returned as-is.\n *\n * @param value - The value to convert to bytes.\n * @returns The bytes as `Uint8Array`.\n */\nexport function valueToBytes(value: Bytes): Uint8Array {\n if (typeof value === 'bigint') {\n return bigIntToBytes(value);\n }\n\n if (typeof value === 'number') {\n return numberToBytes(value);\n }\n\n if (typeof value === 'string') {\n if (value.startsWith('0x')) {\n return hexToBytes(value);\n }\n\n return stringToBytes(value);\n }\n\n if (isBytes(value)) {\n return value;\n }\n\n throw new TypeError(`Unsupported value type: \"${typeof value}\".`);\n}\n\n/**\n * Concatenate multiple byte-like values into a single `Uint8Array`. The values\n * can be `Uint8Array`, `bigint`, `number`, or `string`. This uses\n * {@link valueToBytes} under the hood to convert each value to bytes. Refer to\n * the documentation of that function for more information.\n *\n * @param values - The values to concatenate.\n * @returns The concatenated bytes as `Uint8Array`.\n */\nexport function concatBytes(values: Bytes[]): Uint8Array {\n const normalizedValues = new Array(values.length);\n let byteLength = 0;\n\n for (let i = 0; i < values.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const value = valueToBytes(values[i]!);\n\n normalizedValues[i] = value;\n byteLength += value.length;\n }\n\n const bytes = new Uint8Array(byteLength);\n for (let i = 0, offset = 0; i < normalizedValues.length; i++) {\n // While we could simply spread the values into an array and use\n // `Uint8Array.from`, that is a lot slower than using `Uint8Array.set`.\n bytes.set(normalizedValues[i], offset);\n offset += normalizedValues[i].length;\n }\n\n return bytes;\n}\n\n/**\n * Create a {@link DataView} from a {@link Uint8Array}. This is a convenience\n * function that avoids having to create a {@link DataView} manually, which\n * requires passing the `byteOffset` and `byteLength` parameters every time.\n *\n * Not passing the `byteOffset` and `byteLength` parameters can result in\n * unexpected behavior when the {@link Uint8Array} is a view of a larger\n * {@link ArrayBuffer}, e.g., when using {@link Uint8Array.subarray}.\n *\n * This function also supports Node.js {@link Buffer}s.\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([1, 2, 3]);\n *\n * // This is equivalent to:\n * // const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n * const dataView = createDataView(bytes);\n * ```\n * @param bytes - The bytes to create the {@link DataView} from.\n * @returns The {@link DataView}.\n */\nexport function createDataView(bytes: Uint8Array): DataView {\n // To maintain compatibility with Node.js, we need to check if the bytes are\n // a Buffer. If so, we need to slice the buffer to get the underlying\n // ArrayBuffer.\n // eslint-disable-next-line no-restricted-globals\n if (typeof Buffer !== 'undefined' && bytes instanceof Buffer) {\n const buffer = bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n );\n\n return new DataView(buffer);\n }\n\n return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n}\n"],"names":["isBytes","assertIsBytes","bytesToHex","bytesToBigInt","bytesToSignedBigInt","bytesToNumber","bytesToString","hexToBytes","bigIntToBytes","signedBigIntToBytes","numberToBytes","stringToBytes","valueToBytes","concatBytes","createDataView","HEX_MINIMUM_NUMBER_CHARACTER","HEX_MAXIMUM_NUMBER_CHARACTER","HEX_CHARACTER_OFFSET","getPrecomputedHexValuesBuilder","lookupTable","length","i","push","toString","padStart","getPrecomputedHexValues","value","Uint8Array","assert","bytes","hexadecimal","Array","add0x","join","BigInt","byte","asIntN","bigint","Number","MAX_SAFE_INTEGER","TextDecoder","decode","toLowerCase","assertIsHexString","strippedValue","remove0x","normalizedValue","c1","charCodeAt","c2","n1","n2","bigIntFits","mask","byteLength","numberValue","asUintN","reverse","isSafeInteger","TextEncoder","encode","startsWith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4B,cAAc5B,MAAMN,MAAM;IAC5B;IAEA,MAAMS,QAAQ,IAAIF,WAAW2B;IAC7B,IAAK,IAAIjC,IAAI,GAAG4C,SAAS,GAAG5C,IAAI2C,iBAAiB5C,MAAM,EAAEC,IAAK;QAC5D,gEAAgE;QAChE,uEAAuE;QACvEQ,MAAMqC,GAAG,CAACF,gBAAgB,CAAC3C,EAAE,EAAE4C;QAC/BA,UAAUD,gBAAgB,CAAC3C,EAAE,CAACD,MAAM;IACtC;IAEA,OAAOS;AACT;AAwBO,SAASf,eAAee,KAAiB;IAC9C,4EAA4E;IAC5E,qEAAqE;IACrE,eAAe;IACf,iDAAiD;IACjD,IAAI,OAAOsC,WAAW,eAAetC,iBAAiBsC,QAAQ;QAC5D,MAAMC,SAASvC,MAAMuC,MAAM,CAACC,KAAK,CAC/BxC,MAAMyC,UAAU,EAChBzC,MAAMyC,UAAU,GAAGzC,MAAMyB,UAAU;QAGrC,OAAO,IAAIiB,SAASH;IACtB;IAEA,OAAO,IAAIG,SAAS1C,MAAMuC,MAAM,EAAEvC,MAAMyC,UAAU,EAAEzC,MAAMyB,UAAU;AACtE"}
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "ChecksumStruct", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return ChecksumStruct;
9
+ }
10
+ });
11
+ const _superstruct = require("superstruct");
12
+ const _base64 = require("./base64");
13
+ const ChecksumStruct = (0, _superstruct.size)((0, _base64.base64)((0, _superstruct.string)(), {
14
+ paddingRequired: true
15
+ }), 44, 44);
16
+
17
+ //# sourceMappingURL=checksum.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { size, string } from 'superstruct';\n\nimport { base64 } from './base64';\n\nexport const ChecksumStruct = size(\n base64(string(), { paddingRequired: true }),\n 44,\n 44,\n);\n"],"names":["ChecksumStruct","size","base64","string","paddingRequired"],"mappings":";;;;+BAIaA;;;eAAAA;;;6BAJgB;wBAEN;AAEhB,MAAMA,iBAAiBC,IAAAA,iBAAI,EAChCC,IAAAA,cAAM,EAACC,IAAAA,mBAAM,KAAI;IAAEC,iBAAiB;AAAK,IACzC,IACA"}
@@ -0,0 +1,96 @@
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
+ createNumber: function() {
13
+ return createNumber;
14
+ },
15
+ createBigInt: function() {
16
+ return createBigInt;
17
+ },
18
+ createBytes: function() {
19
+ return createBytes;
20
+ },
21
+ createHex: function() {
22
+ return createHex;
23
+ }
24
+ });
25
+ const _superstruct = require("superstruct");
26
+ const _assert = require("./assert");
27
+ const _bytes = require("./bytes");
28
+ const _hex = require("./hex");
29
+ const NumberLikeStruct = (0, _superstruct.union)([
30
+ (0, _superstruct.number)(),
31
+ (0, _superstruct.bigint)(),
32
+ (0, _superstruct.string)(),
33
+ _hex.StrictHexStruct
34
+ ]);
35
+ const NumberCoercer = (0, _superstruct.coerce)((0, _superstruct.number)(), NumberLikeStruct, Number);
36
+ const BigIntCoercer = (0, _superstruct.coerce)((0, _superstruct.bigint)(), NumberLikeStruct, BigInt);
37
+ const BytesLikeStruct = (0, _superstruct.union)([
38
+ _hex.StrictHexStruct,
39
+ (0, _superstruct.instance)(Uint8Array)
40
+ ]);
41
+ const BytesCoercer = (0, _superstruct.coerce)((0, _superstruct.instance)(Uint8Array), (0, _superstruct.union)([
42
+ _hex.StrictHexStruct
43
+ ]), _bytes.hexToBytes);
44
+ const HexCoercer = (0, _superstruct.coerce)(_hex.StrictHexStruct, (0, _superstruct.instance)(Uint8Array), _bytes.bytesToHex);
45
+ function createNumber(value) {
46
+ try {
47
+ const result = (0, _superstruct.create)(value, NumberCoercer);
48
+ (0, _assert.assert)(Number.isFinite(result), `Expected a number-like value, got "${value}".`);
49
+ return result;
50
+ } catch (error) {
51
+ if (error instanceof _superstruct.StructError) {
52
+ throw new Error(`Expected a number-like value, got "${value}".`);
53
+ }
54
+ /* istanbul ignore next */ throw error;
55
+ }
56
+ }
57
+ function createBigInt(value) {
58
+ try {
59
+ // The `BigInt` constructor throws if the value is not a number-like value.
60
+ // There is no need to validate the value manually.
61
+ return (0, _superstruct.create)(value, BigIntCoercer);
62
+ } catch (error) {
63
+ if (error instanceof _superstruct.StructError) {
64
+ throw new Error(`Expected a number-like value, got "${String(error.value)}".`);
65
+ }
66
+ /* istanbul ignore next */ throw error;
67
+ }
68
+ }
69
+ function createBytes(value) {
70
+ if (typeof value === 'string' && value.toLowerCase() === '0x') {
71
+ return new Uint8Array();
72
+ }
73
+ try {
74
+ return (0, _superstruct.create)(value, BytesCoercer);
75
+ } catch (error) {
76
+ if (error instanceof _superstruct.StructError) {
77
+ throw new Error(`Expected a bytes-like value, got "${String(error.value)}".`);
78
+ }
79
+ /* istanbul ignore next */ throw error;
80
+ }
81
+ }
82
+ function createHex(value) {
83
+ if (value instanceof Uint8Array && value.length === 0 || typeof value === 'string' && value.toLowerCase() === '0x') {
84
+ return '0x';
85
+ }
86
+ try {
87
+ return (0, _superstruct.create)(value, HexCoercer);
88
+ } catch (error) {
89
+ if (error instanceof _superstruct.StructError) {
90
+ throw new Error(`Expected a bytes-like value, got "${String(error.value)}".`);
91
+ }
92
+ /* istanbul ignore next */ throw error;
93
+ }
94
+ }
95
+
96
+ //# sourceMappingURL=coercers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/coercers.ts"],"sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n bigint,\n coerce,\n create,\n instance,\n number,\n string,\n StructError,\n union,\n} from 'superstruct';\n\nimport { assert } from './assert';\nimport { bytesToHex, hexToBytes } from './bytes';\nimport type { Hex } from './hex';\nimport { StrictHexStruct } from './hex';\n\nconst NumberLikeStruct = union([number(), bigint(), string(), StrictHexStruct]);\nconst NumberCoercer = coerce(number(), NumberLikeStruct, Number);\nconst BigIntCoercer = coerce(bigint(), NumberLikeStruct, BigInt);\n\nconst BytesLikeStruct = union([StrictHexStruct, instance(Uint8Array)]);\nconst BytesCoercer = coerce(\n instance(Uint8Array),\n union([StrictHexStruct]),\n hexToBytes,\n);\n\nconst HexCoercer = coerce(StrictHexStruct, instance(Uint8Array), bytesToHex);\n\nexport type NumberLike = Infer<typeof NumberLikeStruct>;\nexport type BytesLike = Infer<typeof BytesLikeStruct>;\n\n/**\n * Create a number from a number-like value.\n *\n * - If the value is a number, it is returned as-is.\n * - If the value is a `bigint`, it is converted to a number.\n * - If the value is a string, it is interpreted as a decimal number.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number.\n *\n * This validates that the value is a number-like value, and that the resulting\n * number is not `NaN` or `Infinity`.\n *\n * @example\n * ```typescript\n * const value = createNumber('0x010203');\n * console.log(value); // 66051\n *\n * const otherValue = createNumber(123n);\n * console.log(otherValue); // 123\n * ```\n * @param value - The value to create the number from.\n * @returns The created number.\n * @throws If the value is not a number-like value, or if the resulting number\n * is `NaN` or `Infinity`.\n */\nexport function createNumber(value: NumberLike): number {\n try {\n const result = create(value, NumberCoercer);\n\n assert(\n Number.isFinite(result),\n `Expected a number-like value, got \"${value}\".`,\n );\n\n return result;\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(`Expected a number-like value, got \"${value}\".`);\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a `bigint` from a number-like value.\n *\n * - If the value is a number, it is converted to a `bigint`.\n * - If the value is a `bigint`, it is returned as-is.\n * - If the value is a string, it is interpreted as a decimal number and\n * converted to a `bigint`.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is\n * interpreted as a hexadecimal number and converted to a `bigint`.\n *\n * @example\n * ```typescript\n * const value = createBigInt('0x010203');\n * console.log(value); // 16909060n\n *\n * const otherValue = createBigInt(123);\n * console.log(otherValue); // 123n\n * ```\n * @param value - The value to create the bigint from.\n * @returns The created bigint.\n * @throws If the value is not a number-like value.\n */\nexport function createBigInt(value: NumberLike): bigint {\n try {\n // The `BigInt` constructor throws if the value is not a number-like value.\n // There is no need to validate the value manually.\n return create(value, BigIntCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a number-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a byte array from a bytes-like value.\n *\n * - If the value is a byte array, it is returned as-is.\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is interpreted\n * as a hexadecimal number and converted to a byte array.\n *\n * @example\n * ```typescript\n * const value = createBytes('0x010203');\n * console.log(value); // Uint8Array [ 1, 2, 3 ]\n *\n * const otherValue = createBytes('0x010203');\n * console.log(otherValue); // Uint8Array [ 1, 2, 3 ]\n * ```\n * @param value - The value to create the byte array from.\n * @returns The created byte array.\n * @throws If the value is not a bytes-like value.\n */\nexport function createBytes(value: BytesLike): Uint8Array {\n if (typeof value === 'string' && value.toLowerCase() === '0x') {\n return new Uint8Array();\n }\n\n try {\n return create(value, BytesCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n\n/**\n * Create a hexadecimal string from a bytes-like value.\n *\n * - If the value is a hex string (i.e., it starts with \"0x\"), it is returned\n * as-is.\n * - If the value is a `Uint8Array`, it is converted to a hex string.\n *\n * @example\n * ```typescript\n * const value = createHex(new Uint8Array([1, 2, 3]));\n * console.log(value); // '0x010203'\n *\n * const otherValue = createHex('0x010203');\n * console.log(otherValue); // '0x010203'\n * ```\n * @param value - The value to create the hex string from.\n * @returns The created hex string.\n * @throws If the value is not a bytes-like value.\n */\nexport function createHex(value: BytesLike): Hex {\n if (\n (value instanceof Uint8Array && value.length === 0) ||\n (typeof value === 'string' && value.toLowerCase() === '0x')\n ) {\n return '0x';\n }\n\n try {\n return create(value, HexCoercer);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Expected a bytes-like value, got \"${String(error.value)}\".`,\n );\n }\n\n /* istanbul ignore next */\n throw error;\n }\n}\n"],"names":["createNumber","createBigInt","createBytes","createHex","NumberLikeStruct","union","number","bigint","string","StrictHexStruct","NumberCoercer","coerce","Number","BigIntCoercer","BigInt","BytesLikeStruct","instance","Uint8Array","BytesCoercer","hexToBytes","HexCoercer","bytesToHex","value","result","create","assert","isFinite","error","StructError","Error","String","toLowerCase","length"],"mappings":";;;;;;;;;;;IA0DgBA,YAAY;eAAZA;;IA0CAC,YAAY;eAAZA;;IAoCAC,WAAW;eAAXA;;IAsCAC,SAAS;eAATA;;;6BApKT;wBAEgB;uBACgB;qBAEP;AAEhC,MAAMC,mBAAmBC,IAAAA,kBAAK,EAAC;IAACC,IAAAA,mBAAM;IAAIC,IAAAA,mBAAM;IAAIC,IAAAA,mBAAM;IAAIC,oBAAe;CAAC;AAC9E,MAAMC,gBAAgBC,IAAAA,mBAAM,EAACL,IAAAA,mBAAM,KAAIF,kBAAkBQ;AACzD,MAAMC,gBAAgBF,IAAAA,mBAAM,EAACJ,IAAAA,mBAAM,KAAIH,kBAAkBU;AAEzD,MAAMC,kBAAkBV,IAAAA,kBAAK,EAAC;IAACI,oBAAe;IAAEO,IAAAA,qBAAQ,EAACC;CAAY;AACrE,MAAMC,eAAeP,IAAAA,mBAAM,EACzBK,IAAAA,qBAAQ,EAACC,aACTZ,IAAAA,kBAAK,EAAC;IAACI,oBAAe;CAAC,GACvBU,iBAAU;AAGZ,MAAMC,aAAaT,IAAAA,mBAAM,EAACF,oBAAe,EAAEO,IAAAA,qBAAQ,EAACC,aAAaI,iBAAU;AA8BpE,SAASrB,aAAasB,KAAiB;IAC5C,IAAI;QACF,MAAMC,SAASC,IAAAA,mBAAM,EAACF,OAAOZ;QAE7Be,IAAAA,cAAM,EACJb,OAAOc,QAAQ,C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