@metamask/snaps-utils 5.2.0 → 6.1.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 +23 -3
- package/dist/cjs/caveats.js +6 -0
- package/dist/cjs/caveats.js.map +1 -1
- package/dist/cjs/eval-worker.js +3 -1
- package/dist/cjs/eval-worker.js.map +1 -1
- package/dist/cjs/handler-types.js +1 -0
- package/dist/cjs/handler-types.js.map +1 -1
- package/dist/cjs/handlers.js +74 -3
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/icon.js +38 -9
- package/dist/cjs/icon.js.map +1 -1
- package/dist/cjs/manifest/manifest.js +8 -0
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js +50 -14
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/post-process.js +1 -1
- package/dist/cjs/post-process.js.map +1 -1
- package/dist/cjs/structs.js +86 -17
- package/dist/cjs/structs.js.map +1 -1
- package/dist/esm/caveats.js +6 -0
- package/dist/esm/caveats.js.map +1 -1
- package/dist/esm/eval-worker.js +3 -1
- package/dist/esm/eval-worker.js.map +1 -1
- package/dist/esm/handler-types.js +1 -0
- package/dist/esm/handler-types.js.map +1 -1
- package/dist/esm/handlers.js +45 -4
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/icon.js +43 -3
- package/dist/esm/icon.js.map +1 -1
- package/dist/esm/manifest/manifest.js +8 -0
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js +38 -16
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/post-process.js +1 -1
- package/dist/esm/post-process.js.map +1 -1
- package/dist/esm/structs.js +133 -21
- package/dist/esm/structs.js.map +1 -1
- package/dist/types/caveats.d.ts +9 -1
- package/dist/types/handler-types.d.ts +2 -1
- package/dist/types/handlers.d.ts +349 -10
- package/dist/types/icon.d.ts +16 -1
- package/dist/types/localization.d.ts +33 -13
- package/dist/types/manifest/validation.d.ts +230 -75
- package/dist/types/post-process.d.ts +1 -1
- package/dist/types/structs.d.ts +61 -7
- package/package.json +5 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["transformSync","template","binaryExpression","isUnaryExpression","isUpdateExpression","stringLiteral","templateElement","templateLiteral","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","raw","cooked","evalWrapper","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","lastMatch","suffix","replace","postProcessBundle","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","expression","setData","StringLiteral","replacement","acc","skip","BinaryExpression","errorMessage","operator","right","argument","left","end","start","includes","Error","file","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;AAExD,SAASA,aAAa,EAAEC,QAAQ,QAAQ,cAAc;AAEtD,SACEC,gBA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M;QAClB;QAEA,OAAO;YACL/D,MAAMgE,KAAKhE,IAAI;YACfE,WAAW8D,KAAKO,GAAG;YACnBlE,UAAUzB,MAAMC,IAAI,CAACwB;QACvB;IACF,EAAE,OAAOmE,OAAO;QACd,MAAM,IAAIT,MAAM,CAAC,8BAA8B,EAAES,MAAMC,OAAO,CAAC,CAAC;IAClE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["transformSync","template","binaryExpression","isUnaryExpression","isUpdateExpression","stringLiteral","templateElement","templateLiteral","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","raw","cooked","evalWrapper","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","lastMatch","suffix","replace","postProcessBundle","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","expression","setData","StringLiteral","replacement","acc","skip","BinaryExpression","errorMessage","operator","right","argument","left","end","start","includes","Error","file","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;AAExD,SAASA,aAAa,EAAEC,QAAQ,QAAQ,cAAc;AAEtD,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,kBAAkB,EAClBC,aAAa,EACbC,eAAe,EACfC,eAAe,QACV,eAAe;WAgDf;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBL,gBAAgB;IAAEM,KAAK;IAAIC,QAAQ;AAAG;AAErE,MAAMC,cAAcb,SAASc,SAAS,CAAC,CAAC;;AAExC,CAAC;AAED,MAAMC,oBAAoBf,SAASc,SAAS,CAAC,CAAC;;AAE9C,CAAC;AAED,MAAME,4BAA4BhB,SAASc,SAAS,CAAC,CAAC;;AAEtD,CAAC;AAED;;;;;;;;;;;CAWC,GACD,SAASG,YAAYC,KAAa;IAChC,MAAMC,SAASD,MAAME,KAAK,CAACX;IAC3B,OACEU,MACE,oEAAoE;IACpE,sEAAsE;KACrEE,MAAM,CAAC,CAACC,QAAUA,UAAU,MAAMA,UAAUC;AAEnD;AAEA;;;;;;;;;;CAUC,GACD,SAASC,2BACPN,KAAa;IAEb,6DAA6D;IAC7D,kEAAkE;IAClE,uEAAuE;IACvE,MAAMO,UAA8BC,MAAMC,IAAI,CAACT,MAAMU,QAAQ,CAACnB;IAE9D,IAAIgB,QAAQI,MAAM,GAAG,GAAG;QACtB,MAAMC,SAASL,QAAQM,MAAM,CAC3B,CAAC,CAACC,UAAUC,YAAY,EAAEC,UAAUC,OAAOC;YACzC,MAAM,GAAGC,OAAOC,KAAK,GAAGJ,SAASb,MAAM,CAAC,CAACV,MAAQA,QAAQY;YAEzD,kEAAkE;YAClE,aAAa;YACb,MAAMgB,SAASrB,MAAMsB,KAA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AAmE;YACnEjE;YACAD;YAEAmE,SAAS;gBACP,IAAO,CAAA;wBACL/D;wBACAM;oBACF,CAAA;aACD;QACH;QAEA,IAAI,CAACmD,MAAMhE,MAAM;YACf,MAAM,IAAI+D,MAAM;QAClB;QAEA,OAAO;YACL/D,MAAMgE,KAAKhE,IAAI;YACfE,WAAW8D,KAAKO,GAAG;YACnBlE,UAAUzB,MAAMC,IAAI,CAACwB;QACvB;IACF,EAAE,OAAOmE,OAAO;QACd,MAAM,IAAIT,MAAM,CAAC,8BAA8B,EAAES,MAAMC,OAAO,CAAC,CAAC;IAClE;AACF"}
|
package/dist/esm/structs.js
CHANGED
|
@@ -1,8 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { union } from '@metamask/snaps-sdk';
|
|
2
|
+
import { assert, isObject } from '@metamask/utils';
|
|
2
3
|
import { bold, green, red } from 'chalk';
|
|
3
4
|
import { resolve } from 'path';
|
|
4
|
-
import { Struct, StructError, create, string, coerce } from 'superstruct';
|
|
5
|
+
import { is, validate, type as superstructType, Struct, StructError, create, string, coerce as superstructCoerce } from 'superstruct';
|
|
5
6
|
import { indent } from './strings';
|
|
7
|
+
/**
|
|
8
|
+
* Colorize a value with a color function. This is useful for colorizing values
|
|
9
|
+
* in error messages. If colorization is disabled, the original value is
|
|
10
|
+
* returned.
|
|
11
|
+
*
|
|
12
|
+
* @param value - The value to colorize.
|
|
13
|
+
* @param colorFunction - The color function to use.
|
|
14
|
+
* @param enabled - Whether to colorize the value.
|
|
15
|
+
* @returns The colorized value, or the original value if colorization is
|
|
16
|
+
* disabled.
|
|
17
|
+
*/ function color(value, colorFunction, enabled) {
|
|
18
|
+
if (enabled) {
|
|
19
|
+
return colorFunction(value);
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
6
23
|
/**
|
|
7
24
|
* A wrapper of `superstruct`'s `string` struct that coerces a value to a string
|
|
8
25
|
* and resolves it relative to the current working directory. This is useful
|
|
@@ -22,7 +39,7 @@ import { indent } from './strings';
|
|
|
22
39
|
* console.log(value.file); // /process/cwd/path/to/file
|
|
23
40
|
* ```
|
|
24
41
|
*/ export function file() {
|
|
25
|
-
return
|
|
42
|
+
return superstructCoerce(string(), string(), (value)=>{
|
|
26
43
|
return resolve(process.cwd(), value);
|
|
27
44
|
});
|
|
28
45
|
}
|
|
@@ -41,12 +58,12 @@ import { indent } from './strings';
|
|
|
41
58
|
});
|
|
42
59
|
}
|
|
43
60
|
export class SnapsStructError extends StructError {
|
|
44
|
-
constructor(struct, prefix, suffix, failure, failures){
|
|
61
|
+
constructor(struct, prefix, suffix, failure, failures, colorize = true){
|
|
45
62
|
super(failure, failures);
|
|
46
63
|
this.name = 'SnapsStructError';
|
|
47
64
|
this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
|
|
48
65
|
...failures()
|
|
49
|
-
])}${suffix ? `\n\n${suffix}` : ''}`;
|
|
66
|
+
], colorize)}${suffix ? `\n\n${suffix}` : ''}`;
|
|
50
67
|
}
|
|
51
68
|
}
|
|
52
69
|
/**
|
|
@@ -70,9 +87,10 @@ export class SnapsStructError extends StructError {
|
|
|
70
87
|
* @param options.suffix - The suffix to add to the error message. Defaults to
|
|
71
88
|
* an empty string.
|
|
72
89
|
* @param options.error - The `superstruct` error to wrap.
|
|
90
|
+
* @param options.colorize - Whether to colorize the value. Defaults to `true`.
|
|
73
91
|
* @returns The `SnapsStructError`.
|
|
74
|
-
*/ export function getError({ struct, prefix, suffix = '', error }) {
|
|
75
|
-
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
|
|
92
|
+
*/ export function getError({ struct, prefix, suffix = '', error, colorize }) {
|
|
93
|
+
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()), colorize);
|
|
76
94
|
}
|
|
77
95
|
/**
|
|
78
96
|
* A wrapper of `superstruct`'s `create` function that throws a
|
|
@@ -118,25 +136,27 @@ export class SnapsStructError extends StructError {
|
|
|
118
136
|
* Get the union struct names from a struct.
|
|
119
137
|
*
|
|
120
138
|
* @param struct - The struct.
|
|
139
|
+
* @param colorize - Whether to colorize the value. Defaults to `true`.
|
|
121
140
|
* @returns The union struct names, or `null` if the struct is not a union
|
|
122
141
|
* struct.
|
|
123
|
-
*/ export function getUnionStructNames(struct) {
|
|
142
|
+
*/ export function getUnionStructNames(struct, colorize = true) {
|
|
124
143
|
if (Array.isArray(struct.schema)) {
|
|
125
|
-
return struct.schema.map(({ type })=>
|
|
144
|
+
return struct.schema.map(({ type })=>color(type, green, colorize));
|
|
126
145
|
}
|
|
127
146
|
return null;
|
|
128
147
|
}
|
|
129
148
|
/**
|
|
130
|
-
* Get
|
|
149
|
+
* Get an error prefix from a `superstruct` failure. This is useful for
|
|
131
150
|
* formatting the error message returned by `superstruct`.
|
|
132
151
|
*
|
|
133
152
|
* @param failure - The `superstruct` failure.
|
|
153
|
+
* @param colorize - Whether to colorize the value. Defaults to `true`.
|
|
134
154
|
* @returns The error prefix.
|
|
135
|
-
*/ export function getStructErrorPrefix(failure) {
|
|
155
|
+
*/ export function getStructErrorPrefix(failure, colorize = true) {
|
|
136
156
|
if (failure.type === 'never' || failure.path.length === 0) {
|
|
137
157
|
return '';
|
|
138
158
|
}
|
|
139
|
-
return `At path: ${
|
|
159
|
+
return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;
|
|
140
160
|
}
|
|
141
161
|
/**
|
|
142
162
|
* Get a string describing the failure. This is similar to the `message`
|
|
@@ -145,13 +165,14 @@ export class SnapsStructError extends StructError {
|
|
|
145
165
|
*
|
|
146
166
|
* @param struct - The struct that caused the failure.
|
|
147
167
|
* @param failure - The `superstruct` failure.
|
|
168
|
+
* @param colorize - Whether to colorize the value. Defaults to `true`.
|
|
148
169
|
* @returns A string describing the failure.
|
|
149
|
-
*/ export function getStructFailureMessage(struct, failure) {
|
|
150
|
-
const received =
|
|
151
|
-
const prefix = getStructErrorPrefix(failure);
|
|
170
|
+
*/ export function getStructFailureMessage(struct, failure, colorize = true) {
|
|
171
|
+
const received = color(JSON.stringify(failure.value), red, colorize);
|
|
172
|
+
const prefix = getStructErrorPrefix(failure, colorize);
|
|
152
173
|
if (failure.type === 'union') {
|
|
153
174
|
const childStruct = getStructFromPath(struct, failure.path);
|
|
154
|
-
const unionNames = getUnionStructNames(childStruct);
|
|
175
|
+
const unionNames = getUnionStructNames(childStruct, colorize);
|
|
155
176
|
if (unionNames) {
|
|
156
177
|
return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
|
|
157
178
|
}
|
|
@@ -160,13 +181,17 @@ export class SnapsStructError extends StructError {
|
|
|
160
181
|
if (failure.type === 'literal') {
|
|
161
182
|
// Superstruct's failure does not provide information about which literal
|
|
162
183
|
// value was expected, so we need to parse the message to get the literal.
|
|
163
|
-
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${
|
|
184
|
+
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${color('$1', green, colorize)}\`,`).replace(/, but received: (.+)/u, `, but received: ${color('$1', red, colorize)}`);
|
|
164
185
|
return `${prefix}${message}.`;
|
|
165
186
|
}
|
|
166
187
|
if (failure.type === 'never') {
|
|
167
|
-
return `Unknown key: ${
|
|
188
|
+
return `Unknown key: ${color(failure.path.join('.'), bold, colorize)}, received: ${received}.`;
|
|
168
189
|
}
|
|
169
|
-
|
|
190
|
+
if (failure.refinement === 'size') {
|
|
191
|
+
const message = failure.message.replace(/length between `(\d+)` and `(\d+)`/u, `length between ${color('$1', green, colorize)} and ${color('$2', green, colorize)},`).replace(/length of `(\d+)`/u, `length of ${color('$1', red, colorize)}`).replace(/a array/u, 'an array');
|
|
192
|
+
return `${prefix}${message}.`;
|
|
193
|
+
}
|
|
194
|
+
return `${prefix}Expected a value of type ${color(failure.type, green, colorize)}, but received: ${received}.`;
|
|
170
195
|
}
|
|
171
196
|
/**
|
|
172
197
|
* Get a string describing the errors. This formats all the errors in a
|
|
@@ -174,10 +199,97 @@ export class SnapsStructError extends StructError {
|
|
|
174
199
|
*
|
|
175
200
|
* @param struct - The struct that caused the failures.
|
|
176
201
|
* @param failures - The `superstruct` failures.
|
|
202
|
+
* @param colorize - Whether to colorize the value. Defaults to `true`.
|
|
177
203
|
* @returns A string describing the errors.
|
|
178
|
-
*/ export function getStructErrorMessage(struct, failures) {
|
|
179
|
-
const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure)}`));
|
|
204
|
+
*/ export function getStructErrorMessage(struct, failures, colorize = true) {
|
|
205
|
+
const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure, colorize)}`));
|
|
180
206
|
return formattedFailures.join('\n');
|
|
181
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* Validate a union struct, and throw readable errors if the value does not
|
|
210
|
+
* satisfy the struct. This is useful for improving the error messages returned
|
|
211
|
+
* by `superstruct`.
|
|
212
|
+
*
|
|
213
|
+
* @param value - The value to validate.
|
|
214
|
+
* @param struct - The `superstruct` union struct to validate the value against.
|
|
215
|
+
* This struct must be a union of object structs, and must have at least one
|
|
216
|
+
* shared key to validate against.
|
|
217
|
+
* @param structKey - The key to validate against. This key must be present in
|
|
218
|
+
* all the object structs in the union struct, and is expected to be a literal
|
|
219
|
+
* value.
|
|
220
|
+
* @param coerce - Whether to coerce the value to satisfy the struct. Defaults
|
|
221
|
+
* to `false`.
|
|
222
|
+
* @returns The validated value.
|
|
223
|
+
* @throws If the value does not satisfy the struct.
|
|
224
|
+
* @example
|
|
225
|
+
* const struct = union([
|
|
226
|
+
* object({ type: literal('a'), value: string() }),
|
|
227
|
+
* object({ type: literal('b'), value: number() }),
|
|
228
|
+
* object({ type: literal('c'), value: boolean() }),
|
|
229
|
+
* // ...
|
|
230
|
+
* ]);
|
|
231
|
+
*
|
|
232
|
+
* // At path: type — Expected the value to be one of: "a", "b", "c", but received: "d".
|
|
233
|
+
* validateUnion({ type: 'd', value: 'foo' }, struct, 'type');
|
|
234
|
+
*
|
|
235
|
+
* // At path: value — Expected a value of type string, but received: 42.
|
|
236
|
+
* validateUnion({ type: 'a', value: 42 }, struct, 'value');
|
|
237
|
+
*/ export function validateUnion(value, struct, structKey, coerce = false) {
|
|
238
|
+
assert(struct.schema, 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.');
|
|
239
|
+
assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');
|
|
240
|
+
const keyUnion = struct.schema.map((innerStruct)=>innerStruct.schema[structKey]);
|
|
241
|
+
const key = superstructType({
|
|
242
|
+
[structKey]: union(keyUnion)
|
|
243
|
+
});
|
|
244
|
+
const [keyError] = validate(value, key, {
|
|
245
|
+
coerce
|
|
246
|
+
});
|
|
247
|
+
if (keyError) {
|
|
248
|
+
throw new Error(getStructFailureMessage(key, keyError.failures()[0], false));
|
|
249
|
+
}
|
|
250
|
+
// At this point it's guaranteed that the value is an object, so we can safely
|
|
251
|
+
// cast it to a Record.
|
|
252
|
+
const objectValue = value;
|
|
253
|
+
const objectStructs = struct.schema.filter((innerStruct)=>is(objectValue[structKey], innerStruct.schema[structKey]));
|
|
254
|
+
assert(objectStructs.length > 0, 'Expected a struct to match the value.');
|
|
255
|
+
// We need to validate the value against all the object structs that match the
|
|
256
|
+
// struct key, and return the first validated value.
|
|
257
|
+
const validationResults = objectStructs.map((objectStruct)=>validate(objectValue, objectStruct, {
|
|
258
|
+
coerce
|
|
259
|
+
}));
|
|
260
|
+
const validatedValue = validationResults.find(([error])=>!error);
|
|
261
|
+
if (validatedValue) {
|
|
262
|
+
return validatedValue[1];
|
|
263
|
+
}
|
|
264
|
+
assert(validationResults[0][0], 'Expected at least one error.');
|
|
265
|
+
// If there is no validated value, we need to find the error with the least
|
|
266
|
+
// number of failures (with the assumption that it's the most specific error).
|
|
267
|
+
const validationError = validationResults.reduce((error, [innerError])=>{
|
|
268
|
+
assert(innerError, 'Expected an error.');
|
|
269
|
+
if (innerError.failures().length < error.failures().length) {
|
|
270
|
+
return innerError;
|
|
271
|
+
}
|
|
272
|
+
return error;
|
|
273
|
+
}, validationResults[0][0]);
|
|
274
|
+
throw new Error(getStructFailureMessage(struct, validationError.failures()[0], false));
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Create a value with the coercion logic of a union struct, and throw readable
|
|
278
|
+
* errors if the value does not satisfy the struct. This is useful for improving
|
|
279
|
+
* the error messages returned by `superstruct`.
|
|
280
|
+
*
|
|
281
|
+
* @param value - The value to validate.
|
|
282
|
+
* @param struct - The `superstruct` union struct to validate the value against.
|
|
283
|
+
* This struct must be a union of object structs, and must have at least one
|
|
284
|
+
* shared key to validate against.
|
|
285
|
+
* @param structKey - The key to validate against. This key must be present in
|
|
286
|
+
* all the object structs in the union struct, and is expected to be a literal
|
|
287
|
+
* value.
|
|
288
|
+
* @returns The validated value.
|
|
289
|
+
* @throws If the value does not satisfy the struct.
|
|
290
|
+
* @see validateUnion
|
|
291
|
+
*/ export function createUnion(value, struct, structKey) {
|
|
292
|
+
return validateUnion(value, struct, structKey, true);
|
|
293
|
+
}
|
|
182
294
|
|
|
183
295
|
//# sourceMappingURL=structs.js.map
|
package/dist/esm/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 } from 'superstruct';\nimport { Struct, StructError, create, string, coerce } from 'superstruct';\nimport type { AnyStruct } 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 `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":["isObject","bold","green","red","resolve","Struct","StructError","create","string","coerce","indent","file","value","process","cwd","named","name","struct","type","SnapsStructError","constructor","prefix","suffix","failure","failures","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","schema","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","JSON","stringify","childStruct","unionNames","replace","formattedFailures"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB;AAC3C,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SAASC,MAAM,EAAEC,WAAW,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,cAAc;AAG1E,SAASC,MAAM,QAAQ,YAAY;AA6BnC;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC;IACd,OAAOF,OAAOD,UAAUA,UAAU,CAACI;QACjC,OAAOR,QAAQS,QAAQC,GAAG,IAAIF;IAChC;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASG,MACdC,IAAY,EACZC,MAA4B;IAE5B,OAAO,IAAIZ,OAAO;QAChB,GAAGY,MAAM;QACTC,MAAMF;IACR;AACF;AAEA,OAAO,MAAMG,yBAAuCb;IAClDc,YACEH,MAA4B,EAC5BI,MAAc,EACdC,MAAc,EACdC,OAAoB,EACpBC,QAAkC,CAClC;QACA,KAAK,CAACD,SAASC;QAEf,IAAI,CAACR,IAAI,GAAG;QACZ,IAAI,CAACS,OAAO,GAAG,CAAC,EAAEJ,OAAO,KAAK,EAAEK,sBAAsBT,QAAQ;eACzDO;SACJ,EAAE,EAAEF,SAAS,CAAC,IAAI,EAAEA,OAAO,CAAC,GAAG,GAAG,CAAC;IACtC;AACF;AASA;;;;;;;CAOC,GACD,OAAO,UAAUK,iBACfC,KAAa;IAEb,KAAK,MAAMC,QAAQD,MAAO;QACxB,MAAMC;IACR;AACF;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASC,SAAuB,EACrCb,MAAM,EACNI,MAAM,EACNC,SAAS,EAAE,EACXS,KAAK,EACyB;IAC9B,OAAO,IAAIZ,iBAAiBF,QAAQI,QAAQC,QAAQS,OAAO,IAC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mptyArray } from '@metamask/utils';\nimport { assert, isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport {\n is,\n validate,\n type as superstructType,\n Struct,\n StructError,\n create,\n string,\n coerce as superstructCoerce,\n} from 'superstruct';\nimport type { AnyStruct } 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 * Colorize a value with a color function. This is useful for colorizing values\n * in error messages. If colorization is disabled, the original value is\n * returned.\n *\n * @param value - The value to colorize.\n * @param colorFunction - The color function to use.\n * @param enabled - Whether to colorize the value.\n * @returns The colorized value, or the original value if colorization is\n * disabled.\n */\nfunction color(\n value: string,\n colorFunction: (value: string) => string,\n enabled: boolean,\n) {\n if (enabled) {\n return colorFunction(value);\n }\n\n return value;\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 superstructCoerce(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 colorize = true,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(\n struct,\n [...failures()],\n colorize,\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 colorize?: boolean;\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 * @param options.colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n colorize,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(\n struct,\n prefix,\n suffix,\n error,\n () => arrayToGenerator(error.failures()),\n colorize,\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 * @param colorize - Whether to colorize the value. Defaults to `true`.\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 colorize = true,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => color(type, green, colorize));\n }\n\n return null;\n}\n\n/**\n * Get an 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 * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure, colorize = true) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;\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 * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n colorize = true,\n) {\n const received = color(JSON.stringify(failure.value), red, colorize);\n const prefix = getStructErrorPrefix(failure, colorize);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct, colorize);\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(\n /the literal `(.+)`,/u,\n `the value to be \\`${color('$1', green, colorize)}\\`,`,\n )\n .replace(\n /, but received: (.+)/u,\n `, but received: ${color('$1', red, colorize)}`,\n );\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${color(\n failure.path.join('.'),\n bold,\n colorize,\n )}, received: ${received}.`;\n }\n\n if (failure.refinement === 'size') {\n const message = failure.message\n .replace(\n /length between `(\\d+)` and `(\\d+)`/u,\n `length between ${color('$1', green, colorize)} and ${color(\n '$2',\n green,\n colorize,\n )},`,\n )\n .replace(/length of `(\\d+)`/u, `length of ${color('$1', red, colorize)}`)\n .replace(/a array/u, 'an array');\n\n return `${prefix}${message}.`;\n }\n\n return `${prefix}Expected a value of type ${color(\n failure.type,\n green,\n colorize,\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 * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n colorize = true,\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure, colorize)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n\n/**\n * Validate a union struct, and throw readable errors if the value does not\n * satisfy the struct. This is useful for improving the error messages returned\n * by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @param coerce - Whether to coerce the value to satisfy the struct. Defaults\n * to `false`.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @example\n * const struct = union([\n * object({ type: literal('a'), value: string() }),\n * object({ type: literal('b'), value: number() }),\n * object({ type: literal('c'), value: boolean() }),\n * // ...\n * ]);\n *\n * // At path: type — Expected the value to be one of: \"a\", \"b\", \"c\", but received: \"d\".\n * validateUnion({ type: 'd', value: 'foo' }, struct, 'type');\n *\n * // At path: value — Expected a value of type string, but received: 42.\n * validateUnion({ type: 'a', value: 42 }, struct, 'value');\n */\nexport function validateUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n coerce = false,\n) {\n assert(\n struct.schema,\n 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.',\n );\n assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');\n\n const keyUnion = struct.schema.map(\n (innerStruct) => innerStruct.schema[structKey],\n // This is guaranteed to be a non-empty array by the assertion above. We\n // need to cast it since `superstruct` requires a non-empty array of structs\n // for the `union` struct.\n ) as NonEmptyArray<Struct>;\n\n const key = superstructType({\n [structKey]: union(keyUnion),\n });\n\n const [keyError] = validate(value, key, { coerce });\n if (keyError) {\n throw new Error(\n getStructFailureMessage(key, keyError.failures()[0], false),\n );\n }\n\n // At this point it's guaranteed that the value is an object, so we can safely\n // cast it to a Record.\n const objectValue = value as Record<PropertyKey, unknown>;\n const objectStructs = struct.schema.filter((innerStruct) =>\n is(objectValue[structKey], innerStruct.schema[structKey]),\n );\n\n assert(objectStructs.length > 0, 'Expected a struct to match the value.');\n\n // We need to validate the value against all the object structs that match the\n // struct key, and return the first validated value.\n const validationResults = objectStructs.map((objectStruct) =>\n validate(objectValue, objectStruct, { coerce }),\n );\n\n const validatedValue = validationResults.find(([error]) => !error);\n if (validatedValue) {\n return validatedValue[1];\n }\n\n assert(validationResults[0][0], 'Expected at least one error.');\n\n // If there is no validated value, we need to find the error with the least\n // number of failures (with the assumption that it's the most specific error).\n const validationError = validationResults.reduce((error, [innerError]) => {\n assert(innerError, 'Expected an error.');\n if (innerError.failures().length < error.failures().length) {\n return innerError;\n }\n\n return error;\n }, validationResults[0][0]);\n\n throw new Error(\n getStructFailureMessage(struct, validationError.failures()[0], false),\n );\n}\n\n/**\n * Create a value with the coercion logic of a union struct, and throw readable\n * errors if the value does not satisfy the struct. 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` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @see validateUnion\n */\nexport function createUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n) {\n return validateUnion(value, struct, structKey, true);\n}\n"],"names":["union","assert","isObject","bold","green","red","resolve","is","validate","type","superstructType","Struct","StructError","create","string","coerce","superstructCoerce","indent","color","value","colorFunction","enabled","file","process","cwd","named","name","struct","SnapsStructError","constructor","prefix","suffix","failure","failures","colorize","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","schema","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","JSON","stringify","childStruct","unionNames","replace","refinement","formattedFailures","validateUnion","structKey","keyUnion","innerStruct","keyError","Error","objectValue","objectStructs","filter","validationResults","objectStruct","validatedValue","find","validationError","innerError","createUnion"],"mappings":"AAAA,SAASA,KAAK,QAAQ,sBA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AC9E,uBAAuB;IACvB,MAAMsC,cAAcpD;IACpB,MAAMqD,gBAAgB7C,OAAOqB,MAAM,CAACyB,MAAM,CAAC,CAACL,cAC1C7D,GAAGgE,WAAW,CAACL,UAAU,EAAEE,YAAYpB,MAAM,CAACkB,UAAU;IAG1DjE,OAAOuE,cAAclB,MAAM,GAAG,GAAG;IAEjC,8EAA8E;IAC9E,oDAAoD;IACpD,MAAMoB,oBAAoBF,cAAcpB,GAAG,CAAC,CAACuB,eAC3CnE,SAAS+D,aAAaI,cAAc;YAAE5D;QAAO;IAG/C,MAAM6D,iBAAiBF,kBAAkBG,IAAI,CAAC,CAAC,CAACpC,MAAM,GAAK,CAACA;IAC5D,IAAImC,gBAAgB;QAClB,OAAOA,cAAc,CAAC,EAAE;IAC1B;IAEA3E,OAAOyE,iBAAiB,CAAC,EAAE,CAAC,EAAE,EAAE;IAEhC,2EAA2E;IAC3E,8EAA8E;IAC9E,MAAMI,kBAAkBJ,kBAAkB7B,MAAM,CAAC,CAACJ,OAAO,CAACsC,WAAW;QACnE9E,OAAO8E,YAAY;QACnB,IAAIA,WAAW9C,QAAQ,GAAGqB,MAAM,GAAGb,MAAMR,QAAQ,GAAGqB,MAAM,EAAE;YAC1D,OAAOyB;QACT;QAEA,OAAOtC;IACT,GAAGiC,iBAAiB,CAAC,EAAE,CAAC,EAAE;IAE1B,MAAM,IAAIJ,MACRd,wBAAwB7B,QAAQmD,gBAAgB7C,QAAQ,EAAE,CAAC,EAAE,EAAE;AAEnE;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAAS+C,YACd7D,KAAc,EACdQ,MAA4B,EAC5BuC,SAAqB;IAErB,OAAOD,cAAc9C,OAAOQ,QAAQuC,WAAW;AACjD"}
|
package/dist/types/caveats.d.ts
CHANGED
|
@@ -34,5 +34,13 @@ export declare enum SnapCaveatType {
|
|
|
34
34
|
/**
|
|
35
35
|
* Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.
|
|
36
36
|
*/
|
|
37
|
-
ChainIds = "chainIds"
|
|
37
|
+
ChainIds = "chainIds",
|
|
38
|
+
/**
|
|
39
|
+
* Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.
|
|
40
|
+
*/
|
|
41
|
+
LookupMatchers = "lookupMatchers",
|
|
42
|
+
/**
|
|
43
|
+
* Caveat specifying the max request time for a handler endowment.
|
|
44
|
+
*/
|
|
45
|
+
MaxRequestTime = "maxRequestTime"
|
|
38
46
|
}
|
|
@@ -7,7 +7,8 @@ export declare enum HandlerType {
|
|
|
7
7
|
OnUpdate = "onUpdate",
|
|
8
8
|
OnNameLookup = "onNameLookup",
|
|
9
9
|
OnKeyringRequest = "onKeyringRequest",
|
|
10
|
-
OnHomePage = "onHomePage"
|
|
10
|
+
OnHomePage = "onHomePage",
|
|
11
|
+
OnUserInput = "onUserInput"
|
|
11
12
|
}
|
|
12
13
|
export declare type SnapHandler = {
|
|
13
14
|
/**
|