@metamask/utils 5.0.2 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/README.md +3 -4
- package/dist/__fixtures__/bytes.d.ts +25 -0
- package/dist/__fixtures__/bytes.js +234 -0
- package/dist/__fixtures__/bytes.js.map +1 -0
- package/dist/__fixtures__/coercions.d.ts +5 -0
- package/dist/__fixtures__/coercions.js +22 -0
- package/dist/__fixtures__/coercions.js.map +1 -0
- package/dist/__fixtures__/index.d.ts +4 -0
- package/dist/__fixtures__/index.js +21 -0
- package/dist/__fixtures__/index.js.map +1 -0
- package/dist/__fixtures__/json.d.ts +1226 -0
- package/dist/__fixtures__/json.js +1491 -0
- package/dist/__fixtures__/json.js.map +1 -0
- package/dist/__fixtures__/numbers.d.ts +5 -0
- package/dist/__fixtures__/numbers.js +56 -0
- package/dist/__fixtures__/numbers.js.map +1 -0
- package/dist/assert.js +1 -2
- package/dist/assert.js.map +1 -1
- package/dist/base64.js +2 -3
- package/dist/base64.js.map +1 -1
- package/dist/bytes.js +1 -2
- package/dist/bytes.js.map +1 -1
- package/dist/hex.test-d.d.ts +1 -0
- package/dist/hex.test-d.js +16 -0
- package/dist/hex.test-d.js.map +1 -0
- package/dist/json.d.ts +17 -4
- package/dist/json.js +33 -45
- package/dist/json.js.map +1 -1
- package/dist/json.test-d.d.ts +1 -0
- package/dist/json.test-d.js +62 -0
- package/dist/json.test-d.js.map +1 -0
- package/dist/misc.js +1 -2
- package/dist/misc.js.map +1 -1
- package/dist/misc.test-d.d.ts +1 -0
- package/dist/misc.test-d.js +97 -0
- package/dist/misc.test-d.js.map +1 -0
- package/package.json +25 -14
package/dist/json.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;AAAA,6CAmBqB;AAErB,qCAAmE;AAanE;;;;;GAKG;AACH,M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,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;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAxBD,sDAwBC","sourcesContent":["import {\n array,\n boolean,\n define,\n Infer,\n integer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object,\n omit,\n optional,\n record,\n string,\n Struct,\n union,\n unknown,\n} from 'superstruct';\n\nimport { AssertionErrorConstructor, assertStruct } from './assert';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A struct to check if the given value is finite number. Superstruct's\n * `number()` struct does not check if the value is finite.\n *\n * @returns A struct to check if the given value is finite number.\n */\nconst finiteNumber = () =>\n define<number>('finite number', (value) => {\n return is(value, number()) && Number.isFinite(value);\n });\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\n// We cannot infer the type of the struct, because it is recursive.\nexport const UnsafeJsonStruct: Struct<Json> = union([\n literal(null),\n boolean(),\n finiteNumber(),\n string(),\n array(lazy(() => UnsafeJsonStruct)),\n record(\n string(),\n lazy(() => UnsafeJsonStruct),\n ),\n]);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = define<Json>('Json', (value, context) => {\n /**\n * Helper function that runs the given struct validator and returns the\n * validation errors, if any. If the value is valid, it returns `true`.\n *\n * @param innerValue - The value to validate.\n * @param struct - The struct to use for validation.\n * @returns The validation errors, or `true` if the value is valid.\n */\n function checkStruct<Type>(innerValue: unknown, struct: Struct<Type>) {\n const iterator = struct.validator(innerValue, context);\n const errors = [...iterator];\n\n if (errors.length > 0) {\n return errors;\n }\n\n return true;\n }\n\n try {\n // The plain value must be a valid JSON value, but it may be altered in the\n // process of JSON serialization, so we need to validate it again after\n // serialization. This has the added benefit that the returned error messages\n // will be more helpful, as they will point to the exact location of the\n // invalid value.\n //\n // This seems overcomplicated, but without checking the plain value first,\n // there are some cases where the validation passes, even though the value is\n // not valid JSON. For example, `undefined` is not valid JSON, but serializing\n // it will remove it from the object, so the validation will pass.\n const unsafeResult = checkStruct(value, UnsafeJsonStruct);\n if (unsafeResult !== true) {\n return unsafeResult;\n }\n\n // JavaScript engines are highly optimized for this specific use case of\n // JSON parsing and stringifying, so there should be no performance impact.\n return checkStruct(JSON.parse(JSON.stringify(value)), UnsafeJsonStruct);\n } catch (error) {\n if (error instanceof RangeError) {\n return 'Circular reference detected';\n }\n\n return false;\n }\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n return is(value, JsonStruct);\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: optional(JsonStruct),\n stack: optional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct = optional(\n union([record(string(), JsonStruct), array(JsonStruct)]),\n);\nexport type JsonRpcParams = Infer<typeof JsonRpcParamsStruct>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: JsonRpcParamsStruct,\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Omit<Infer<Type>, 'params'> &\n (keyof Params extends undefined\n ? {\n params?: Params;\n }\n : {\n params: Params;\n });\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;AAAA,6CAsBqB;AAErB,qCAAmE;AAanE;;;;;GAKG;AACH,MAAM,YAAY,GAAG,GAAG,EAAE,CACxB,IAAA,oBAAM,EAAS,eAAe,EAAE,CAAC,KAAK,EAAE,EAAE;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,IAAA,oBAAM,GAAE,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AACvD,CAAC,CAAC,CAAC;AAEL;;;;GAIG;AACH,mEAAmE;AACtD,QAAA,gBAAgB,GAAiB,IAAA,mBAAK,EAAC;IAClD,IAAA,qBAAO,EAAC,IAAI,CAAC;IACb,IAAA,qBAAO,GAAE;IACT,YAAY,EAAE;IACd,IAAA,oBAAM,GAAE;IACR,IAAA,mBAAK,EAAC,IAAA,kBAAI,EAAC,GAAG,EAAE,CAAC,wBAAgB,CAAC,CAAC;IACnC,IAAA,oBAAM,EACJ,IAAA,oBAAM,GAAE,EACR,IAAA,kBAAI,EAAC,GAAG,EAAE,CAAC,wBAAgB,CAAC,CAC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D,iBAAiB,EAAE,IAAI;QACvB,eAAe,EAAE,KAAK;QACtB,UAAU,EAAE,IAAI;QAChB,GAAG,OAAO;KACX,CAAC;IAEF;;;;;;OAMG;IACH,MAAM,gBAAgB,GAAG,CAAC,EAAW,EAAmB,EAAE;QACxD,OAAO,OAAO,CACZ,CAAC,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,eAAe,IAAI,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;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;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAxBD,sDAwBC","sourcesContent":["import {\n any,\n array,\n boolean,\n coerce,\n create,\n define,\n Infer,\n integer,\n is,\n lazy,\n literal,\n nullable,\n number,\n object,\n omit,\n optional,\n record,\n string,\n Struct,\n union,\n unknown,\n} from 'superstruct';\n\nimport { AssertionErrorConstructor, assertStruct } from './assert';\n\n/**\n * Any JSON-compatible value.\n */\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [prop: string]: Json };\n\n/**\n * A struct to check if the given value is finite number. Superstruct's\n * `number()` struct does not check if the value is finite.\n *\n * @returns A struct to check if the given value is finite number.\n */\nconst finiteNumber = () =>\n define<number>('finite number', (value) => {\n return is(value, number()) && Number.isFinite(value);\n });\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.\n */\n// We cannot infer the type of the struct, because it is recursive.\nexport const UnsafeJsonStruct: Struct<Json> = union([\n literal(null),\n boolean(),\n finiteNumber(),\n string(),\n array(lazy(() => UnsafeJsonStruct)),\n record(\n string(),\n lazy(() => UnsafeJsonStruct),\n ),\n]);\n\n/**\n * A struct to check if the given value is a valid JSON-serializable value.\n *\n * This struct sanitizes the value before validating it, so that it is safe to\n * use with untrusted input.\n */\nexport const JsonStruct = coerce(UnsafeJsonStruct, any(), (value) => {\n assertStruct(value, UnsafeJsonStruct);\n return JSON.parse(JSON.stringify(value));\n});\n\n/**\n * Check if the given value is a valid {@link Json} value, i.e., a value that is\n * serializable to JSON.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link Json} value.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n getSafeJson(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate and return sanitized JSON.\n *\n * Note:\n * This function uses sanitized JsonStruct for validation\n * that applies stringify and then parse of a value provided\n * to ensure that there are no getters which can have side effects\n * that can cause security issues.\n *\n * @param value - JSON structure to be processed.\n * @returns Sanitized JSON structure.\n */\nexport function getSafeJson<Type extends Json = Json>(value: unknown): Type {\n return create(value, JsonStruct) as Type;\n}\n\n/**\n * Get the size of a JSON value in bytes. This also validates the value.\n *\n * @param value - The JSON value to get the size of.\n * @returns The size of the JSON value in bytes.\n */\nexport function getJsonSize(value: unknown): number {\n assertStruct(value, JsonStruct, 'Invalid JSON value');\n\n const json = JSON.stringify(value);\n return new TextEncoder().encode(json).byteLength;\n}\n\n/**\n * The string '2.0'.\n */\nexport const jsonrpc2 = '2.0' as const;\nexport const JsonRpcVersionStruct = literal(jsonrpc2);\n\n/**\n * A String specifying the version of the JSON-RPC protocol.\n * MUST be exactly \"2.0\".\n */\nexport type JsonRpcVersion2 = typeof jsonrpc2;\n\nexport const JsonRpcIdStruct = nullable(union([number(), string()]));\n\n/**\n * An identifier established by the Client that MUST contain a String, Number,\n * or NULL value if included. If it is not included it is assumed to be a\n * notification. The value SHOULD normally not be Null and Numbers SHOULD\n * NOT contain fractional parts.\n */\nexport type JsonRpcId = Infer<typeof JsonRpcIdStruct>;\n\nexport const JsonRpcErrorStruct = object({\n code: integer(),\n message: string(),\n data: optional(JsonStruct),\n stack: optional(string()),\n});\n\n/**\n * Mark a certain key of a type as optional.\n */\nexport type OptionalField<\n Type extends Record<string, unknown>,\n Key extends keyof Type,\n> = Omit<Type, Key> & Partial<Pick<Type, Key>>;\n\n/**\n * A JSON-RPC error object.\n *\n * Note that TypeScript infers `unknown | undefined` as `unknown`, meaning that\n * the `data` field is not optional. To make it optional, we use the\n * `OptionalField` helper, to explicitly make it optional.\n */\nexport type JsonRpcError = OptionalField<\n Infer<typeof JsonRpcErrorStruct>,\n 'data'\n>;\n\nexport const JsonRpcParamsStruct = optional(\n union([record(string(), JsonStruct), array(JsonStruct)]),\n);\nexport type JsonRpcParams = Infer<typeof JsonRpcParamsStruct>;\n\nexport const JsonRpcRequestStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n method: string(),\n params: JsonRpcParamsStruct,\n});\n\nexport type InferWithParams<\n Type extends Struct<any>,\n Params extends JsonRpcParams,\n> = Omit<Infer<Type>, 'params'> &\n (keyof Params extends undefined\n ? {\n params?: Params;\n }\n : {\n params: Params;\n });\n\n/**\n * A JSON-RPC request object.\n */\nexport type JsonRpcRequest<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcRequestStruct, Params>;\n\nexport const JsonRpcNotificationStruct = omit(JsonRpcRequestStruct, ['id']);\n\n/**\n * A JSON-RPC notification object.\n */\nexport type JsonRpcNotification<Params extends JsonRpcParams = JsonRpcParams> =\n InferWithParams<typeof JsonRpcNotificationStruct, Params>;\n\n/**\n * Check if the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcNotification}\n * object.\n */\nexport function isJsonRpcNotification(\n value: unknown,\n): value is JsonRpcNotification {\n return is(value, JsonRpcNotificationStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcNotification} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcNotification} object.\n */\nexport function assertIsJsonRpcNotification(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcNotification {\n assertStruct(\n value,\n JsonRpcNotificationStruct,\n 'Invalid JSON-RPC notification',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcRequest} object.\n */\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n return is(value, JsonRpcRequestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcRequest} object.\n *\n * @param value - The JSON-RPC request or notification to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcRequest} object.\n */\nexport function assertIsJsonRpcRequest(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcRequest {\n assertStruct(\n value,\n JsonRpcRequestStruct,\n 'Invalid JSON-RPC request',\n ErrorWrapper,\n );\n}\n\nexport const PendingJsonRpcResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: optional(unknown()),\n error: optional(JsonRpcErrorStruct),\n});\n\n/**\n * A JSON-RPC response object that has not yet been resolved.\n */\nexport type PendingJsonRpcResponse<Result extends Json> = Omit<\n Infer<typeof PendingJsonRpcResponseStruct>,\n 'result'\n> & {\n result?: Result;\n};\n\nexport const JsonRpcSuccessStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: JsonStruct,\n});\n\n/**\n * A successful JSON-RPC response object.\n */\nexport type JsonRpcSuccess<Result extends Json> = Omit<\n Infer<typeof JsonRpcSuccessStruct>,\n 'result'\n> & {\n result: Result;\n};\n\nexport const JsonRpcFailureStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n error: JsonRpcErrorStruct as Struct<JsonRpcError>,\n});\n\n/**\n * A failed JSON-RPC response object.\n */\nexport type JsonRpcFailure = Infer<typeof JsonRpcFailureStruct>;\n\nexport const JsonRpcResponseStruct = union([\n JsonRpcSuccessStruct,\n JsonRpcFailureStruct,\n]);\n\n/**\n * A JSON-RPC response object. Must be checked to determine whether it's a\n * success or failure.\n *\n * @template Result - The type of the result.\n */\nexport type JsonRpcResponse<Result extends Json> =\n | JsonRpcSuccess<Result>\n | JsonRpcFailure;\n\n/**\n * Type guard to check whether specified JSON-RPC response is a\n * {@link PendingJsonRpcResponse}.\n *\n * @param response - The JSON-RPC response to check.\n * @returns Whether the specified JSON-RPC response is pending.\n */\nexport function isPendingJsonRpcResponse(\n response: unknown,\n): response is PendingJsonRpcResponse<Json> {\n return is(response, PendingJsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link PendingJsonRpcResponse} object.\n *\n * @param response - The JSON-RPC response to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link PendingJsonRpcResponse}\n * object.\n */\nexport function assertIsPendingJsonRpcResponse(\n response: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts response is PendingJsonRpcResponse<Json> {\n assertStruct(\n response,\n PendingJsonRpcResponseStruct,\n 'Invalid pending JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Type guard to check if a value is a {@link JsonRpcResponse}.\n *\n * @param response - The object to check.\n * @returns Whether the object is a JsonRpcResponse.\n */\nexport function isJsonRpcResponse(\n response: unknown,\n): response is JsonRpcResponse<Json> {\n return is(response, JsonRpcResponseStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcResponse} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcResponse} object.\n */\nexport function assertIsJsonRpcResponse(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcResponse<Json> {\n assertStruct(\n value,\n JsonRpcResponseStruct,\n 'Invalid JSON-RPC response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcSuccess} object.\n */\nexport function isJsonRpcSuccess(\n value: unknown,\n): value is JsonRpcSuccess<Json> {\n return is(value, JsonRpcSuccessStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcSuccess} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcSuccess} object.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcSuccess<Json> {\n assertStruct(\n value,\n JsonRpcSuccessStruct,\n 'Invalid JSON-RPC success response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcFailure} object.\n */\nexport function isJsonRpcFailure(value: unknown): value is JsonRpcFailure {\n return is(value, JsonRpcFailureStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcFailure} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcFailure} object.\n */\nexport function assertIsJsonRpcFailure(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcFailure {\n assertStruct(\n value,\n JsonRpcFailureStruct,\n 'Invalid JSON-RPC failure response',\n ErrorWrapper,\n );\n}\n\n/**\n * Check if the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @returns Whether the given value is a valid {@link JsonRpcError} object.\n */\nexport function isJsonRpcError(value: unknown): value is JsonRpcError {\n return is(value, JsonRpcErrorStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link JsonRpcError} object.\n *\n * @param value - The value to check.\n * @param ErrorWrapper - The error class to throw if the assertion fails.\n * Defaults to {@link AssertionError}.\n * @throws If the given value is not a valid {@link JsonRpcError} object.\n */\nexport function assertIsJsonRpcError(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is JsonRpcError {\n assertStruct(\n value,\n JsonRpcErrorStruct,\n 'Invalid JSON-RPC error',\n ErrorWrapper,\n );\n}\n\ntype JsonRpcValidatorOptions = {\n permitEmptyString?: boolean;\n permitFractions?: boolean;\n permitNull?: boolean;\n};\n\n/**\n * Gets a function for validating JSON-RPC request / response `id` values.\n *\n * By manipulating the options of this factory, you can control the behavior\n * of the resulting validator for some edge cases. This is useful because e.g.\n * `null` should sometimes but not always be permitted.\n *\n * Note that the empty string (`''`) is always permitted by the JSON-RPC\n * specification, but that kind of sucks and you may want to forbid it in some\n * instances anyway.\n *\n * For more details, see the\n * [JSON-RPC Specification](https://www.jsonrpc.org/specification).\n *\n * @param options - An options object.\n * @param options.permitEmptyString - Whether the empty string (i.e. `''`)\n * should be treated as a valid ID. Default: `true`\n * @param options.permitFractions - Whether fractional numbers (e.g. `1.2`)\n * should be treated as valid IDs. Default: `false`\n * @param options.permitNull - Whether `null` should be treated as a valid ID.\n * Default: `true`\n * @returns The JSON-RPC ID validator function.\n */\nexport function getJsonRpcIdValidator(options?: JsonRpcValidatorOptions) {\n const { permitEmptyString, permitFractions, permitNull } = {\n permitEmptyString: true,\n permitFractions: false,\n permitNull: true,\n ...options,\n };\n\n /**\n * Type guard for {@link JsonRpcId}.\n *\n * @param id - The JSON-RPC ID value to check.\n * @returns Whether the given ID is valid per the options given to the\n * factory.\n */\n const isValidJsonRpcId = (id: unknown): id is JsonRpcId => {\n return Boolean(\n (typeof id === 'number' && (permitFractions || Number.isInteger(id))) ||\n (typeof id === 'string' && (permitEmptyString || id.length > 0)) ||\n (permitNull && id === null),\n );\n };\n\n return isValidJsonRpcId;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/* eslint-disable @typescript-eslint/consistent-type-definitions */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
const tsd_1 = require("tsd");
|
|
5
|
+
// Valid Json:
|
|
6
|
+
(0, tsd_1.expectAssignable)(null);
|
|
7
|
+
(0, tsd_1.expectAssignable)(false);
|
|
8
|
+
(0, tsd_1.expectAssignable)('');
|
|
9
|
+
(0, tsd_1.expectAssignable)(0);
|
|
10
|
+
(0, tsd_1.expectAssignable)([]);
|
|
11
|
+
(0, tsd_1.expectAssignable)({});
|
|
12
|
+
(0, tsd_1.expectAssignable)([0]);
|
|
13
|
+
(0, tsd_1.expectAssignable)({ a: 0 });
|
|
14
|
+
(0, tsd_1.expectAssignable)({ deeply: [{ nested: 1 }, 'mixed', 'types', 0] });
|
|
15
|
+
(0, tsd_1.expectAssignable)(['array', { nested: { mixed: true, types: null } }, 0]);
|
|
16
|
+
const jsonCompatibleType = { c: 0 };
|
|
17
|
+
(0, tsd_1.expectAssignable)(jsonCompatibleType);
|
|
18
|
+
// Invalid Json:
|
|
19
|
+
(0, tsd_1.expectNotAssignable)(undefined);
|
|
20
|
+
(0, tsd_1.expectNotAssignable)(new Date());
|
|
21
|
+
(0, tsd_1.expectNotAssignable)(() => 0);
|
|
22
|
+
(0, tsd_1.expectNotAssignable)(new Set());
|
|
23
|
+
(0, tsd_1.expectNotAssignable)(new Map());
|
|
24
|
+
(0, tsd_1.expectNotAssignable)(Symbol('test'));
|
|
25
|
+
(0, tsd_1.expectNotAssignable)({ a: new Date() });
|
|
26
|
+
(0, tsd_1.expectNotAssignable)(5);
|
|
27
|
+
const interfaceWithOptionalProperty = { a: 0 };
|
|
28
|
+
(0, tsd_1.expectNotAssignable)(interfaceWithOptionalProperty);
|
|
29
|
+
const interfaceWithDate = { a: new Date() };
|
|
30
|
+
(0, tsd_1.expectNotAssignable)(interfaceWithDate);
|
|
31
|
+
const interfaceWithOptionalDate = { a: new Date() };
|
|
32
|
+
(0, tsd_1.expectNotAssignable)(interfaceWithOptionalDate);
|
|
33
|
+
const interfaceWithUndefinedTypeUnion = {
|
|
34
|
+
a: 0,
|
|
35
|
+
};
|
|
36
|
+
(0, tsd_1.expectNotAssignable)(interfaceWithUndefinedTypeUnion);
|
|
37
|
+
const interfaceWithFunction = { a: () => 0 };
|
|
38
|
+
(0, tsd_1.expectNotAssignable)(interfaceWithFunction);
|
|
39
|
+
const typeWithDate = { a: new Date() };
|
|
40
|
+
(0, tsd_1.expectNotAssignable)(typeWithDate);
|
|
41
|
+
const typeWithOptionalDate = { a: new Date() };
|
|
42
|
+
(0, tsd_1.expectNotAssignable)(typeWithOptionalDate);
|
|
43
|
+
const typeWithUndefinedTypeUnion = {
|
|
44
|
+
a: 0,
|
|
45
|
+
};
|
|
46
|
+
(0, tsd_1.expectNotAssignable)(typeWithUndefinedTypeUnion);
|
|
47
|
+
const typeWithFunction = { a: () => 0 };
|
|
48
|
+
(0, tsd_1.expectNotAssignable)(typeWithFunction);
|
|
49
|
+
const typeWithOptionalProperty = { a: undefined };
|
|
50
|
+
(0, tsd_1.expectNotAssignable)(typeWithOptionalProperty);
|
|
51
|
+
// Edge cases:
|
|
52
|
+
// The Json type doesn't protect against the `any` type.
|
|
53
|
+
(0, tsd_1.expectAssignable)(null);
|
|
54
|
+
const a = { a: 0 };
|
|
55
|
+
(0, tsd_1.expectNotAssignable)(a);
|
|
56
|
+
// The Json type gets confused by classes. This class instance is valid Json,
|
|
57
|
+
// but it's incompatible with the Json type.
|
|
58
|
+
class Foo {
|
|
59
|
+
}
|
|
60
|
+
const foo = new Foo();
|
|
61
|
+
(0, tsd_1.expectNotAssignable)(foo);
|
|
62
|
+
//# sourceMappingURL=json.test-d.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json.test-d.js","sourceRoot":"","sources":["../src/json.test-d.ts"],"names":[],"mappings":";AAAA,mEAAmE;;AAEnE,6BAA4D;AAI5D,cAAc;AAEd,IAAA,sBAAgB,EAAO,IAAI,CAAC,CAAC;AAE7B,IAAA,sBAAgB,EAAO,KAAK,CAAC,CAAC;AAE9B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAAO,CAAC,CAAC,CAAC;AAE1B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAAO,EAAE,CAAC,CAAC;AAE3B,IAAA,sBAAgB,EAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AAE5B,IAAA,sBAAgB,EAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAEjC,IAAA,sBAAgB,EAAO,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;AAEzE,IAAA,sBAAgB,EAAO,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AAK/E,MAAM,kBAAkB,GAAuB,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxD,IAAA,sBAAgB,EAAO,kBAAkB,CAAC,CAAC;AAE3C,gBAAgB;AAEhB,IAAA,yBAAmB,EAAO,SAAS,CAAC,CAAC;AAErC,IAAA,yBAAmB,EAAO,IAAI,IAAI,EAAE,CAAC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AM,0BAA0B,GAA+B;IAC7D,CAAC,EAAE,CAAC;CACL,CAAC;AACF,IAAA,yBAAmB,EAAO,0BAA0B,CAAC,CAAC;AAKtD,MAAM,gBAAgB,GAAqB,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC;AAC1D,IAAA,yBAAmB,EAAO,gBAAgB,CAAC,CAAC;AAK5C,MAAM,wBAAwB,GAA6B,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC;AAC5E,IAAA,yBAAmB,EAAO,wBAAwB,CAAC,CAAC;AAEpD,cAAc;AAEd,wDAAwD;AACxD,IAAA,sBAAgB,EAAO,IAAW,CAAC,CAAC;AAOpC,MAAM,CAAC,GAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACtB,IAAA,yBAAmB,EAAO,CAAC,CAAC,CAAC;AAE7B,6EAA6E;AAC7E,4CAA4C;AAC5C,MAAM,GAAG;CAER;AACD,MAAM,GAAG,GAAG,IAAI,GAAG,EAAE,CAAC;AACtB,IAAA,yBAAmB,EAAO,GAAG,CAAC,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/consistent-type-definitions */\n\nimport { expectAssignable, expectNotAssignable } from 'tsd';\n\nimport type { Json } from '.';\n\n// Valid Json:\n\nexpectAssignable<Json>(null);\n\nexpectAssignable<Json>(false);\n\nexpectAssignable<Json>('');\n\nexpectAssignable<Json>(0);\n\nexpectAssignable<Json>([]);\n\nexpectAssignable<Json>({});\n\nexpectAssignable<Json>([0]);\n\nexpectAssignable<Json>({ a: 0 });\n\nexpectAssignable<Json>({ deeply: [{ nested: 1 }, 'mixed', 'types', 0] });\n\nexpectAssignable<Json>(['array', { nested: { mixed: true, types: null } }, 0]);\n\ntype JsonCompatibleType = {\n c: number;\n};\nconst jsonCompatibleType: JsonCompatibleType = { c: 0 };\nexpectAssignable<Json>(jsonCompatibleType);\n\n// Invalid Json:\n\nexpectNotAssignable<Json>(undefined);\n\nexpectNotAssignable<Json>(new Date());\n\nexpectNotAssignable<Json>(() => 0);\n\nexpectNotAssignable<Json>(new Set());\n\nexpectNotAssignable<Json>(new Map());\n\nexpectNotAssignable<Json>(Symbol('test'));\n\nexpectNotAssignable<Json>({ a: new Date() });\n\nexpectNotAssignable<Json>(5 as number | undefined);\n\ninterface InterfaceWithOptionalProperty {\n a?: number;\n}\nconst interfaceWithOptionalProperty: InterfaceWithOptionalProperty = { a: 0 };\nexpectNotAssignable<Json>(interfaceWithOptionalProperty);\n\ninterface InterfaceWithDate {\n a: Date;\n}\nconst interfaceWithDate: InterfaceWithDate = { a: new Date() };\nexpectNotAssignable<Json>(interfaceWithDate);\n\ninterface InterfaceWithOptionalDate {\n a?: Date;\n}\nconst interfaceWithOptionalDate: InterfaceWithOptionalDate = { a: new Date() };\nexpectNotAssignable<Json>(interfaceWithOptionalDate);\n\ninterface InterfaceWithUndefinedTypeUnion {\n a: number | undefined;\n}\nconst interfaceWithUndefinedTypeUnion: InterfaceWithUndefinedTypeUnion = {\n a: 0,\n};\nexpectNotAssignable<Json>(interfaceWithUndefinedTypeUnion);\n\ninterface InterfaceWithFunction {\n a: () => number;\n}\nconst interfaceWithFunction: InterfaceWithFunction = { a: () => 0 };\nexpectNotAssignable<Json>(interfaceWithFunction);\n\ntype TypeWithDate = {\n a: Date;\n};\nconst typeWithDate: TypeWithDate = { a: new Date() };\nexpectNotAssignable<Json>(typeWithDate);\n\ntype TypeWithOptionalDate = {\n a?: Date;\n};\nconst typeWithOptionalDate: TypeWithOptionalDate = { a: new Date() };\nexpectNotAssignable<Json>(typeWithOptionalDate);\n\ntype TypeWithUndefinedTypeUnion = {\n a: number | undefined;\n};\nconst typeWithUndefinedTypeUnion: TypeWithUndefinedTypeUnion = {\n a: 0,\n};\nexpectNotAssignable<Json>(typeWithUndefinedTypeUnion);\n\ntype TypeWithFunction = {\n a: () => number;\n};\nconst typeWithFunction: TypeWithFunction = { a: () => 0 };\nexpectNotAssignable<Json>(typeWithFunction);\n\ntype TypeWithOptionalProperty = {\n a?: number | undefined;\n};\nconst typeWithOptionalProperty: TypeWithOptionalProperty = { a: undefined };\nexpectNotAssignable<Json>(typeWithOptionalProperty);\n\n// Edge cases:\n\n// The Json type doesn't protect against the `any` type.\nexpectAssignable<Json>(null as any);\n\n// The Json type gets confused by interfaces. This interface is valid Json,\n// but it's incompatible with the Json type.\ninterface A {\n a: number;\n}\nconst a: A = { a: 0 };\nexpectNotAssignable<Json>(a);\n\n// The Json type gets confused by classes. This class instance is valid Json,\n// but it's incompatible with the Json type.\nclass Foo {\n a!: number;\n}\nconst foo = new Foo();\nexpectNotAssignable<Json>(foo);\n"]}
|
package/dist/misc.js
CHANGED
|
@@ -111,7 +111,6 @@ exports.isASCII = isASCII;
|
|
|
111
111
|
* @returns Number of bytes used to store whole string value.
|
|
112
112
|
*/
|
|
113
113
|
function calculateStringSize(value) {
|
|
114
|
-
var _a;
|
|
115
114
|
const size = value.split('').reduce((total, character) => {
|
|
116
115
|
if (isASCII(character)) {
|
|
117
116
|
return total + 1;
|
|
@@ -119,7 +118,7 @@ function calculateStringSize(value) {
|
|
|
119
118
|
return total + 2;
|
|
120
119
|
}, 0);
|
|
121
120
|
// Also detect characters that need backslash escape
|
|
122
|
-
return size + (
|
|
121
|
+
return size + (value.match(exports.ESCAPE_CHARACTERS_REGEXP) ?? []).length;
|
|
123
122
|
}
|
|
124
123
|
exports.calculateStringSize = calculateStringSize;
|
|
125
124
|
/**
|
package/dist/misc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"misc.js","sourceRoot":"","sources":["../src/misc.ts"],"names":[],"mappings":";AAAA,EAAE;AACF,QAAQ;AACR,EAAE;;;AAoCF,EAAE;AACF,cAAc;AACd,EAAE;AAEF;;;;;;GAMG;AACH,SAAgB,eAAe,CAC7B,KAAgB;IAEhB,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAClD,CAAC;AAJD,0C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AG,CAAC,KAAK,CAAC,KAAK,CAAC,gCAAwB,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;AACrE,CAAC;AAVD,kDAUC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CAAC,KAAa;IAC/C,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC;AACjC,CAAC;AAFD,kDAEC","sourcesContent":["//\n// Types\n//\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template ObjectValue - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n ObjectValue extends Record<string, unknown>,\n TargetKey extends keyof ObjectValue,\n> = {\n -readonly [Key in keyof Pick<ObjectValue, TargetKey>]: ObjectValue[Key];\n} & {\n [Key in keyof Omit<ObjectValue, TargetKey>]: ObjectValue[Key];\n};\n\n/**\n * Useful for representing some value that _might_ be present and / or complete.\n *\n * @template Value - The value that might be present or complete.\n */\nexport type PartialOrAbsent<Value> = Partial<Value> | null | undefined;\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template Element - The non-empty array member type.\n */\nexport type NonEmptyArray<Element> = [Element, ...Element[]];\n\n/**\n * A JavaScript object that is not `null`, a function, or an array.\n */\nexport type RuntimeObject = Record<PropertyKey, unknown>;\n\n//\n// Type Guards\n//\n\n/**\n * A {@link NonEmptyArray} type guard.\n *\n * @template Element - The non-empty array member type.\n * @param value - The value to check.\n * @returns Whether the value is a non-empty array.\n */\nexport function isNonEmptyArray<Element>(\n value: Element[],\n): value is NonEmptyArray<Element> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for \"nullishness\".\n *\n * @param value - Any value.\n * @returns `true` if the value is null or undefined, `false` otherwise.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * A type guard for {@link RuntimeObject}.\n *\n * @param value - The value to check.\n * @returns Whether the specified value has a runtime type of `object` and is\n * neither `null` nor an `Array`.\n */\nexport function isObject(value: unknown): value is RuntimeObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n//\n// Other utility functions\n//\n\n/**\n * A type guard for ensuring an object has a property.\n *\n * @param objectToCheck - The object to check.\n * @param name - The property name to check for.\n * @returns Whether the specified object has an own property with the specified\n * name, regardless of whether it is enumerable or not.\n */\nexport const hasProperty = <\n // eslint-disable-next-line @typescript-eslint/ban-types\n ObjectToCheck extends Object,\n Property extends PropertyKey,\n>(\n objectToCheck: ObjectToCheck,\n name: Property,\n): objectToCheck is ObjectToCheck &\n Record<\n Property,\n Property extends keyof ObjectToCheck ? ObjectToCheck[Property] : unknown\n > => Object.hasOwnProperty.call(objectToCheck, name);\n\nexport type PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Predefined sizes (in Bytes) of specific parts of JSON structure.\n */\nexport enum JsonSize {\n Null = 4,\n Comma = 1,\n Wrapper = 1,\n True = 4,\n False = 5,\n Quote = 1,\n Colon = 1,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Date = 24,\n}\n\n/**\n * Regular expression with pattern matching for (special) escaped characters.\n */\nexport const ESCAPE_CHARACTERS_REGEXP = /\"|\\\\|\\n|\\r|\\t/gu;\n\n/**\n * Check if the value is plain object.\n *\n * @param value - Value to be checked.\n * @returns True if an object is the plain JavaScript object,\n * false if the object is not plain (e.g. function).\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n try {\n let proto = value;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(value) === proto;\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Check if character is ASCII.\n *\n * @param character - Character.\n * @returns True if a character code is ASCII, false if not.\n */\nexport function isASCII(character: string) {\n return character.charCodeAt(0) <= 127;\n}\n\n/**\n * Calculate string size.\n *\n * @param value - String value to calculate size.\n * @returns Number of bytes used to store whole string value.\n */\nexport function calculateStringSize(value: string): number {\n const size = value.split('').reduce((total, character) => {\n if (isASCII(character)) {\n return total + 1;\n }\n return total + 2;\n }, 0);\n\n // Also detect characters that need backslash escape\n return size + (value.match(ESCAPE_CHARACTERS_REGEXP) ?? []).length;\n}\n\n/**\n * Calculate size of a number ofter JSON serialization.\n *\n * @param value - Number value to calculate size.\n * @returns Number of bytes used to store whole number in JSON.\n */\nexport function calculateNumberSize(value: number): number {\n return value.toString().length;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const tsd_1 = require("tsd");
|
|
4
|
+
const misc_1 = require("./misc");
|
|
5
|
+
//=============================================================================
|
|
6
|
+
// isObject
|
|
7
|
+
//=============================================================================
|
|
8
|
+
// eslint-disable-next-line @typescript-eslint/ban-types
|
|
9
|
+
const unknownValue = {};
|
|
10
|
+
(0, tsd_1.expectNotAssignable)(unknownValue);
|
|
11
|
+
if ((0, misc_1.isObject)(unknownValue)) {
|
|
12
|
+
(0, tsd_1.expectAssignable)(unknownValue);
|
|
13
|
+
}
|
|
14
|
+
// Does not interfere with satisfaction of static type
|
|
15
|
+
const constObjectType = { foo: 'foo' };
|
|
16
|
+
if ((0, misc_1.hasProperty)(constObjectType, 'foo')) {
|
|
17
|
+
(0, tsd_1.expectAssignable)(constObjectType);
|
|
18
|
+
}
|
|
19
|
+
//=============================================================================
|
|
20
|
+
// hasProperty
|
|
21
|
+
//=============================================================================
|
|
22
|
+
// eslint-disable-next-line @typescript-eslint/ban-types
|
|
23
|
+
const unknownObject = {};
|
|
24
|
+
// Establish that `Object` is not accepted when a specific property is needed.
|
|
25
|
+
(0, tsd_1.expectNotAssignable)(unknownObject);
|
|
26
|
+
// Establish that `RuntimeObject` is not accepted when a specific property is needed.
|
|
27
|
+
if ((0, misc_1.isObject)(unknownObject)) {
|
|
28
|
+
(0, tsd_1.expectNotAssignable)(unknownObject);
|
|
29
|
+
}
|
|
30
|
+
// An object is accepted after `hasProperty` is used to prove that it has the required property.
|
|
31
|
+
if ((0, misc_1.isObject)(unknownObject) && (0, misc_1.hasProperty)(unknownObject, 'foo')) {
|
|
32
|
+
(0, tsd_1.expectAssignable)(unknownObject);
|
|
33
|
+
}
|
|
34
|
+
// An object is accepted after `hasProperty` is used to prove that it has all required properties.
|
|
35
|
+
if ((0, misc_1.isObject)(unknownObject) &&
|
|
36
|
+
(0, misc_1.hasProperty)(unknownObject, 'foo') &&
|
|
37
|
+
(0, misc_1.hasProperty)(unknownObject, 'bar')) {
|
|
38
|
+
(0, tsd_1.expectAssignable)(unknownObject);
|
|
39
|
+
}
|
|
40
|
+
// An object is not accepted after `hasProperty` has only been used to establish that some required properties exist.
|
|
41
|
+
if ((0, misc_1.isObject)(unknownObject) && (0, misc_1.hasProperty)(unknownObject, 'foo')) {
|
|
42
|
+
(0, tsd_1.expectNotAssignable)(unknownObject);
|
|
43
|
+
}
|
|
44
|
+
// Does not interfere with satisfaction of non-overlapping types
|
|
45
|
+
const overlappingTypesExample = { foo: 'foo', baz: 'baz' };
|
|
46
|
+
if ((0, misc_1.hasProperty)(overlappingTypesExample, 'foo')) {
|
|
47
|
+
(0, tsd_1.expectAssignable)(overlappingTypesExample);
|
|
48
|
+
}
|
|
49
|
+
const exampleErrorWithCode = new Error('test');
|
|
50
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
51
|
+
// @ts-ignore
|
|
52
|
+
exampleErrorWithCode.code = 999;
|
|
53
|
+
// Establish that trying to check for a custom property on an error results in failure
|
|
54
|
+
(0, tsd_1.expectNotAssignable)(exampleErrorWithCode);
|
|
55
|
+
// Using custom Error property is allowed after checking with `hasProperty`
|
|
56
|
+
if ((0, misc_1.hasProperty)(exampleErrorWithCode, 'code')) {
|
|
57
|
+
(0, tsd_1.expectType)(exampleErrorWithCode.code);
|
|
58
|
+
}
|
|
59
|
+
const hasPropertyInterfaceExample = { a: 0 };
|
|
60
|
+
(0, misc_1.hasProperty)(hasPropertyInterfaceExample, 'a');
|
|
61
|
+
// `hasProperty` is compatible with classes
|
|
62
|
+
class HasPropertyClassExample {
|
|
63
|
+
}
|
|
64
|
+
const hasPropertyClassExample = new HasPropertyClassExample();
|
|
65
|
+
(0, misc_1.hasProperty)(hasPropertyClassExample, 'a');
|
|
66
|
+
// It keeps the original type when defined.
|
|
67
|
+
const hasPropertyTypeExample = {};
|
|
68
|
+
if ((0, misc_1.hasProperty)(hasPropertyTypeExample, 'a')) {
|
|
69
|
+
(0, tsd_1.expectType)(hasPropertyTypeExample.a);
|
|
70
|
+
}
|
|
71
|
+
//=============================================================================
|
|
72
|
+
// RuntimeObject
|
|
73
|
+
//=============================================================================
|
|
74
|
+
// Valid runtime objects:
|
|
75
|
+
(0, tsd_1.expectAssignable)({});
|
|
76
|
+
(0, tsd_1.expectAssignable)({ foo: 'foo' });
|
|
77
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
78
|
+
(0, tsd_1.expectAssignable)({ 0: 'foo' });
|
|
79
|
+
(0, tsd_1.expectAssignable)({ [Symbol('foo')]: 'foo' });
|
|
80
|
+
// Invalid runtime objects:
|
|
81
|
+
(0, tsd_1.expectNotAssignable)(null);
|
|
82
|
+
(0, tsd_1.expectNotAssignable)(undefined);
|
|
83
|
+
(0, tsd_1.expectNotAssignable)('foo');
|
|
84
|
+
(0, tsd_1.expectNotAssignable)(0);
|
|
85
|
+
(0, tsd_1.expectNotAssignable)([]);
|
|
86
|
+
(0, tsd_1.expectNotAssignable)(new Date());
|
|
87
|
+
(0, tsd_1.expectNotAssignable)(() => 0);
|
|
88
|
+
(0, tsd_1.expectNotAssignable)(new Set());
|
|
89
|
+
(0, tsd_1.expectNotAssignable)(new Map());
|
|
90
|
+
(0, tsd_1.expectNotAssignable)(Symbol('test'));
|
|
91
|
+
const runtimeObjectInterfaceExample = { a: 0 };
|
|
92
|
+
(0, tsd_1.expectNotAssignable)(runtimeObjectInterfaceExample);
|
|
93
|
+
class RuntimeObjectClassExample {
|
|
94
|
+
}
|
|
95
|
+
const runtimeObjectClassExample = new RuntimeObjectClassExample();
|
|
96
|
+
(0, tsd_1.expectNotAssignable)(runtimeObjectClassExample);
|
|
97
|
+
//# sourceMappingURL=misc.test-d.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"misc.test-d.js","sourceRoot":"","sources":["../src/misc.test-d.ts"],"names":[],"mappings":";;AAAA,6BAAwE;AAExE,iCAA8D;AAE9D,+EAA+E;AAC/E,WAAW;AACX,+EAA+E;AAE/E,wDAAwD;AACxD,MAAM,YAAY,GAAG,EAAa,CAAC;AAEnC,IAAA,yBAAmB,EAAgB,YAAY,CAAC,CAAC;AAEjD,IAAI,IAAA,eAAQ,EAAC,YAAY,CAAC,EAAE;IAC1B,IAAA,sBAAgB,EAAgB,YAAY,CAAC,CAAC;CAC/C;AAED,sDAAsD;AACtD,MAAM,eAAe,GAAG,EAAE,GAAG,EAAE,KAAK,EAAW,CAAC;AAChD,IAAI,IAAA,kBAAW,EAAC,eAAe,EAAE,KAAK,CAAC,EAAE;IACvC,IAAA,sBAAgB,EAAiB,eAAe,CAAC,CAAC;CACnD;AAED,+EAA+E;AAC/E,cAAc;AACd,+EAA+E;AAE/E,wDAAwD;AACxD,MAAM,aAAa,GAAG,EAAY,CAAC;AAEnC,8EAA8E;AAC9E,IAAA,yBAAmB,EAAyB,aAAa,CAAC,CAAC;AAE3D,qFAAqF;AACrF,IAAI,IAAA,eAAQ,EAAC,aAAa,CAAC,EAAE;IAC3B,IAAA,yBAAmB,EAAyB,aAAa,CAAC,CAAC;CAC5D;AAED,gGAAgG;AAChG,IAAI,IAAA,eAAQ,EAAC,aAAa,CAAC,IAAI,IAAA,kBAAW,EAAC,aAAa,EAAE,KAAK,CAAC,EAAE;IAChE,IAAA,sBAAgB,EAAyB,aAAa,CAAC,CAAC;CACzD;AAED,kGAAkG;AAClG,IACE,IA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,IAAI,yBAAyB,EAAE,CAAC;AAClE,IAAA,yBAAmB,EAAgB,yBAAyB,CAAC,CAAC","sourcesContent":["import { expectAssignable, expectNotAssignable, expectType } from 'tsd';\n\nimport { isObject, hasProperty, RuntimeObject } from './misc';\n\n//=============================================================================\n// isObject\n//=============================================================================\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nconst unknownValue = {} as unknown;\n\nexpectNotAssignable<RuntimeObject>(unknownValue);\n\nif (isObject(unknownValue)) {\n expectAssignable<RuntimeObject>(unknownValue);\n}\n\n// Does not interfere with satisfaction of static type\nconst constObjectType = { foo: 'foo' } as const;\nif (hasProperty(constObjectType, 'foo')) {\n expectAssignable<{ foo: 'foo' }>(constObjectType);\n}\n\n//=============================================================================\n// hasProperty\n//=============================================================================\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nconst unknownObject = {} as Object;\n\n// Establish that `Object` is not accepted when a specific property is needed.\nexpectNotAssignable<Record<'foo', unknown>>(unknownObject);\n\n// Establish that `RuntimeObject` is not accepted when a specific property is needed.\nif (isObject(unknownObject)) {\n expectNotAssignable<Record<'foo', unknown>>(unknownObject);\n}\n\n// An object is accepted after `hasProperty` is used to prove that it has the required property.\nif (isObject(unknownObject) && hasProperty(unknownObject, 'foo')) {\n expectAssignable<Record<'foo', unknown>>(unknownObject);\n}\n\n// An object is accepted after `hasProperty` is used to prove that it has all required properties.\nif (\n isObject(unknownObject) &&\n hasProperty(unknownObject, 'foo') &&\n hasProperty(unknownObject, 'bar')\n) {\n expectAssignable<Record<'foo' | 'bar', unknown>>(unknownObject);\n}\n\n// An object is not accepted after `hasProperty` has only been used to establish that some required properties exist.\nif (isObject(unknownObject) && hasProperty(unknownObject, 'foo')) {\n expectNotAssignable<Record<'foo' | 'bar', unknown>>(unknownObject);\n}\n\n// Does not interfere with satisfaction of non-overlapping types\nconst overlappingTypesExample = { foo: 'foo', baz: 'baz' };\nif (hasProperty(overlappingTypesExample, 'foo')) {\n expectAssignable<Record<'baz', unknown>>(overlappingTypesExample);\n}\n\nconst exampleErrorWithCode = new Error('test');\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nexampleErrorWithCode.code = 999;\n\n// Establish that trying to check for a custom property on an error results in failure\nexpectNotAssignable<{ code: any }>(exampleErrorWithCode);\n\n// Using custom Error property is allowed after checking with `hasProperty`\nif (hasProperty(exampleErrorWithCode, 'code')) {\n expectType<unknown>(exampleErrorWithCode.code);\n}\n\n// `hasProperty` is compatible with interfaces\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface HasPropertyInterfaceExample {\n a: number;\n}\nconst hasPropertyInterfaceExample: HasPropertyInterfaceExample = { a: 0 };\nhasProperty(hasPropertyInterfaceExample, 'a');\n\n// `hasProperty` is compatible with classes\nclass HasPropertyClassExample {\n a!: number;\n}\nconst hasPropertyClassExample = new HasPropertyClassExample();\nhasProperty(hasPropertyClassExample, 'a');\n\ntype HasPropertyTypeExample = {\n a?: number;\n};\n\n// It keeps the original type when defined.\nconst hasPropertyTypeExample: HasPropertyTypeExample = {};\nif (hasProperty(hasPropertyTypeExample, 'a')) {\n expectType<number | undefined>(hasPropertyTypeExample.a);\n}\n\n//=============================================================================\n// RuntimeObject\n//=============================================================================\n\n// Valid runtime objects:\n\nexpectAssignable<RuntimeObject>({});\n\nexpectAssignable<RuntimeObject>({ foo: 'foo' });\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexpectAssignable<RuntimeObject>({ 0: 'foo' });\n\nexpectAssignable<RuntimeObject>({ [Symbol('foo')]: 'foo' });\n\n// Invalid runtime objects:\n\nexpectNotAssignable<RuntimeObject>(null);\n\nexpectNotAssignable<RuntimeObject>(undefined);\n\nexpectNotAssignable<RuntimeObject>('foo');\n\nexpectNotAssignable<RuntimeObject>(0);\n\nexpectNotAssignable<RuntimeObject>([]);\n\nexpectNotAssignable<RuntimeObject>(new Date());\n\nexpectNotAssignable<RuntimeObject>(() => 0);\n\nexpectNotAssignable<RuntimeObject>(new Set());\n\nexpectNotAssignable<RuntimeObject>(new Map());\n\nexpectNotAssignable<RuntimeObject>(Symbol('test'));\n\n// The RuntimeObject type gets confused by interfaces. This interface is a valid object,\n// but it's incompatible with the RuntimeObject type.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RuntimeObjectInterfaceExample {\n a: number;\n}\nconst runtimeObjectInterfaceExample: RuntimeObjectInterfaceExample = { a: 0 };\nexpectNotAssignable<RuntimeObject>(runtimeObjectInterfaceExample);\n\nclass RuntimeObjectClassExample {\n a!: number;\n}\nconst runtimeObjectClassExample = new RuntimeObjectClassExample();\nexpectNotAssignable<RuntimeObject>(runtimeObjectClassExample);\n"]}
|
package/package.json
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/utils",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase
|
|
3
|
+
"version": "6.0.0",
|
|
4
|
+
"description": "Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase",
|
|
5
|
+
"homepage": "https://github.com/MetaMask/utils#readme",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/MetaMask/utils/issues"
|
|
8
|
+
},
|
|
5
9
|
"repository": {
|
|
6
10
|
"type": "git",
|
|
7
11
|
"url": "https://github.com/MetaMask/utils.git"
|
|
8
12
|
},
|
|
9
13
|
"license": "ISC",
|
|
10
|
-
"main": "dist/index.js",
|
|
11
|
-
"types": "dist/index.d.ts",
|
|
14
|
+
"main": "./dist/index.js",
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
12
16
|
"files": [
|
|
13
17
|
"dist/"
|
|
14
18
|
],
|
|
@@ -16,13 +20,16 @@
|
|
|
16
20
|
"build": "tsc --project tsconfig.build.json",
|
|
17
21
|
"build:clean": "rimraf dist && yarn build",
|
|
18
22
|
"build:docs": "typedoc",
|
|
19
|
-
"lint": "yarn lint:eslint && yarn lint:misc --check",
|
|
23
|
+
"lint": "yarn lint:eslint && yarn lint:misc --check && yarn lint:dependencies --check && yarn lint:changelog && yarn lint:constraints",
|
|
24
|
+
"lint:changelog": "auto-changelog validate",
|
|
25
|
+
"lint:constraints": "yarn constraints",
|
|
26
|
+
"lint:dependencies": "depcheck && yarn dedupe",
|
|
20
27
|
"lint:eslint": "eslint . --cache --ext js,ts",
|
|
21
|
-
"lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write",
|
|
28
|
+
"lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write && yarn lint:dependencies && yarn lint:changelog && yarn lint:constraints --fix",
|
|
22
29
|
"lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore --no-error-on-unmatched-pattern",
|
|
23
30
|
"prepack": "./scripts/prepack.sh",
|
|
24
31
|
"test": "yarn test:source && yarn test:types",
|
|
25
|
-
"test:source": "jest",
|
|
32
|
+
"test:source": "jest && jest-it-up",
|
|
26
33
|
"test:types": "tsd",
|
|
27
34
|
"test:watch": "jest --watch"
|
|
28
35
|
},
|
|
@@ -38,14 +45,17 @@
|
|
|
38
45
|
},
|
|
39
46
|
"devDependencies": {
|
|
40
47
|
"@lavamoat/allow-scripts": "^2.0.3",
|
|
41
|
-
"@
|
|
48
|
+
"@lavamoat/preinstall-always-fail": "^1.0.0",
|
|
49
|
+
"@metamask/auto-changelog": "^3.1.0",
|
|
42
50
|
"@metamask/eslint-config": "^11.0.1",
|
|
43
51
|
"@metamask/eslint-config-jest": "^11.0.0",
|
|
44
52
|
"@metamask/eslint-config-nodejs": "^11.0.1",
|
|
45
53
|
"@metamask/eslint-config-typescript": "^11.0.0",
|
|
46
54
|
"@types/jest": "^28.1.7",
|
|
47
|
-
"@
|
|
48
|
-
"@typescript-eslint/
|
|
55
|
+
"@types/node": "^17.0.23",
|
|
56
|
+
"@typescript-eslint/eslint-plugin": "^5.43.0",
|
|
57
|
+
"@typescript-eslint/parser": "^5.43.0",
|
|
58
|
+
"depcheck": "^1.4.3",
|
|
49
59
|
"eslint": "^8.27.0",
|
|
50
60
|
"eslint-config-prettier": "^8.5.0",
|
|
51
61
|
"eslint-plugin-import": "^2.26.0",
|
|
@@ -54,19 +64,20 @@
|
|
|
54
64
|
"eslint-plugin-node": "^11.1.0",
|
|
55
65
|
"eslint-plugin-prettier": "^4.2.1",
|
|
56
66
|
"jest": "^29.2.2",
|
|
57
|
-
"
|
|
67
|
+
"jest-it-up": "^2.0.2",
|
|
58
68
|
"prettier": "^2.7.1",
|
|
59
|
-
"prettier-plugin-packagejson": "^2.
|
|
69
|
+
"prettier-plugin-packagejson": "^2.3.0",
|
|
60
70
|
"rimraf": "^3.0.2",
|
|
61
71
|
"stdio-mock": "^1.2.0",
|
|
62
72
|
"ts-jest": "^29.0.3",
|
|
73
|
+
"ts-node": "^10.7.0",
|
|
63
74
|
"tsd": "^0.24.1",
|
|
64
|
-
"typedoc": "^0.23.
|
|
75
|
+
"typedoc": "^0.23.15",
|
|
65
76
|
"typescript": "~4.8.4"
|
|
66
77
|
},
|
|
67
78
|
"packageManager": "yarn@3.2.3",
|
|
68
79
|
"engines": {
|
|
69
|
-
"node": ">=
|
|
80
|
+
"node": ">=16.0.0"
|
|
70
81
|
},
|
|
71
82
|
"publishConfig": {
|
|
72
83
|
"access": "public",
|