@metamask/snaps-utils 3.3.0 → 4.0.1
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 +34 -1
- package/dist/cjs/auxiliary-files.js +6 -19
- package/dist/cjs/auxiliary-files.js.map +1 -1
- package/dist/cjs/checksum.js +22 -5
- package/dist/cjs/checksum.js.map +1 -1
- package/dist/cjs/cronjob.js.map +1 -1
- package/dist/cjs/enum.js.map +1 -1
- package/dist/cjs/errors.js +6 -154
- package/dist/cjs/errors.js.map +1 -1
- package/dist/cjs/handlers.js +6 -13
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/index.browser.js +1 -0
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.js +1 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/localization.js +2 -2
- package/dist/cjs/localization.js.map +1 -1
- package/dist/cjs/manifest/manifest.js +11 -11
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/namespace.js +5 -1
- package/dist/cjs/namespace.js.map +1 -1
- package/dist/cjs/npm.js +2 -2
- package/dist/cjs/npm.js.map +1 -1
- package/dist/cjs/snaps.js +7 -6
- package/dist/cjs/snaps.js.map +1 -1
- package/dist/cjs/structs.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/ui.js +53 -0
- package/dist/cjs/ui.js.map +1 -0
- package/dist/cjs/validation.js +2 -2
- package/dist/cjs/validation.js.map +1 -1
- package/dist/esm/auxiliary-files.js +1 -6
- package/dist/esm/auxiliary-files.js.map +1 -1
- package/dist/esm/checksum.js +25 -6
- package/dist/esm/checksum.js.map +1 -1
- package/dist/esm/cronjob.js +1 -1
- package/dist/esm/cronjob.js.map +1 -1
- package/dist/esm/enum.js.map +1 -1
- package/dist/esm/errors.js +2 -157
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/handlers.js +4 -8
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/index.browser.js +1 -0
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/localization.js +1 -1
- package/dist/esm/localization.js.map +1 -1
- package/dist/esm/manifest/manifest.js +8 -8
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/namespace.js +3 -2
- package/dist/esm/namespace.js.map +1 -1
- package/dist/esm/npm.js +2 -2
- package/dist/esm/npm.js.map +1 -1
- package/dist/esm/snaps.js +7 -6
- package/dist/esm/snaps.js.map +1 -1
- package/dist/esm/structs.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/ui.js +50 -0
- package/dist/esm/ui.js.map +1 -0
- package/dist/esm/validation.js +2 -2
- package/dist/esm/validation.js.map +1 -1
- package/dist/types/auxiliary-files.d.ts +1 -5
- package/dist/types/checksum.d.ts +9 -2
- package/dist/types/enum.d.ts +1 -21
- package/dist/types/errors.d.ts +1 -109
- package/dist/types/handlers.d.ts +48 -173
- package/dist/types/index.browser.d.ts +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/localization.d.ts +22 -22
- package/dist/types/manifest/manifest.d.ts +2 -2
- package/dist/types/manifest/validation.d.ts +80 -78
- package/dist/types/namespace.d.ts +11 -10
- package/dist/types/npm.d.ts +1 -1
- package/dist/types/snaps.d.ts +8 -43
- package/dist/types/structs.d.ts +23 -0
- package/dist/types/types.d.ts +0 -1
- package/dist/types/ui.d.ts +20 -0
- package/dist/types/validation.d.ts +1 -1
- package/package.json +3 -3
package/dist/cjs/structs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["literal","union","file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","value","define","JSON","stringify","superstructLiteral","validator","head","tail","struct","superstructUnion","Struct","schema","coerce","string","resolve","process","cwd","name","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","Array","isArray","map","green","length","bold","join","received","red","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAuCgBA,OAAO;eAAPA;;IAmBAC,KAAK;eAALA;;IAkCAC,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBA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ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["literal","union","file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","value","define","JSON","stringify","superstructLiteral","validator","head","tail","struct","superstructUnion","Struct","schema","coerce","string","resolve","process","cwd","name","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","Array","isArray","map","green","length","bold","join","received","red","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAkEgBA,OAAO;eAAPA;;IAmBAC,KAAK;eAALA;;IAkCAC,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBAC,oBAAoB;eAApBA;;IAiBAC,uBAAuB;eAAvBA;;IAiDAC,qBAAqB;eAArBA;;;uBAzVS;uBACQ;sBACT;6BAWjB;yBAGgB;AAkDhB,SAASZ,QAAgDa,KAAW;IACzE,OAAOC,IAAAA,mBAAM,EACXC,KAAKC,SAAS,CAACH,QACfI,IAAAA,oBAAkB,EAACJ,OAAOK,SAAS;AAEvC;AAcO,SAASjB,MAAwD,CACtEkB,MACA,GAAGC,KACyB;IAI5B,MAAMC,SAASC,IAAAA,kBAAgB,EAAC;QAACH;WAASC;KAAK;IAE/C,OAAO,IAAIG,mBAAM,CAAC;QAChB,GAAGF,MAAM;QACTG,QAAQ;YAACL;eAASC;SAAK;IACzB;AACF;AAqBO,SAASlB;IACd,OAAOuB,IAAAA,mBAAM,EAACC,IAAAA,mBAAM,KAAIA,IAAAA,mBAAM,KAAI,CAACb;QACjC,OAAOc,IAAAA,aAAO,EAACC,QAAQC,GAAG,IAAIhB;IAChC;AACF;AAWO,SAASV,MACd2B,IAAY,EACZT,MAA4B;IAE5B,OAAO,IAAIE,mBAAM,CAAC;QAChB,GAAGF,MAAM;QACTU,MAAMD;IACR;AACF;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5B,OAAO,CAAC,aAAa,EAAEsB,IAAAA,WAAI,EACzBjB,QAAQO,IAAI,CAACW,IAAI,CAAC,MAClB,YAAY,EAAEC,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAErB,OAAO,yBAAyB,EAAEiB,IAAAA,YAAK,EAC/Cf,QAAQL,IAAI,EACZ,gBAAgB,EAAEwB,SAAS,CAAC,CAAC;AACjC;AAUO,SAAS3C,sBACdS,MAA4B,EAC5BgB,QAAmB;IAEnB,MAAMuB,oBAAoBvB,SAASa,GAAG,CAAC,CAACd,UACtCyB,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAElD,wBAAwBU,QAAQe,SAAS,CAAC;IAGxD,OAAOwB,kBAAkBN,IAAI,CAAC;AAChC"}
|
package/dist/cjs/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile<LocalizationFile>[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles' | 'localizationFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\
|
|
1
|
+
{"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile<LocalizationFile>[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles' | 'localizationFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["NameStruct","NpmSnapPackageJsonStruct","isNpmSnapPackageJson","assertIsNpmSnapPackageJson","uri","isValidUrl","WALLET_SNAP_PERMISSION_KEY","NpmSnapFileNames","PackageJson","Manifest","size","pattern","string","type","version","VersionStruct","name","main","optional","Infinity","repository","object","url","value","is","assertStruct","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","opts","refine","union","instance","URL","UrlStruct","assertSuperstruct","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;IA4BaA,UAAU;eAAVA;;IAWAC,wBAAwB;eAAxBA;;IAqBGC,oBAAoB;eAApBA;;IAYAC,0BAA0B;eAA1BA;;IAyFHC,GAAG;eAAHA;;IAoBGC,UAAU;eAAVA;;IAQHC,0BAA0B;eAA1BA;;;uBA5L+B;6BAcrC;IAQA;UAAKC,gBAAgB;IAAhBA,iBACVC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7B,IAAAA,iBAAI,EAACwB;YACvBM,IAAAA,mBAAiB,EAACrB,KAAKoB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEnB,MAAMqB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF;AASK,SAASvC,WACdiB,GAAY,EACZe,OAAwB,CAAC,CAAC;IAE1B,OAAOb,IAAAA,eAAE,EAACF,KAAKlB,IAAIiC;AACrB;AAGO,MAAM/B,6BAA6B"}
|
package/dist/cjs/ui.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
validateTextLinks: function() {
|
|
13
|
+
return validateTextLinks;
|
|
14
|
+
},
|
|
15
|
+
validateComponentLinks: function() {
|
|
16
|
+
return validateComponentLinks;
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
const _snapssdk = require("@metamask/snaps-sdk");
|
|
20
|
+
const _utils = require("@metamask/utils");
|
|
21
|
+
const MARKDOWN_LINK_REGEX = RegExp("\\[(?<name>[^\\]]*)\\]\\((?<url>[^)]+)\\)", "giu");
|
|
22
|
+
const ALLOWED_PROTOCOLS = [
|
|
23
|
+
'https:',
|
|
24
|
+
'mailto:'
|
|
25
|
+
];
|
|
26
|
+
function validateTextLinks(text, isOnPhishingList) {
|
|
27
|
+
const matches = String.prototype.matchAll.call(text, MARKDOWN_LINK_REGEX);
|
|
28
|
+
for (const { groups } of matches){
|
|
29
|
+
const link = groups?.url;
|
|
30
|
+
/* This case should never happen with the regex but the TS type allows for undefined */ /* istanbul ignore next */ if (!link) {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
const url = new URL(link);
|
|
35
|
+
(0, _utils.assert)(ALLOWED_PROTOCOLS.includes(url.protocol), `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`);
|
|
36
|
+
const hostname = url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;
|
|
37
|
+
(0, _utils.assert)(!isOnPhishingList(hostname), 'The specified URL is not allowed.');
|
|
38
|
+
} catch (error) {
|
|
39
|
+
throw new Error(`Invalid URL: ${error instanceof _utils.AssertionError ? error.message : 'Unable to parse URL.'}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function validateComponentLinks(component, isOnPhishingList) {
|
|
44
|
+
const { type } = component;
|
|
45
|
+
if (type === _snapssdk.NodeType.Panel) {
|
|
46
|
+
component.children.forEach((node)=>validateComponentLinks(node, isOnPhishingList));
|
|
47
|
+
}
|
|
48
|
+
if (type === _snapssdk.NodeType.Text) {
|
|
49
|
+
validateTextLinks(component.value, isOnPhishingList);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=ui.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/ui.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport { assert, AssertionError } from '@metamask/utils';\n\nconst MARKDOWN_LINK_REGEX = /\\[(?<name>[^\\]]*)\\]\\((?<url>[^)]+)\\)/giu;\n\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Searches for markdown links in a string and checks them against the phishing list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const matches = String.prototype.matchAll.call(text, MARKDOWN_LINK_REGEX);\n\n for (const { groups } of matches) {\n const link = groups?.url;\n\n /* This case should never happen with the regex but the TS type allows for undefined */\n /* istanbul ignore next */\n if (!link) {\n continue;\n }\n\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;\n\n assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError\n ? error.message\n : 'Unable to parse URL.'\n }`,\n );\n }\n }\n}\n\n/**\n * Search for links in UI components and check that the URL they are trying to\n * pass in is not in the phishing list.\n *\n * @param component - The custom UI component.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the component contains a link that is not allowed.\n */\nexport function validateComponentLinks(\n component: Component,\n isOnPhishingList: (url: string) => boolean,\n) {\n const { type } = component;\n if (type === NodeType.Panel) {\n component.children.forEach((node) =>\n validateComponentLinks(node, isOnPhishingList),\n );\n }\n\n if (type === NodeType.Text) {\n validateTextLinks(component.value, isOnPhishingList);\n }\n}\n"],"names":["validateTextLinks","validateComponentLinks","MARKDOWN_LINK_REGEX","ALLOWED_PROTOCOLS","text","isOnPhishingList","matches","String","prototype","matchAll","call","groups","link","url","URL","assert","includes","protocol","join","hostname","pathname","split","error","Error","AssertionError","message","component","type","NodeType","Panel","children","forEach","node","Text","value"],"mappings":";;;;;;;;;;;IAgBgBA,iBAAiB;eAAjBA;;IA+CAC,sBAAsB;eAAtBA;;;0BA9DS;uBACc;AAEvC,MAAMC,sBAAsB;AAE5B,MAAMC,oBAAoB;IAAC;IAAU;CAAU;AAUxC,SAASH,kBACdI,IAAY,EACZC,gBAA0C;IAE1C,MAAMC,UAAUC,OAAOC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACN,MAAMF;IAErD,KAAK,MAAM,EAAES,MAAM,EAAE,IAAIL,QAAS;QAChC,MAAMM,OAAOD,QAAQE;QAErB,qFAAqF,GACrF,wBAAwB,GACxB,IAAI,CAACD,MAAM;YACT;QACF;QAEA,IAAI;YACF,MAAMC,MAAM,IAAIC,IAAIF;YACpBG,IAAAA,aAAM,EACJZ,kBAAkBa,QAAQ,CAACH,IAAII,QAAQ,GACvC,CAAC,yBAAyB,EAAEd,kBAAkBe,IAAI,CAAC,MAAM,CAAC,CAAC;YAG7D,MAAMC,WACJN,IAAII,QAAQ,KAAK,YAAYJ,IAAIO,QAAQ,CAACC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAGR,IAAIM,QAAQ;YAExEJ,IAAAA,aAAM,EAAC,CAACV,iBAAiBc,WAAW;QACtC,EAAE,OAAOG,OAAO;YACd,MAAM,IAAIC,MACR,CAAC,aAAa,EACZD,iBAAiBE,qBAAc,GAC3BF,MAAMG,OAAO,GACb,uBACL,CAAC;QAEN;IACF;AACF;AAWO,SAASxB,uBACdyB,SAAoB,EACpBrB,gBAA0C;IAE1C,MAAM,EAAEsB,IAAI,EAAE,GAAGD;IACjB,IAAIC,SAASC,kBAAQ,CAACC,KAAK,EAAE;QAC3BH,UAAUI,QAAQ,CAACC,OAAO,CAAC,CAACC,OAC1B/B,uBAAuB+B,MAAM3B;IAEjC;IAEA,IAAIsB,SAASC,kBAAQ,CAACK,IAAI,EAAE;QAC1BjC,kBAAkB0B,UAAUQ,KAAK,EAAE7B;IACrC;AACF"}
|
package/dist/cjs/validation.js
CHANGED
|
@@ -12,9 +12,9 @@ const _icon = require("./icon");
|
|
|
12
12
|
const _localization = require("./localization");
|
|
13
13
|
const _validation = require("./manifest/validation");
|
|
14
14
|
const _snaps = require("./snaps");
|
|
15
|
-
function validateFetchedSnap(files) {
|
|
15
|
+
async function validateFetchedSnap(files) {
|
|
16
16
|
(0, _validation.assertIsSnapManifest)(files.manifest.result);
|
|
17
|
-
(0, _snaps.validateSnapShasum)(files);
|
|
17
|
+
await (0, _snaps.validateSnapShasum)(files);
|
|
18
18
|
(0, _localization.validateSnapManifestLocalizations)(files.manifest.result, files.localizationFiles.map((file)=>file.result));
|
|
19
19
|
if (files.svgIcon) {
|
|
20
20
|
(0, _icon.assertIsSnapIcon)(files.svgIcon);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateSnapManifestLocalizations } from './localization';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(files: FetchedSnapFiles): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n validateSnapManifestLocalizations(\n files.manifest.result,\n files.localizationFiles.map((file) => file.result),\n );\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["validateFetchedSnap","files","assertIsSnapManifest","manifest","result","validateSnapShasum","validateSnapManifestLocalizations","localizationFiles","map","file","svgIcon","assertIsSnapIcon"],"mappings":";;;;+
|
|
1
|
+
{"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateSnapManifestLocalizations } from './localization';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport async function validateFetchedSnap(\n files: FetchedSnapFiles,\n): Promise<void> {\n assertIsSnapManifest(files.manifest.result);\n await validateSnapShasum(files);\n validateSnapManifestLocalizations(\n files.manifest.result,\n files.localizationFiles.map((file) => file.result),\n );\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["validateFetchedSnap","files","assertIsSnapManifest","manifest","result","validateSnapShasum","validateSnapManifestLocalizations","localizationFiles","map","file","svgIcon","assertIsSnapIcon"],"mappings":";;;;+BAYsBA;;;eAAAA;;;sBAZW;8BACiB;4BACb;uBACF;AAS5B,eAAeA,oBACpBC,KAAuB;IAEvBC,IAAAA,gCAAoB,EAACD,MAAME,QAAQ,CAACC,MAAM;IAC1C,MAAMC,IAAAA,yBAAkB,EAACJ;IACzBK,IAAAA,+CAAiC,EAC/BL,MAAME,QAAQ,CAACC,MAAM,EACrBH,MAAMM,iBAAiB,CAACC,GAAG,CAAC,CAACC,OAASA,KAAKL,MAAM;IAGnD,IAAIH,MAAMS,OAAO,EAAE;QACjBC,IAAAA,sBAAgB,EAACV,MAAMS,OAAO;IAChC;AACF"}
|
|
@@ -1,11 +1,6 @@
|
|
|
1
|
+
import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';
|
|
1
2
|
import { bytesToHex, bytesToString } from '@metamask/utils';
|
|
2
3
|
import { base64 } from '@scure/base';
|
|
3
|
-
export var AuxiliaryFileEncoding;
|
|
4
|
-
(function(AuxiliaryFileEncoding) {
|
|
5
|
-
AuxiliaryFileEncoding["Base64"] = 'base64';
|
|
6
|
-
AuxiliaryFileEncoding["Hex"] = 'hex';
|
|
7
|
-
AuxiliaryFileEncoding["Utf8"] = 'utf8';
|
|
8
|
-
})(AuxiliaryFileEncoding || (AuxiliaryFileEncoding = {}));
|
|
9
4
|
/**
|
|
10
5
|
* Re-encodes an auxiliary file if needed depending on the requested file encoding.
|
|
11
6
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';\nimport { bytesToHex, bytesToString } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = base64.decode(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["AuxiliaryFileEncoding","bytesToHex","bytesToString","base64","encodeAuxiliaryFile","value","encoding","Base64","decoded","decode","Utf8"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,sBAAsB;AAC5D,SAASC,UAAU,EAAEC,aAAa,QAAQ,kBAAkB;AAC5D,SAASC,MAAM,QAAQ,cAAc;AAErC;;;;;;CAMC,GACD,OAAO,SAASC,oBACdC,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaN,sBAAsBO,MAAM,EAAE;QAC7C,OAAOF;IACT;IAEA,qCAAqC;IACrC,MAAMG,UAAUL,OAAOM,MAAM,CAACJ;IAC9B,IAAIC,aAAaN,sBAAsBU,IAAI,EAAE;QAC3C,OAAOR,cAAcM;IACvB;IAEA,OAAOP,WAAWO;AACpB"}
|
package/dist/esm/checksum.js
CHANGED
|
@@ -1,13 +1,31 @@
|
|
|
1
|
-
import { assert, concatBytes } from '@metamask/utils';
|
|
1
|
+
import { assert, concatBytes, stringToBytes } from '@metamask/utils';
|
|
2
2
|
import { sha256 } from '@noble/hashes/sha256';
|
|
3
3
|
import { VirtualFile } from './virtual-file/VirtualFile';
|
|
4
|
+
/**
|
|
5
|
+
* Convert an input value to a Uint8Array for use in a checksum.
|
|
6
|
+
*
|
|
7
|
+
* @param bytes - A value to use for a checksum calculation.
|
|
8
|
+
* @returns The input value converted to a Uint8Array if necessary.
|
|
9
|
+
*/ export function getChecksumBytes(bytes) {
|
|
10
|
+
// Unwrap VirtualFiles to extract the content
|
|
11
|
+
// The content is then either a string or Uint8Array
|
|
12
|
+
const unwrapped = bytes instanceof VirtualFile ? bytes.value : bytes;
|
|
13
|
+
if (typeof unwrapped === 'string') {
|
|
14
|
+
return stringToBytes(unwrapped);
|
|
15
|
+
}
|
|
16
|
+
return unwrapped;
|
|
17
|
+
}
|
|
4
18
|
/**
|
|
5
19
|
* Calculates checksum for a single byte array.
|
|
6
20
|
*
|
|
7
21
|
* @param bytes - The byte array to calculate the checksum for.
|
|
8
22
|
* @returns A single sha-256 checksum.
|
|
9
|
-
*/ export function checksum(bytes) {
|
|
10
|
-
const value = bytes
|
|
23
|
+
*/ export async function checksum(bytes) {
|
|
24
|
+
const value = getChecksumBytes(bytes);
|
|
25
|
+
// Use crypto.subtle.digest whenever possible as it is faster.
|
|
26
|
+
if ('crypto' in globalThis && typeof globalThis.crypto === 'object' && crypto.subtle?.digest) {
|
|
27
|
+
return new Uint8Array(await crypto.subtle.digest('SHA-256', value));
|
|
28
|
+
}
|
|
11
29
|
return sha256(value);
|
|
12
30
|
}
|
|
13
31
|
/**
|
|
@@ -21,8 +39,8 @@ import { VirtualFile } from './virtual-file/VirtualFile';
|
|
|
21
39
|
*
|
|
22
40
|
* @param files - The files over which to calculate the checksum.
|
|
23
41
|
* @returns A single sha-256 checksum.
|
|
24
|
-
*/ export function checksumFiles(files) {
|
|
25
|
-
|
|
42
|
+
*/ export async function checksumFiles(files) {
|
|
43
|
+
const checksums = await Promise.all([
|
|
26
44
|
...files
|
|
27
45
|
].sort((a, b)=>{
|
|
28
46
|
assert(a.path !== b.path, 'Tried to sort files with non-unique paths.');
|
|
@@ -30,7 +48,8 @@ import { VirtualFile } from './virtual-file/VirtualFile';
|
|
|
30
48
|
return -1;
|
|
31
49
|
}
|
|
32
50
|
return 1;
|
|
33
|
-
}).map((file)=>checksum(file)))
|
|
51
|
+
}).map(async (file)=>checksum(file)));
|
|
52
|
+
return checksum(concatBytes(checksums));
|
|
34
53
|
}
|
|
35
54
|
|
|
36
55
|
//# sourceMappingURL=checksum.js.map
|
package/dist/esm/checksum.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport function checksum(bytes: VirtualFile | Uint8Array | string): Uint8Array {\n const value = bytes
|
|
1
|
+
{"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes, stringToBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Convert an input value to a Uint8Array for use in a checksum.\n *\n * @param bytes - A value to use for a checksum calculation.\n * @returns The input value converted to a Uint8Array if necessary.\n */\nexport function getChecksumBytes(\n bytes: VirtualFile | Uint8Array | string,\n): Uint8Array {\n // Unwrap VirtualFiles to extract the content\n // The content is then either a string or Uint8Array\n const unwrapped = bytes instanceof VirtualFile ? bytes.value : bytes;\n\n if (typeof unwrapped === 'string') {\n return stringToBytes(unwrapped);\n }\n\n return unwrapped;\n}\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport async function checksum(\n bytes: VirtualFile | Uint8Array | string,\n): Promise<Uint8Array> {\n const value = getChecksumBytes(bytes);\n // Use crypto.subtle.digest whenever possible as it is faster.\n if (\n 'crypto' in globalThis &&\n typeof globalThis.crypto === 'object' &&\n crypto.subtle?.digest\n ) {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', value));\n }\n return sha256(value);\n}\n\n/**\n * Calculates checksum over multiple files in a reproducible way.\n *\n * 1. Sort all the files by their paths.\n * 2. Calculate sha-256 checksum of each file separately.\n * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.\n *\n * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.\n *\n * @param files - The files over which to calculate the checksum.\n * @returns A single sha-256 checksum.\n */\nexport async function checksumFiles(files: VirtualFile[]) {\n const checksums = await Promise.all(\n [...files]\n .sort((a, b) => {\n assert(a.path !== b.path, 'Tried to sort files with non-unique paths.');\n if (a.path < b.path) {\n return -1;\n }\n return 1;\n })\n .map(async (file) => checksum(file)),\n );\n\n return checksum(concatBytes(checksums));\n}\n"],"names":["assert","concatBytes","stringToBytes","sha256","VirtualFile","getChecksumBytes","bytes","unwrapped","value","checksum","globalThis","crypto","subtle","digest","Uint8Array","checksumFiles","files","checksums","Promise","all","sort","a","b","path","map","file"],"mappings":"AAAA,SAASA,MAAM,EAAEC,WAAW,EAAEC,aAAa,QAAQ,kBAAkB;AACrE,SAASC,MAAM,QAAQ,uBAAuB;AAE9C,SAASC,WAAW,QAAQ,6BAA6B;AAEzD;;;;;CAKC,GACD,OAAO,SAASC,iBACdC,KAAwC;IAExC,6CAA6C;IAC7C,oDAAoD;IACpD,MAAMC,YAAYD,iBAAiBF,cAAcE,MAAME,KAAK,GAAGF;IAE/D,IAAI,OAAOC,cAAc,UAAU;QACjC,OAAOL,cAAcK;IACvB;IAEA,OAAOA;AACT;AAEA;;;;;CAKC,GACD,OAAO,eAAeE,SACpBH,KAAwC;IAExC,MAAME,QAAQH,iBAAiBC;IAC/B,8DAA8D;IAC9D,IACE,YAAYI,cACZ,OAAOA,WAAWC,MAAM,KAAK,YAC7BA,OAAOC,MAAM,EAAEC,QACf;QACA,OAAO,IAAIC,WAAW,MAAMH,OAAOC,MAAM,CAACC,MAAM,CAAC,WAAWL;IAC9D;IACA,OAAOL,OAAOK;AAChB;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeO,cAAcC,KAAoB;IACtD,MAAMC,YAAY,MAAMC,QAAQC,GAAG,CACjC;WAAIH;KAAM,CACPI,IAAI,CAAC,CAACC,GAAGC;QACRtB,OAAOqB,EAAEE,IAAI,KAAKD,EAAEC,IAAI,EAAE;QAC1B,IAAIF,EAAEE,IAAI,GAAGD,EAAEC,IAAI,EAAE;YACnB,OAAO,CAAC;QACV;QACA,OAAO;IACT,GACCC,GAAG,CAAC,OAAOC,OAAShB,SAASgB;IAGlC,OAAOhB,SAASR,YAAYgB;AAC9B"}
|
package/dist/esm/cronjob.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { JsonRpcRequestStruct } from '@metamask/utils';
|
|
2
2
|
import { parseExpression } from 'cron-parser';
|
|
3
|
-
import {
|
|
3
|
+
import { assign, omit, partial, pick, array, coerce, create, object, optional, refine, string } from 'superstruct';
|
|
4
4
|
export const CronjobRpcRequestStruct = assign(partial(pick(JsonRpcRequestStruct, [
|
|
5
5
|
'id',
|
|
6
6
|
'jsonrpc'
|
package/dist/esm/cronjob.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n
|
|
1
|
+
{"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n assign,\n omit,\n partial,\n pick,\n array,\n coerce,\n create,\n object,\n optional,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["JsonRpcRequestStruct","parseExpression","assign","omit","partial","pick","array","coerce","create","object","optional","refine","string","CronjobRpcRequestStruct","CronExpressionStruct","minute","hour","dayOfMonth","month","dayOfWeek","value","parseCronExpression","expression","ensureStringExpression","CronjobSpecificationStruct","request","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,kBAAkB;AACvD,SAASC,eAAe,QAAQ,cAAc;AAE9C,SACEC,MAAM,EACNC,IAAI,EACJC,OAAO,EACPC,I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CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type { EnumToUnion } from '@metamask/snaps-sdk';\nimport type { Struct } from 'superstruct';\n\nimport { literal } from './structs';\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, null> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["literal","enumValue","constant"],"mappings":"AAGA,SAASA,OAAO,QAAQ,YAAY;AAEpC;;;;;;CAMC,GACD,OAAO,SAASC,UACdC,QAAc;IAEd,OAAOF,QAAQE;AACjB"}
|
package/dist/esm/errors.js
CHANGED
|
@@ -39,60 +39,10 @@ function _class_private_field_set(receiver, privateMap, value) {
|
|
|
39
39
|
return value;
|
|
40
40
|
}
|
|
41
41
|
import { errorCodes, JsonRpcError as RpcError, serializeCause } from '@metamask/rpc-errors';
|
|
42
|
-
import {
|
|
43
|
-
|
|
44
|
-
* Get the error message from an unknown error type.
|
|
45
|
-
*
|
|
46
|
-
* - If the error is an object with a `message` property, return the message.
|
|
47
|
-
* - Otherwise, return the error converted to a string.
|
|
48
|
-
*
|
|
49
|
-
* @param error - The error to get the message from.
|
|
50
|
-
* @returns The error message.
|
|
51
|
-
*/ export function getErrorMessage(error) {
|
|
52
|
-
if (isObject(error) && hasProperty(error, 'message') && typeof error.message === 'string') {
|
|
53
|
-
return error.message;
|
|
54
|
-
}
|
|
55
|
-
return String(error);
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Get the error stack from an unknown error type.
|
|
59
|
-
*
|
|
60
|
-
* @param error - The error to get the stack from.
|
|
61
|
-
* @returns The error stack, or undefined if the error does not have a valid
|
|
62
|
-
* stack.
|
|
63
|
-
*/ export function getErrorStack(error) {
|
|
64
|
-
if (isObject(error) && hasProperty(error, 'stack') && typeof error.stack === 'string') {
|
|
65
|
-
return error.stack;
|
|
66
|
-
}
|
|
67
|
-
return undefined;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Get the error code from an unknown error type.
|
|
71
|
-
*
|
|
72
|
-
* @param error - The error to get the code from.
|
|
73
|
-
* @returns The error code, or `-32603` if the error does not have a valid code.
|
|
74
|
-
*/ export function getErrorCode(error) {
|
|
75
|
-
if (isObject(error) && hasProperty(error, 'code') && typeof error.code === 'number' && Number.isInteger(error.code)) {
|
|
76
|
-
return error.code;
|
|
77
|
-
}
|
|
78
|
-
return errorCodes.rpc.internal;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Get the error data from an unknown error type.
|
|
82
|
-
*
|
|
83
|
-
* @param error - The error to get the data from.
|
|
84
|
-
* @returns The error data, or an empty object if the error does not have valid
|
|
85
|
-
* data.
|
|
86
|
-
*/ export function getErrorData(error) {
|
|
87
|
-
if (isObject(error) && hasProperty(error, 'data') && typeof error.data === 'object' && error.data !== null && isValidJson(error.data) && !Array.isArray(error.data)) {
|
|
88
|
-
return error.data;
|
|
89
|
-
}
|
|
90
|
-
return {};
|
|
91
|
-
}
|
|
42
|
+
import { getErrorMessage, getErrorStack, SNAP_ERROR_CODE, SNAP_ERROR_MESSAGE } from '@metamask/snaps-sdk';
|
|
43
|
+
import { isObject, isJsonRpcError } from '@metamask/utils';
|
|
92
44
|
export const SNAP_ERROR_WRAPPER_CODE = -31001;
|
|
93
45
|
export const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';
|
|
94
|
-
export const SNAP_ERROR_CODE = -31002;
|
|
95
|
-
export const SNAP_ERROR_MESSAGE = 'Snap Error';
|
|
96
46
|
var _error = /*#__PURE__*/ new WeakMap(), _message = /*#__PURE__*/ new WeakMap(), _stack = /*#__PURE__*/ new WeakMap();
|
|
97
47
|
export class WrappedSnapError extends Error {
|
|
98
48
|
/**
|
|
@@ -162,111 +112,6 @@ export class WrappedSnapError extends Error {
|
|
|
162
112
|
_class_private_field_set(this, _stack, getErrorStack(error));
|
|
163
113
|
}
|
|
164
114
|
}
|
|
165
|
-
var _code = /*#__PURE__*/ new WeakMap(), _message1 = /*#__PURE__*/ new WeakMap(), _data = /*#__PURE__*/ new WeakMap(), _stack1 = /*#__PURE__*/ new WeakMap();
|
|
166
|
-
/**
|
|
167
|
-
* A generic error which can be thrown by a Snap, without it causing the Snap to
|
|
168
|
-
* crash.
|
|
169
|
-
*/ export class SnapError extends Error {
|
|
170
|
-
/**
|
|
171
|
-
* The error name.
|
|
172
|
-
*
|
|
173
|
-
* @returns The error name.
|
|
174
|
-
*/ get name() {
|
|
175
|
-
return 'SnapError';
|
|
176
|
-
}
|
|
177
|
-
/**
|
|
178
|
-
* The error code.
|
|
179
|
-
*
|
|
180
|
-
* @returns The error code.
|
|
181
|
-
*/ get code() {
|
|
182
|
-
return _class_private_field_get(this, _code);
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* The error message.
|
|
186
|
-
*
|
|
187
|
-
* @returns The error message.
|
|
188
|
-
*/ get message() {
|
|
189
|
-
return _class_private_field_get(this, _message1);
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Additional data for the error.
|
|
193
|
-
*
|
|
194
|
-
* @returns Additional data for the error.
|
|
195
|
-
*/ get data() {
|
|
196
|
-
return _class_private_field_get(this, _data);
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* The error stack.
|
|
200
|
-
*
|
|
201
|
-
* @returns The error stack.
|
|
202
|
-
*/ get stack() {
|
|
203
|
-
return _class_private_field_get(this, _stack1);
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Convert the error to a JSON object.
|
|
207
|
-
*
|
|
208
|
-
* @returns The JSON object.
|
|
209
|
-
*/ toJSON() {
|
|
210
|
-
return {
|
|
211
|
-
code: SNAP_ERROR_CODE,
|
|
212
|
-
message: SNAP_ERROR_MESSAGE,
|
|
213
|
-
data: {
|
|
214
|
-
cause: {
|
|
215
|
-
code: this.code,
|
|
216
|
-
message: this.message,
|
|
217
|
-
stack: this.stack,
|
|
218
|
-
data: this.data
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* Serialize the error to a JSON object. This is called by
|
|
225
|
-
* `@metamask/rpc-errors` when serializing the error.
|
|
226
|
-
*
|
|
227
|
-
* @returns The JSON object.
|
|
228
|
-
*/ serialize() {
|
|
229
|
-
return this.toJSON();
|
|
230
|
-
}
|
|
231
|
-
/**
|
|
232
|
-
* Create a new `SnapError`.
|
|
233
|
-
*
|
|
234
|
-
* @param error - The error to create the `SnapError` from. If this is a
|
|
235
|
-
* `string`, it will be used as the error message. If this is an `Error`, its
|
|
236
|
-
* `message` property will be used as the error message. If this is a
|
|
237
|
-
* `JsonRpcError`, its `message` property will be used as the error message
|
|
238
|
-
* and its `code` property will be used as the error code. Otherwise, the
|
|
239
|
-
* error will be converted to a string and used as the error message.
|
|
240
|
-
* @param data - Additional data to include in the error. This will be merged
|
|
241
|
-
* with the error data, if any.
|
|
242
|
-
*/ constructor(error, data = {}){
|
|
243
|
-
const message = getErrorMessage(error);
|
|
244
|
-
super(message);
|
|
245
|
-
_class_private_field_init(this, _code, {
|
|
246
|
-
writable: true,
|
|
247
|
-
value: void 0
|
|
248
|
-
});
|
|
249
|
-
_class_private_field_init(this, _message1, {
|
|
250
|
-
writable: true,
|
|
251
|
-
value: void 0
|
|
252
|
-
});
|
|
253
|
-
_class_private_field_init(this, _data, {
|
|
254
|
-
writable: true,
|
|
255
|
-
value: void 0
|
|
256
|
-
});
|
|
257
|
-
_class_private_field_init(this, _stack1, {
|
|
258
|
-
writable: true,
|
|
259
|
-
value: void 0
|
|
260
|
-
});
|
|
261
|
-
_class_private_field_set(this, _message1, message);
|
|
262
|
-
_class_private_field_set(this, _code, getErrorCode(error));
|
|
263
|
-
_class_private_field_set(this, _data, {
|
|
264
|
-
...getErrorData(error),
|
|
265
|
-
...data
|
|
266
|
-
});
|
|
267
|
-
_class_private_field_set(this, _stack1, super.stack);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
115
|
/**
|
|
271
116
|
* Check if an object is a `SnapError`.
|
|
272
117
|
*
|
package/dist/esm/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcError } from '@metamask/utils';\nimport {\n hasProperty,\n isJsonRpcError,\n isObject,\n isValidJson,\n} from '@metamask/utils';\n\n/**\n * Get the error message from an unknown error type.\n *\n * - If the error is an object with a `message` property, return the message.\n * - Otherwise, return the error converted to a string.\n *\n * @param error - The error to get the message from.\n * @returns The error message.\n */\nexport function getErrorMessage(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n\n return String(error);\n}\n\n/**\n * Get the error stack from an unknown error type.\n *\n * @param error - The error to get the stack from.\n * @returns The error stack, or undefined if the error does not have a valid\n * stack.\n */\nexport function getErrorStack(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'stack') &&\n typeof error.stack === 'string'\n ) {\n return error.stack;\n }\n\n return undefined;\n}\n\n/**\n * Get the error code from an unknown error type.\n *\n * @param error - The error to get the code from.\n * @returns The error code, or `-32603` if the error does not have a valid code.\n */\nexport function getErrorCode(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'code') &&\n typeof error.code === 'number' &&\n Number.isInteger(error.code)\n ) {\n return error.code;\n }\n\n return errorCodes.rpc.internal;\n}\n\n/**\n * Get the error data from an unknown error type.\n *\n * @param error - The error to get the data from.\n * @returns The error data, or an empty object if the error does not have valid\n * data.\n */\nexport function getErrorData(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'data') &&\n typeof error.data === 'object' &&\n error.data !== null &&\n isValidJson(error.data) &&\n !Array.isArray(error.data)\n ) {\n return error.data;\n }\n\n return {};\n}\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport const SNAP_ERROR_CODE = -31002;\nexport const SNAP_ERROR_MESSAGE = 'Snap Error';\n\nexport type SerializedSnapErrorWrapper = {\n code: typeof SNAP_ERROR_WRAPPER_CODE;\n message: typeof SNAP_ERROR_WRAPPER_MESSAGE;\n data: {\n cause: Json;\n };\n};\n\nexport type SerializedSnapError = {\n code: typeof SNAP_ERROR_CODE;\n message: typeof SNAP_ERROR_MESSAGE;\n data: {\n cause: JsonRpcError & {\n data: Record<string, Json>;\n };\n };\n};\n\nexport class WrappedSnapError extends Error {\n readonly #error: unknown;\n\n readonly #message: string;\n\n readonly #stack?: string;\n\n /**\n * Create a new `WrappedSnapError`.\n *\n * @param error - The error to create the `WrappedSnapError` from.\n */\n constructor(error: unknown) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#error = error;\n this.#message = message;\n this.#stack = getErrorStack(error);\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'WrappedSnapError';\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapErrorWrapper {\n const cause = isSnapError(this.#error)\n ? this.#error.serialize()\n : serializeCause(this.#error);\n\n return {\n code: SNAP_ERROR_WRAPPER_CODE,\n message: SNAP_ERROR_WRAPPER_MESSAGE,\n data: {\n cause,\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * A generic error which can be thrown by a Snap, without it causing the Snap to\n * crash.\n */\nexport class SnapError extends Error {\n readonly #code: number;\n\n readonly #message: string;\n\n readonly #data: Record<string, Json>;\n\n readonly #stack?: string;\n\n /**\n * Create a new `SnapError`.\n *\n * @param error - The error to create the `SnapError` from. If this is a\n * `string`, it will be used as the error message. If this is an `Error`, its\n * `message` property will be used as the error message. If this is a\n * `JsonRpcError`, its `message` property will be used as the error message\n * and its `code` property will be used as the error code. Otherwise, the\n * error will be converted to a string and used as the error message.\n * @param data - Additional data to include in the error. This will be merged\n * with the error data, if any.\n */\n constructor(\n error: string | Error | JsonRpcError,\n data: Record<string, Json> = {},\n ) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#message = message;\n this.#code = getErrorCode(error);\n this.#data = { ...getErrorData(error), ...data };\n this.#stack = super.stack;\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'SnapError';\n }\n\n /**\n * The error code.\n *\n * @returns The error code.\n */\n get code() {\n return this.#code;\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * Additional data for the error.\n *\n * @returns Additional data for the error.\n */\n get data() {\n return this.#data;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapError {\n return {\n code: SNAP_ERROR_CODE,\n message: SNAP_ERROR_MESSAGE,\n data: {\n cause: {\n code: this.code,\n message: this.message,\n stack: this.stack,\n data: this.data,\n },\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * Check if an object is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSnapError(error: unknown): error is SnapError {\n if (\n isObject(error) &&\n 'serialize' in error &&\n typeof error.serialize === 'function'\n ) {\n const serialized = error.serialize();\n return isJsonRpcError(serialized) && isSerializedSnapError(serialized);\n }\n\n return false;\n}\n\n/**\n * Check if a JSON-RPC error is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSerializedSnapError(\n error: JsonRpcError,\n): error is SerializedSnapError {\n return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;\n}\n\n/**\n * Check if a JSON-RPC error is a `WrappedSnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `WrappedSnapError`.\n */\nexport function isWrappedSnapError(\n error: unknown,\n): error is SerializedSnapErrorWrapper {\n return (\n isJsonRpcError(error) &&\n error.code === SNAP_ERROR_WRAPPER_CODE &&\n error.message === SNAP_ERROR_WRAPPER_MESSAGE\n );\n}\n\n/**\n * Get a JSON-RPC error with the given code, message, stack, and data.\n *\n * @param code - The error code.\n * @param message - The error message.\n * @param stack - The error stack.\n * @param data - Additional data for the error.\n * @returns The JSON-RPC error.\n */\nfunction getJsonRpcError(\n code: number,\n message: string,\n stack?: string,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack;\n\n return error;\n}\n\n/**\n * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will\n * try to get the error code, message, and data from the error, and return a\n * `JsonRpcError` with those properties.\n *\n * @param error - The error to unwrap.\n * @returns A tuple containing the unwrapped error and a boolean indicating\n * whether the error was handled.\n */\nexport function unwrapError(\n error: unknown,\n): [error: RpcError<DataWithOptionalCause>, isHandled: boolean] {\n // This logic is a bit complicated, but it's necessary to handle all the\n // different types of errors that can be thrown by a Snap.\n\n // If the error is a wrapped Snap error, unwrap it.\n if (isWrappedSnapError(error)) {\n // The wrapped error can be a JSON-RPC error, or an unknown error. If it's\n // a JSON-RPC error, we can unwrap it further.\n if (isJsonRpcError(error.data.cause)) {\n // If the JSON-RPC error is a wrapped Snap error, unwrap it further.\n if (isSerializedSnapError(error.data.cause)) {\n const { code, message, stack, data } = error.data.cause.data.cause;\n return [getJsonRpcError(code, message, stack, data), true];\n }\n\n // Otherwise, we use the original JSON-RPC error.\n const { code, message, stack, data } = error.data.cause;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // Otherwise, we throw an internal error with the wrapped error as the\n // message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error.data.cause),\n getErrorStack(error.data.cause),\n ),\n false,\n ];\n }\n\n // The error can be a non-wrapped JSON-RPC error, in which case we can just\n // re-throw it with the same code, message, and data.\n if (isJsonRpcError(error)) {\n const { code, message, stack, data } = error;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // If the error is not a wrapped error, we don't know how to handle it, so we\n // throw an internal error with the error as the message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error),\n getErrorStack(error),\n ),\n false,\n ];\n}\n"],"names":["errorCodes","JsonRpcError","RpcError","serializeCause","hasProperty","isJsonRpcError","isObject","isValidJson","getErrorMessage","error","message","String","getErrorStack","stack","undefined","getErrorCode","code","Number","isInteger","rpc","internal","getErrorData","data","Array","isArray","SNAP_ERROR_WRAPPER_CODE","SNAP_ERROR_WRAPPER_MESSAGE","SNAP_ERROR_CODE","SNAP_ERROR_MESSAGE","WrappedSnapError","Error","name","toJSON","cause","isSnapError","serialize","constructor","SnapError","serialized","isSerializedSnapError","isWrappedSnapError","getJsonRpcError","unwrapError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SACEA,UAAU,EACVC,gBAAgBC,QAAQ,EACxBC,cAAc,QACT,uBAAuB;AAG9B,SACEC,WAAW,EACXC,cAAc,EACdC,QAAQ,EACRC,WAAW,QACN,kBAAkB;AAEzB;;;;;;;;CAQC,GACD,OAAO,SAASC,gBAAgBC,KAAc;IAC5C,IACEH,SAASG,UACTL,YAAYK,O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AMa,IAAI,CAACW,KAAK,GAAG;gBAC3C,MAAM,EAAEjB,IAAI,EAAEN,OAAO,EAAEG,KAAK,EAAES,IAAI,EAAE,GAAGb,MAAMa,IAAI,CAACW,KAAK,CAACX,IAAI,CAACW,KAAK;gBAClE,OAAO;oBAACQ,gBAAgBzB,MAAMN,SAASG,OAAOS;oBAAO;iBAAK;YAC5D;YAEA,iDAAiD;YACjD,MAAM,EAAEN,IAAI,EAAEN,OAAO,EAAEG,KAAK,EAAES,IAAI,EAAE,GAAGb,MAAMa,IAAI,CAACW,KAAK;YACvD,OAAO;gBAACQ,gBAAgBzB,MAAMN,SAASG,OAAOS;gBAAO;aAAM;QAC7D;QAEA,sEAAsE;QACtE,WAAW;QACX,OAAO;YACLmB,gBACEzC,WAAWmB,GAAG,CAACC,QAAQ,EACvBZ,gBAAgBC,MAAMa,IAAI,CAACW,KAAK,GAChCrB,cAAcH,MAAMa,IAAI,CAACW,KAAK;YAEhC;SACD;IACH;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,IAAI5B,eAAeI,QAAQ;QACzB,MAAM,EAAEO,IAAI,EAAEN,OAAO,EAAEG,KAAK,EAAES,IAAI,EAAE,GAAGb;QACvC,OAAO;YAACgC,gBAAgBzB,MAAMN,SAASG,OAAOS;YAAO;SAAM;IAC7D;IAEA,6EAA6E;IAC7E,yDAAyD;IACzD,OAAO;QACLmB,gBACEzC,WAAWmB,GAAG,CAACC,QAAQ,EACvBZ,gBAAgBC,QAChBG,cAAcH;QAEhB;KACD;AACH"}
|
|
1
|
+
{"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type { SerializedSnapError, SnapError } from '@metamask/snaps-sdk';\nimport {\n getErrorMessage,\n getErrorStack,\n SNAP_ERROR_CODE,\n SNAP_ERROR_MESSAGE,\n} from '@metamask/snaps-sdk';\nimport type { Json, JsonRpcError } from '@metamask/utils';\nimport { isObject, isJsonRpcError } from '@metamask/utils';\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport type SerializedSnapErrorWrapper = {\n code: typeof SNAP_ERROR_WRAPPER_CODE;\n message: typeof SNAP_ERROR_WRAPPER_MESSAGE;\n data: {\n cause: Json;\n };\n};\n\nexport class WrappedSnapError extends Error {\n readonly #error: unknown;\n\n readonly #message: string;\n\n readonly #stack?: string;\n\n /**\n * Create a new `WrappedSnapError`.\n *\n * @param error - The error to create the `WrappedSnapError` from.\n */\n constructor(error: unknown) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#error = error;\n this.#message = message;\n this.#stack = getErrorStack(error);\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'WrappedSnapError';\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapErrorWrapper {\n const cause = isSnapError(this.#error)\n ? this.#error.serialize()\n : serializeCause(this.#error);\n\n return {\n code: SNAP_ERROR_WRAPPER_CODE,\n message: SNAP_ERROR_WRAPPER_MESSAGE,\n data: {\n cause,\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * Check if an object is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSnapError(error: unknown): error is SnapError {\n if (\n isObject(error) &&\n 'serialize' in error &&\n typeof error.serialize === 'function'\n ) {\n const serialized = error.serialize();\n return isJsonRpcError(serialized) && isSerializedSnapError(serialized);\n }\n\n return false;\n}\n\n/**\n * Check if a JSON-RPC error is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSerializedSnapError(\n error: JsonRpcError,\n): error is SerializedSnapError {\n return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;\n}\n\n/**\n * Check if a JSON-RPC error is a `WrappedSnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `WrappedSnapError`.\n */\nexport function isWrappedSnapError(\n error: unknown,\n): error is SerializedSnapErrorWrapper {\n return (\n isJsonRpcError(error) &&\n error.code === SNAP_ERROR_WRAPPER_CODE &&\n error.message === SNAP_ERROR_WRAPPER_MESSAGE\n );\n}\n\n/**\n * Get a JSON-RPC error with the given code, message, stack, and data.\n *\n * @param code - The error code.\n * @param message - The error message.\n * @param stack - The error stack.\n * @param data - Additional data for the error.\n * @returns The JSON-RPC error.\n */\nfunction getJsonRpcError(\n code: number,\n message: string,\n stack?: string,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack;\n\n return error;\n}\n\n/**\n * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will\n * try to get the error code, message, and data from the error, and return a\n * `JsonRpcError` with those properties.\n *\n * @param error - The error to unwrap.\n * @returns A tuple containing the unwrapped error and a boolean indicating\n * whether the error was handled.\n */\nexport function unwrapError(\n error: unknown,\n): [error: RpcError<DataWithOptionalCause>, isHandled: boolean] {\n // This logic is a bit complicated, but it's necessary to handle all the\n // different types of errors that can be thrown by a Snap.\n\n // If the error is a wrapped Snap error, unwrap it.\n if (isWrappedSnapError(error)) {\n // The wrapped error can be a JSON-RPC error, or an unknown error. If it's\n // a JSON-RPC error, we can unwrap it further.\n if (isJsonRpcError(error.data.cause)) {\n // If the JSON-RPC error is a wrapped Snap error, unwrap it further.\n if (isSerializedSnapError(error.data.cause)) {\n const { code, message, stack, data } = error.data.cause.data.cause;\n return [getJsonRpcError(code, message, stack, data), true];\n }\n\n // Otherwise, we use the original JSON-RPC error.\n const { code, message, stack, data } = error.data.cause;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // Otherwise, we throw an internal error with the wrapped error as the\n // message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error.data.cause),\n getErrorStack(error.data.cause),\n ),\n false,\n ];\n }\n\n // The error can be a non-wrapped JSON-RPC error, in which case we can just\n // re-throw it with the same code, message, and data.\n if (isJsonRpcError(error)) {\n const { code, message, stack, data } = error;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // If the error is not a wrapped error, we don't know how to handle it, so we\n // throw an internal error with the error as the message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error),\n getErrorStack(error),\n ),\n false,\n ];\n}\n"],"names":["errorCodes","JsonRpcError","RpcError","serializeCause","getErrorMessage","getErrorStack","SNAP_ERROR_CODE","SNAP_ERROR_MESSAGE","isObject","isJsonRpcError","SNAP_ERROR_WRAPPER_CODE","SNAP_ERROR_WRAPPER_MESSAGE","WrappedSnapError","Error","name","message","stack","toJSON","cause","isSnapError","error","serialize","code","data","constructor","serialized","isSerializedSnapError","isWrappedSnapError","getJsonRpcError","unwrapError","rpc","internal"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SACEA,UAAU,EACVC,gBAAgBC,QAAQ,EACxBC,cAAc,QACT,uBAAuB;AAG9B,SACEC,eAAe,EACfC,aAAa,EACbC,eAAe,EACfC,kBAAkB,QACb,sBAAsB;AAE7B,SAASC,QAAQ,EAAEC,cAAc,QAAQ,kBAAkB;AAE3D,OAAO,MAAMC,0BAA0B,CAAC,MAAM;AAC9C,OAAO,MAAMC,6BAA6B,qBAAqB;IAWpD,sCAEA,wCAEA;AALX,OAAO,MAAMC,yBAAyBC;IAqBpC;;;;GAIC,GACD,IAAIC,OAAO;QACT,OAAO;IACT;IAEA;;;;GAIC,GACD,IAAIC,UAAU;QACZ,gCAAO,IAAI,EAAEA;IACf;IAEA;;;;GA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
import { ComponentStruct } from '@metamask/snaps-
|
|
2
|
-
import { literal, object, optional } from 'superstruct';
|
|
1
|
+
import { SeverityLevel, ComponentStruct } from '@metamask/snaps-sdk';
|
|
2
|
+
import { literal, nullable, object, optional } from 'superstruct';
|
|
3
3
|
import { HandlerType } from './handler-types';
|
|
4
4
|
export const SNAP_EXPORTS = {
|
|
5
5
|
[HandlerType.OnRpcRequest]: {
|
|
@@ -59,14 +59,10 @@ export const SNAP_EXPORTS = {
|
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
61
|
};
|
|
62
|
-
export
|
|
63
|
-
(function(SeverityLevel) {
|
|
64
|
-
SeverityLevel["Critical"] = 'critical';
|
|
65
|
-
})(SeverityLevel || (SeverityLevel = {}));
|
|
66
|
-
export const OnTransactionResponseStruct = object({
|
|
62
|
+
export const OnTransactionResponseStruct = nullable(object({
|
|
67
63
|
content: ComponentStruct,
|
|
68
64
|
severity: optional(literal(SeverityLevel.Critical))
|
|
69
|
-
});
|
|
65
|
+
}));
|
|
70
66
|
export const OnHomePageResponseStruct = object({
|
|
71
67
|
content: ComponentStruct
|
|
72
68
|
});
|