@metamask/utils 1.0.0 → 2.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 CHANGED
@@ -6,9 +6,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [2.0.0]
10
+ ### Added
11
+ - Add more JSON utils ([#8](https://github.com/MetaMask/utils/pull/8))
12
+
13
+ ### Changed
14
+ - **BREAKING:** Refactor and expand time utils ([#9](https://github.com/MetaMask/utils/pull/9))
15
+ - Adds a new function, `inMilliseconds`, and moves the time constants into a TypeScript `enum`.
16
+
9
17
  ## [1.0.0]
10
18
  ### Added
11
19
  - Initial release
12
20
 
13
- [Unreleased]: https://github.com/MetaMask/utils/compare/v1.0.0...HEAD
21
+ [Unreleased]: https://github.com/MetaMask/utils/compare/v2.0.0...HEAD
22
+ [2.0.0]: https://github.com/MetaMask/utils/compare/v1.0.0...v2.0.0
14
23
  [1.0.0]: https://github.com/MetaMask/utils/releases/tag/v1.0.0
package/README.md CHANGED
@@ -12,7 +12,7 @@ or
12
12
 
13
13
  ## API
14
14
 
15
- The full API documentation for the latest published version of this library is [available here](https://metamask.github.io/eth-sig-util/index.html).
15
+ The full API documentation for the latest published version of this library is [available here](https://metamask.github.io/utils/index.html).
16
16
 
17
17
  ## Contributing
18
18
 
package/dist/json.d.ts CHANGED
@@ -57,6 +57,35 @@ export declare type JsonRpcNotification<Params> = {
57
57
  method: string;
58
58
  params?: Params;
59
59
  };
60
+ /**
61
+ * Type guard to narrow a JSON-RPC request or notification object to a
62
+ * notification.
63
+ *
64
+ * @param requestOrNotification - The JSON-RPC request or notification to check.
65
+ * @returns Whether the specified JSON-RPC message is a notification.
66
+ */
67
+ export declare function isJsonRpcNotification<T>(requestOrNotification: JsonRpcNotification<T> | JsonRpcRequest<T>): requestOrNotification is JsonRpcNotification<T>;
68
+ /**
69
+ * Assertion type guard to narrow a JSON-RPC request or notification object to a
70
+ * notification.
71
+ *
72
+ * @param requestOrNotification - The JSON-RPC request or notification to check.
73
+ */
74
+ export declare function assertIsJsonRpcNotification<T>(requestOrNotification: JsonRpcNotification<T> | JsonRpcRequest<T>): asserts requestOrNotification is JsonRpcNotification<T>;
75
+ /**
76
+ * Type guard to narrow a JSON-RPC request or notification object to a request.
77
+ *
78
+ * @param requestOrNotification - The JSON-RPC request or notification to check.
79
+ * @returns Whether the specified JSON-RPC message is a request.
80
+ */
81
+ export declare function isJsonRpcRequest<T>(requestOrNotification: JsonRpcNotification<T> | JsonRpcRequest<T>): requestOrNotification is JsonRpcRequest<T>;
82
+ /**
83
+ * Assertion type guard to narrow a JSON-RPC request or notification object to a
84
+ * request.
85
+ *
86
+ * @param requestOrNotification - The JSON-RPC request or notification to check.
87
+ */
88
+ export declare function assertIsJsonRpcRequest<T>(requestOrNotification: JsonRpcNotification<T> | JsonRpcRequest<T>): asserts requestOrNotification is JsonRpcRequest<T>;
60
89
  /**
61
90
  * A successful JSON-RPC response object.
62
91
  *
@@ -83,10 +112,6 @@ export declare type JsonRpcFailure = {
83
112
  */
84
113
  export declare type JsonRpcResponse<Result = unknown> = JsonRpcSuccess<Result> | JsonRpcFailure;
85
114
  /**
86
- * ATTN: Assumes that only one of the `result` and `error` properties is
87
- * present on the `response`, as guaranteed by e.g.
88
- * [`JsonRpcEngine.handle`](https://github.com/MetaMask/json-rpc-engine/blob/main/src/JsonRpcEngine.ts).
89
- *
90
115
  * Type guard to narrow a JsonRpcResponse object to a success (or failure).
91
116
  *
92
117
  * @param response - The response object to check.
@@ -95,10 +120,12 @@ export declare type JsonRpcResponse<Result = unknown> = JsonRpcSuccess<Result> |
95
120
  */
96
121
  export declare function isJsonRpcSuccess<Result>(response: JsonRpcResponse<Result>): response is JsonRpcSuccess<Result>;
97
122
  /**
98
- * ATTN: Assumes that only one of the `result` and `error` properties is
99
- * present on the `response`, as guaranteed by e.g.
100
- * [`JsonRpcEngine.handle`](https://github.com/MetaMask/json-rpc-engine/blob/main/src/JsonRpcEngine.ts).
123
+ * Type assertion to narrow a JsonRpcResponse object to a success (or failure).
101
124
  *
125
+ * @param response - The response object to check.
126
+ */
127
+ export declare function assertIsJsonRpcSuccess<T>(response: JsonRpcResponse<T>): asserts response is JsonRpcSuccess<T>;
128
+ /**
102
129
  * Type guard to narrow a JsonRpcResponse object to a failure (or success).
103
130
  *
104
131
  * @param response - The response object to check.
@@ -106,3 +133,39 @@ export declare function isJsonRpcSuccess<Result>(response: JsonRpcResponse<Resul
106
133
  * property.
107
134
  */
108
135
  export declare function isJsonRpcFailure(response: JsonRpcResponse<unknown>): response is JsonRpcFailure;
136
+ /**
137
+ * Type assertion to narrow a JsonRpcResponse object to a failure (or success).
138
+ *
139
+ * @param response - The response object to check.
140
+ */
141
+ export declare function assertIsJsonRpcFailure(response: JsonRpcResponse<unknown>): asserts response is JsonRpcFailure;
142
+ declare type JsonRpcValidatorOptions = {
143
+ permitEmptyString?: boolean;
144
+ permitFractions?: boolean;
145
+ permitNull?: boolean;
146
+ };
147
+ /**
148
+ * Gets a function for validating JSON-RPC request / response `id` values.
149
+ *
150
+ * By manipulating the options of this factory, you can control the behavior
151
+ * of the resulting validator for some edge cases. This is useful because e.g.
152
+ * `null` should sometimes but not always be permitted.
153
+ *
154
+ * Note that the empty string (`''`) is always permitted by the JSON-RPC
155
+ * specification, but that kind of sucks and you may want to forbid it in some
156
+ * instances anyway.
157
+ *
158
+ * For more details, see the
159
+ * [JSON-RPC Specification](https://www.jsonrpc.org/specification).
160
+ *
161
+ * @param options - An options object.
162
+ * @param options.permitEmptyString - Whether the empty string (i.e. `''`)
163
+ * should be treated as a valid ID. Default: `true`
164
+ * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)
165
+ * should be treated as valid IDs. Default: `false`
166
+ * @param options.permitNull - Whether `null` should be treated as a valid ID.
167
+ * Default: `true`
168
+ * @returns The JSON-RPC ID validator function.
169
+ */
170
+ export declare function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions): (id: unknown) => id is JsonRpcId;
171
+ export {};
package/dist/json.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.isJsonRpcFailure = exports.isJsonRpcSuccess = exports.jsonrpc2 = exports.isValidJson = void 0;
6
+ exports.getJsonRpcIdValidator = exports.assertIsJsonRpcFailure = exports.isJsonRpcFailure = exports.assertIsJsonRpcSuccess = exports.isJsonRpcSuccess = exports.assertIsJsonRpcRequest = exports.isJsonRpcRequest = exports.assertIsJsonRpcNotification = exports.isJsonRpcNotification = exports.jsonrpc2 = exports.isValidJson = void 0;
7
7
  const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
8
8
  const misc_1 = require("./misc");
9
9
  /**
@@ -26,10 +26,51 @@ exports.isValidJson = isValidJson;
26
26
  */
27
27
  exports.jsonrpc2 = '2.0';
28
28
  /**
29
- * ATTN: Assumes that only one of the `result` and `error` properties is
30
- * present on the `response`, as guaranteed by e.g.
31
- * [`JsonRpcEngine.handle`](https://github.com/MetaMask/json-rpc-engine/blob/main/src/JsonRpcEngine.ts).
29
+ * Type guard to narrow a JSON-RPC request or notification object to a
30
+ * notification.
32
31
  *
32
+ * @param requestOrNotification - The JSON-RPC request or notification to check.
33
+ * @returns Whether the specified JSON-RPC message is a notification.
34
+ */
35
+ function isJsonRpcNotification(requestOrNotification) {
36
+ return !misc_1.hasProperty(requestOrNotification, 'id');
37
+ }
38
+ exports.isJsonRpcNotification = isJsonRpcNotification;
39
+ /**
40
+ * Assertion type guard to narrow a JSON-RPC request or notification object to a
41
+ * notification.
42
+ *
43
+ * @param requestOrNotification - The JSON-RPC request or notification to check.
44
+ */
45
+ function assertIsJsonRpcNotification(requestOrNotification) {
46
+ if (!isJsonRpcNotification(requestOrNotification)) {
47
+ throw new Error('Not a JSON-RPC notification.');
48
+ }
49
+ }
50
+ exports.assertIsJsonRpcNotification = assertIsJsonRpcNotification;
51
+ /**
52
+ * Type guard to narrow a JSON-RPC request or notification object to a request.
53
+ *
54
+ * @param requestOrNotification - The JSON-RPC request or notification to check.
55
+ * @returns Whether the specified JSON-RPC message is a request.
56
+ */
57
+ function isJsonRpcRequest(requestOrNotification) {
58
+ return misc_1.hasProperty(requestOrNotification, 'id');
59
+ }
60
+ exports.isJsonRpcRequest = isJsonRpcRequest;
61
+ /**
62
+ * Assertion type guard to narrow a JSON-RPC request or notification object to a
63
+ * request.
64
+ *
65
+ * @param requestOrNotification - The JSON-RPC request or notification to check.
66
+ */
67
+ function assertIsJsonRpcRequest(requestOrNotification) {
68
+ if (!isJsonRpcRequest(requestOrNotification)) {
69
+ throw new Error('Not a JSON-RPC request.');
70
+ }
71
+ }
72
+ exports.assertIsJsonRpcRequest = assertIsJsonRpcRequest;
73
+ /**
33
74
  * Type guard to narrow a JsonRpcResponse object to a success (or failure).
34
75
  *
35
76
  * @param response - The response object to check.
@@ -41,10 +82,17 @@ function isJsonRpcSuccess(response) {
41
82
  }
42
83
  exports.isJsonRpcSuccess = isJsonRpcSuccess;
43
84
  /**
44
- * ATTN: Assumes that only one of the `result` and `error` properties is
45
- * present on the `response`, as guaranteed by e.g.
46
- * [`JsonRpcEngine.handle`](https://github.com/MetaMask/json-rpc-engine/blob/main/src/JsonRpcEngine.ts).
85
+ * Type assertion to narrow a JsonRpcResponse object to a success (or failure).
47
86
  *
87
+ * @param response - The response object to check.
88
+ */
89
+ function assertIsJsonRpcSuccess(response) {
90
+ if (!isJsonRpcSuccess(response)) {
91
+ throw new Error('Not a successful JSON-RPC response.');
92
+ }
93
+ }
94
+ exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess;
95
+ /**
48
96
  * Type guard to narrow a JsonRpcResponse object to a failure (or success).
49
97
  *
50
98
  * @param response - The response object to check.
@@ -55,4 +103,55 @@ function isJsonRpcFailure(response) {
55
103
  return misc_1.hasProperty(response, 'error');
56
104
  }
57
105
  exports.isJsonRpcFailure = isJsonRpcFailure;
106
+ /**
107
+ * Type assertion to narrow a JsonRpcResponse object to a failure (or success).
108
+ *
109
+ * @param response - The response object to check.
110
+ */
111
+ function assertIsJsonRpcFailure(response) {
112
+ if (!isJsonRpcFailure(response)) {
113
+ throw new Error('Not a failed JSON-RPC response.');
114
+ }
115
+ }
116
+ exports.assertIsJsonRpcFailure = assertIsJsonRpcFailure;
117
+ /**
118
+ * Gets a function for validating JSON-RPC request / response `id` values.
119
+ *
120
+ * By manipulating the options of this factory, you can control the behavior
121
+ * of the resulting validator for some edge cases. This is useful because e.g.
122
+ * `null` should sometimes but not always be permitted.
123
+ *
124
+ * Note that the empty string (`''`) is always permitted by the JSON-RPC
125
+ * specification, but that kind of sucks and you may want to forbid it in some
126
+ * instances anyway.
127
+ *
128
+ * For more details, see the
129
+ * [JSON-RPC Specification](https://www.jsonrpc.org/specification).
130
+ *
131
+ * @param options - An options object.
132
+ * @param options.permitEmptyString - Whether the empty string (i.e. `''`)
133
+ * should be treated as a valid ID. Default: `true`
134
+ * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)
135
+ * should be treated as valid IDs. Default: `false`
136
+ * @param options.permitNull - Whether `null` should be treated as a valid ID.
137
+ * Default: `true`
138
+ * @returns The JSON-RPC ID validator function.
139
+ */
140
+ function getJsonRpcIdValidator(options) {
141
+ const { permitEmptyString, permitFractions, permitNull } = Object.assign({ permitEmptyString: true, permitFractions: false, permitNull: true }, options);
142
+ /**
143
+ * Type guard for {@link JsonRpcId}.
144
+ *
145
+ * @param id - The JSON-RPC ID value to check.
146
+ * @returns Whether the given ID is valid per the options given to the
147
+ * factory.
148
+ */
149
+ const isValidJsonRpcId = (id) => {
150
+ return Boolean((typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||
151
+ (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||
152
+ (permitNull && id === null));
153
+ };
154
+ return isValidJsonRpcId;
155
+ }
156
+ exports.getJsonRpcIdValidator = getJsonRpcIdValidator;
58
157
  //# sourceMappingURL=json.js.map
package/dist/json.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;;;;AAAA,sEAAwC;AACxC,iCAAqC;AAarC;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,IAAI;QACF,OAAO,yBAAS,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,kCAMC;AAED;;GAEG;AACU,QAAA,QAAQ,GAAG,KAAc,CAAC;AA+EvC;;;;;;;;;;GAUG;AACH,SAAgB,gBAAgB,CAC9B,QAAiC;IAEjC,OAAO,kBAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;AACzC,CAAC;AAJD,4CAIC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,gBAAgB,CAC9B,QAAkC;IAElC,OAAO,kBAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC;AAJD,4CAIC","sourcesContent":["import deepEqual from 'fast-deep-equal';\nimport { hasProperty } from './misc';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = number | string | null;\n\n/**\n * A JSON-RPC error object.\n */\nexport type JsonRpcError = {\n code: number;\n message: string;\n data?: unknown;\n stack?: string;\n};\n\n/**\n * A JSON-RPC request object.\n *\n * @template Params - The type of the params.\n */\nexport type JsonRpcRequest<Params> = {\n id: JsonRpcId;\n jsonrpc: JsonRpcVersion2;\n method: string;\n params?: Params;\n};\n\n/**\n * A JSON-RPC notification object.\n *\n * @template Params - The type of the params.\n */\nexport type JsonRpcNotification<Params> = {\n jsonrpc: JsonRpcVersion2;\n method: string;\n params?: Params;\n};\n\n/**\n * A successful JSON-RPC response object.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcSuccess<Result = unknown> = {\n id: JsonRpcId;\n jsonrpc: JsonRpcVersion2;\n result: Result;\n};\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = {\n id: JsonRpcId;\n jsonrpc: JsonRpcVersion2;\n error: JsonRpcError;\n};\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result = unknown> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * ATTN: Assumes that only one of the `result` and `error` properties is\n * present on the `response`, as guaranteed by e.g.\n * [`JsonRpcEngine.handle`](https://github.com/MetaMask/json-rpc-engine/blob/main/src/JsonRpcEngine.ts).\n *\n * Type guard to narrow a JsonRpcResponse object to a success (or failure).\n *\n * @param response - The response object to check.\n * @returns Whether the response object is a success, i.e. has a `result`\n * property.\n */\nexport function isJsonRpcSuccess<Result>(\n response: JsonRpcResponse<Result>,\n): response is JsonRpcSuccess<Result> {\n return hasProperty(response, 'result');\n}\n\n/**\n * ATTN: Assumes that only one of the `result` and `error` properties is\n * present on the `response`, as guaranteed by e.g.\n * [`JsonRpcEngine.handle`](https://github.com/MetaMask/json-rpc-engine/blob/main/src/JsonRpcEngine.ts).\n *\n * Type guard to narrow a JsonRpcResponse object to a failure (or success).\n *\n * @param response - The response object to check.\n * @returns Whether the response object is a failure, i.e. has an `error`\n * property.\n */\nexport function isJsonRpcFailure(\n response: JsonRpcResponse<unknown>,\n): response is JsonRpcFailure {\n return hasProperty(response, 'error');\n}\n"]}
1
+ {"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;;;;AAAA,sEAAwC;AACxC,iCAAqC;AAarC;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,IAAI;QACF,OAAO,yBAAS,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,kCAMC;AAED;;GAEG;AACU,QAAA,QAAQ,GAAG,KAAc,CAAC;AAiDvC;;;;;;GAMG;AACH,SAAgB,qBAAqB,CACnC,qBAAiE;IAEjE,OAAO,CAAC,kBAAW,CAAC,qBAAqB,EAAE,IAAI,CAAC,CAAC;AACnD,CAAC;AAJD,sDAIC;AAED;;;;;GAKG;AACH,SAAgB,2BAA2B,CACzC,qBAAiE;IAEjE,IAAI,CAAC,qBAAqB,CAAC,qBAAqB,CAAC,EAAE;QACjD,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;KACjD;AACH,CAAC;AAND,kEAMC;AAED;;;;;GAKG;AACH,SAAgB,gBAAgB,CAC9B,qBAAiE;IAEjE,OAAO,kBAAW,CAAC,qBAAqB,EAAE,IAAI,CAAC,CAAC;AAClD,CAAC;AAJD,4CAIC;AAED;;;;;GAKG;AACH,SAAgB,sBAAsB,CACpC,qBAAiE;IAEjE,IAAI,CAAC,gBAAgB,CAAC,qBAAqB,CAAC,EAAE;QAC5C,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;KAC5C;AACH,CAAC;AAND,wDAMC;AAgCD;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAC9B,QAAiC;IAEjC,OAAO,kBAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;AACzC,CAAC;AAJD,4CAIC;AAED;;;;GAIG;AACH,SAAgB,sBAAsB,CACpC,QAA4B;IAE5B,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE;QAC/B,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;KACxD;AACH,CAAC;AAND,wDAMC;AAED;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAC9B,QAAkC;IAElC,OAAO,kBAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC;AAJD,4CAIC;AAED;;;;GAIG;AACH,SAAgB,sBAAsB,CACpC,QAAkC;IAElC,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE;QAC/B,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;KACpD;AACH,CAAC;AAND,wDAMC;AAQD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,qBAAqB,CAAC,OAAiC;IACrE,MAAM,EAAE,iBAAiB,EAAE,eAAe,EAAE,UAAU,EAAE,mBACtD,iBAAiB,EAAE,IAAI,EACvB,eAAe,EAAE,KAAK,EACtB,UAAU,EAAE,IAAI,IACb,OAAO,CACX,CAAC;IAEF;;;;;;OAMG;IACH,MAAM,gBAAgB,GAAG,CAAC,EAAW,EAAmB,EAAE;QACxD,OAAO,OAAO,CACZ,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,eAAe,IAAI,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;YACnE,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAChE,CAAC,UAAU,IAAI,EAAE,KAAK,IAAI,CAAC,CAC9B,CAAC;IACJ,CAAC,CAAC;IACF,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAvBD,sDAuBC","sourcesContent":["import deepEqual from 'fast-deep-equal';\nimport { hasProperty } from './misc';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = number | string | null;\n\n/**\n * A JSON-RPC error object.\n */\nexport type JsonRpcError = {\n code: number;\n message: string;\n data?: unknown;\n stack?: string;\n};\n\n/**\n * A JSON-RPC request object.\n *\n * @template Params - The type of the params.\n */\nexport type JsonRpcRequest<Params> = {\n id: JsonRpcId;\n jsonrpc: JsonRpcVersion2;\n method: string;\n params?: Params;\n};\n\n/**\n * A JSON-RPC notification object.\n *\n * @template Params - The type of the params.\n */\nexport type JsonRpcNotification<Params> = {\n jsonrpc: JsonRpcVersion2;\n method: string;\n params?: Params;\n};\n\n/**\n * Type guard to narrow a JSON-RPC request or notification object to a\n * notification.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n * @returns Whether the specified JSON-RPC message is a notification.\n */\nexport function isJsonRpcNotification<T>(\n requestOrNotification: JsonRpcNotification<T> | JsonRpcRequest<T>,\n): requestOrNotification is JsonRpcNotification<T> {\n return !hasProperty(requestOrNotification, 'id');\n}\n\n/**\n * Assertion type guard to narrow a JSON-RPC request or notification object to a\n * notification.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n */\nexport function assertIsJsonRpcNotification<T>(\n requestOrNotification: JsonRpcNotification<T> | JsonRpcRequest<T>,\n): asserts requestOrNotification is JsonRpcNotification<T> {\n if (!isJsonRpcNotification(requestOrNotification)) {\n throw new Error('Not a JSON-RPC notification.');\n }\n}\n\n/**\n * Type guard to narrow a JSON-RPC request or notification object to a request.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n * @returns Whether the specified JSON-RPC message is a request.\n */\nexport function isJsonRpcRequest<T>(\n requestOrNotification: JsonRpcNotification<T> | JsonRpcRequest<T>,\n): requestOrNotification is JsonRpcRequest<T> {\n return hasProperty(requestOrNotification, 'id');\n}\n\n/**\n * Assertion type guard to narrow a JSON-RPC request or notification object to a\n * request.\n *\n * @param requestOrNotification - The JSON-RPC request or notification to check.\n */\nexport function assertIsJsonRpcRequest<T>(\n requestOrNotification: JsonRpcNotification<T> | JsonRpcRequest<T>,\n): asserts requestOrNotification is JsonRpcRequest<T> {\n if (!isJsonRpcRequest(requestOrNotification)) {\n throw new Error('Not a JSON-RPC request.');\n }\n}\n\n/**\n * A successful JSON-RPC response object.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcSuccess<Result = unknown> = {\n id: JsonRpcId;\n jsonrpc: JsonRpcVersion2;\n result: Result;\n};\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = {\n id: JsonRpcId;\n jsonrpc: JsonRpcVersion2;\n error: JsonRpcError;\n};\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result = unknown> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to narrow a JsonRpcResponse object to a success (or failure).\n *\n * @param response - The response object to check.\n * @returns Whether the response object is a success, i.e. has a `result`\n * property.\n */\nexport function isJsonRpcSuccess<Result>(\n response: JsonRpcResponse<Result>,\n): response is JsonRpcSuccess<Result> {\n return hasProperty(response, 'result');\n}\n\n/**\n * Type assertion to narrow a JsonRpcResponse object to a success (or failure).\n *\n * @param response - The response object to check.\n */\nexport function assertIsJsonRpcSuccess<T>(\n response: JsonRpcResponse<T>,\n): asserts response is JsonRpcSuccess<T> {\n if (!isJsonRpcSuccess(response)) {\n throw new Error('Not a successful JSON-RPC response.');\n }\n}\n\n/**\n * Type guard to narrow a JsonRpcResponse object to a failure (or success).\n *\n * @param response - The response object to check.\n * @returns Whether the response object is a failure, i.e. has an `error`\n * property.\n */\nexport function isJsonRpcFailure(\n response: JsonRpcResponse<unknown>,\n): response is JsonRpcFailure {\n return hasProperty(response, 'error');\n}\n\n/**\n * Type assertion to narrow a JsonRpcResponse object to a failure (or success).\n *\n * @param response - The response object to check.\n */\nexport function assertIsJsonRpcFailure(\n response: JsonRpcResponse<unknown>,\n): asserts response is JsonRpcFailure {\n if (!isJsonRpcFailure(response)) {\n throw new Error('Not a failed JSON-RPC response.');\n }\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n return isValidJsonRpcId;\n}\n"]}
package/dist/time.d.ts CHANGED
@@ -1,23 +1,44 @@
1
1
  /**
2
- * A millisecond.
2
+ * Common duration constants, in milliseconds.
3
3
  */
4
- export declare const MILLISECOND = 1;
4
+ export declare enum Duration {
5
+ /**
6
+ * A millisecond.
7
+ */
8
+ Millisecond = 1,
9
+ /**
10
+ * A second, in milliseconds.
11
+ */
12
+ Second = 1000,
13
+ /**
14
+ * A minute, in milliseconds.
15
+ */
16
+ Minute = 60000,
17
+ /**
18
+ * An hour, in milliseconds.
19
+ */
20
+ Hour = 3600000,
21
+ /**
22
+ * A day, in milliseconds.
23
+ */
24
+ Day = 86400000,
25
+ /**
26
+ * A week, in milliseconds.
27
+ */
28
+ Week = 604800000,
29
+ /**
30
+ * A year, in milliseconds.
31
+ */
32
+ Year = 31536000000
33
+ }
5
34
  /**
6
- * A second, in milliseconds.
7
- */
8
- export declare const SECOND = 1000;
9
- /**
10
- * A minute, in milliseconds.
11
- */
12
- export declare const MINUTE = 60000;
13
- /**
14
- * An hour, in milliseconds.
15
- */
16
- export declare const HOUR = 3600000;
17
- /**
18
- * A day, in milliseconds.
35
+ * Calculates the millisecond value of the specified number of units of time.
36
+ *
37
+ * @param count - The number of units of time.
38
+ * @param duration - The unit of time to count.
39
+ * @returns The count multiplied by the specified duration.
19
40
  */
20
- export declare const DAY = 86400000;
41
+ export declare function inMilliseconds(count: number, duration: Duration): number;
21
42
  /**
22
43
  * Gets the milliseconds since a particular Unix epoch timestamp.
23
44
  *
package/dist/time.js CHANGED
@@ -1,26 +1,58 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.timeSince = exports.DAY = exports.HOUR = exports.MINUTE = exports.SECOND = exports.MILLISECOND = void 0;
3
+ exports.timeSince = exports.inMilliseconds = exports.Duration = void 0;
4
4
  /**
5
- * A millisecond.
5
+ * Common duration constants, in milliseconds.
6
6
  */
7
- exports.MILLISECOND = 1;
7
+ var Duration;
8
+ (function (Duration) {
9
+ /**
10
+ * A millisecond.
11
+ */
12
+ Duration[Duration["Millisecond"] = 1] = "Millisecond";
13
+ /**
14
+ * A second, in milliseconds.
15
+ */
16
+ Duration[Duration["Second"] = 1000] = "Second";
17
+ /**
18
+ * A minute, in milliseconds.
19
+ */
20
+ Duration[Duration["Minute"] = 60000] = "Minute";
21
+ /**
22
+ * An hour, in milliseconds.
23
+ */
24
+ Duration[Duration["Hour"] = 3600000] = "Hour";
25
+ /**
26
+ * A day, in milliseconds.
27
+ */
28
+ Duration[Duration["Day"] = 86400000] = "Day";
29
+ /**
30
+ * A week, in milliseconds.
31
+ */
32
+ Duration[Duration["Week"] = 604800000] = "Week";
33
+ /**
34
+ * A year, in milliseconds.
35
+ */
36
+ Duration[Duration["Year"] = 31536000000] = "Year";
37
+ })(Duration = exports.Duration || (exports.Duration = {}));
38
+ const isNonNegativeInteger = (number) => Number.isInteger(number) && number >= 0;
39
+ const assertIsNonNegativeInteger = (number, name) => {
40
+ if (!isNonNegativeInteger(number)) {
41
+ throw new Error(`"${name}" must be a non-negative integer. Received: "${number}".`);
42
+ }
43
+ };
8
44
  /**
9
- * A second, in milliseconds.
10
- */
11
- exports.SECOND = 1000; // MILLISECOND * 1000
12
- /**
13
- * A minute, in milliseconds.
14
- */
15
- exports.MINUTE = 60000; // SECOND * 60
16
- /**
17
- * An hour, in milliseconds.
18
- */
19
- exports.HOUR = 3600000; // MINUTE * 60
20
- /**
21
- * A day, in milliseconds.
45
+ * Calculates the millisecond value of the specified number of units of time.
46
+ *
47
+ * @param count - The number of units of time.
48
+ * @param duration - The unit of time to count.
49
+ * @returns The count multiplied by the specified duration.
22
50
  */
23
- exports.DAY = 86400000; // HOUR * 24
51
+ function inMilliseconds(count, duration) {
52
+ assertIsNonNegativeInteger(count, 'count');
53
+ return count * duration;
54
+ }
55
+ exports.inMilliseconds = inMilliseconds;
24
56
  /**
25
57
  * Gets the milliseconds since a particular Unix epoch timestamp.
26
58
  *
@@ -28,6 +60,7 @@ exports.DAY = 86400000; // HOUR * 24
28
60
  * @returns The number of milliseconds elapsed since the specified timestamp.
29
61
  */
30
62
  function timeSince(timestamp) {
63
+ assertIsNonNegativeInteger(timestamp, 'timestamp');
31
64
  return Date.now() - timestamp;
32
65
  }
33
66
  exports.timeSince = timeSince;
package/dist/time.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"time.js","sourceRoot":"","sources":["../src/time.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACU,QAAA,WAAW,GAAG,CAAC,CAAC;AAE7B;;GAEG;AACU,QAAA,MAAM,GAAG,IAAI,CAAC,CAAC,qBAAqB;AAEjD;;GAEG;AACU,QAAA,MAAM,GAAG,KAAM,CAAC,CAAC,cAAc;AAE5C;;GAEG;AACU,QAAA,IAAI,GAAG,OAAS,CAAC,CAAC,cAAc;AAE7C;;GAEG;AACU,QAAA,GAAG,GAAG,QAAU,CAAC,CAAC,YAAY;AAE3C;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,SAAiB;IACzC,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;AAChC,CAAC;AAFD,8BAEC","sourcesContent":["/**\n * A millisecond.\n */\nexport const MILLISECOND = 1;\n\n/**\n * A second, in milliseconds.\n */\nexport const SECOND = 1000; // MILLISECOND * 1000\n\n/**\n * A minute, in milliseconds.\n */\nexport const MINUTE = 60_000; // SECOND * 60\n\n/**\n * An hour, in milliseconds.\n */\nexport const HOUR = 3_600_000; // MINUTE * 60\n\n/**\n * A day, in milliseconds.\n */\nexport const DAY = 86_400_000; // HOUR * 24\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 return Date.now() - timestamp;\n}\n"]}
1
+ {"version":3,"file":"time.js","sourceRoot":"","sources":["../src/time.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,IAAY,QAmCX;AAnCD,WAAY,QAAQ;IAClB;;OAEG;IACH,qDAAe,CAAA;IAEf;;OAEG;IACH,8CAAa,CAAA;IAEb;;OAEG;IACH,+CAAe,CAAA;IAEf;;OAEG;IACH,6CAAgB,CAAA;IAEhB;;OAEG;IACH,4CAAgB,CAAA;IAEhB;;OAEG;IACH,+CAAkB,CAAA;IAElB;;OAEG;IACH,iDAAqB,CAAA;AACvB,CAAC,EAnCW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAmCnB;AAED,MAAM,oBAAoB,GAAG,CAAC,MAAc,EAAE,EAAE,CAC9C,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC,CAAC;AAE1C,MAAM,0BAA0B,GAAG,CAAC,MAAc,EAAE,IAAY,EAAE,EAAE;IAClE,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,EAAE;QACjC,MAAM,IAAI,KAAK,CACb,IAAI,IAAI,gDAAgD,MAAM,IAAI,CACnE,CAAC;KACH;AACH,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,KAAa,EAAE,QAAkB;IAC9D,0BAA0B,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC3C,OAAO,KAAK,GAAG,QAAQ,CAAC;AAC1B,CAAC;AAHD,wCAGC;AAED;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,SAAiB;IACzC,0BAA0B,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IACnD,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;AAChC,CAAC;AAHD,8BAGC","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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/utils",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "description": "Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase.",
5
5
  "repository": {
6
6
  "type": "git",