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AAE;gBACP,GAAG,EAAE,CAAC,CAAC;oBACL,GAAG;oBACH,OAAO;iBACR,CAAC;aACH;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC5C,CAAC;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,SAAS,EAAE,IAAI,CAAC,GAAG;YACnB,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC/B,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACpE,CAAC;AACH,CAAC","sourcesContent":["import 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"]}