@metamask/snaps-utils 8.10.0 → 9.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -1
- package/dist/eval-worker.cjs +1 -1
- package/dist/eval-worker.cjs.map +1 -1
- package/dist/eval-worker.mjs +1 -1
- package/dist/eval-worker.mjs.map +1 -1
- package/dist/fs.cjs +1 -1
- package/dist/fs.cjs.map +1 -1
- package/dist/fs.mjs +1 -1
- package/dist/fs.mjs.map +1 -1
- package/dist/iframe.cjs +0 -1
- package/dist/iframe.cjs.map +1 -1
- package/dist/iframe.d.cts +0 -1
- package/dist/iframe.d.cts.map +1 -1
- package/dist/iframe.d.mts +0 -1
- package/dist/iframe.d.mts.map +1 -1
- package/dist/iframe.mjs +0 -1
- package/dist/iframe.mjs.map +1 -1
- package/dist/index.cjs +0 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.executionenv.cjs +0 -1
- package/dist/index.executionenv.cjs.map +1 -1
- package/dist/index.executionenv.d.cts +0 -1
- package/dist/index.executionenv.d.cts.map +1 -1
- package/dist/index.executionenv.d.mts +0 -1
- package/dist/index.executionenv.d.mts.map +1 -1
- package/dist/index.executionenv.mjs +0 -1
- package/dist/index.executionenv.mjs.map +1 -1
- package/dist/index.mjs +0 -2
- package/dist/index.mjs.map +1 -1
- package/dist/json-rpc.cjs +2 -6
- package/dist/json-rpc.cjs.map +1 -1
- package/dist/json-rpc.d.cts.map +1 -1
- package/dist/json-rpc.d.mts.map +1 -1
- package/dist/json-rpc.mjs +2 -6
- package/dist/json-rpc.mjs.map +1 -1
- package/dist/manifest/manifest.cjs +1 -1
- package/dist/manifest/manifest.cjs.map +1 -1
- package/dist/manifest/manifest.d.cts +2 -2
- package/dist/manifest/manifest.d.cts.map +1 -1
- package/dist/manifest/manifest.d.mts +2 -2
- package/dist/manifest/manifest.d.mts.map +1 -1
- package/dist/manifest/manifest.mjs +1 -1
- package/dist/manifest/manifest.mjs.map +1 -1
- package/dist/manifest/validation.cjs +1 -2
- package/dist/manifest/validation.cjs.map +1 -1
- package/dist/manifest/validation.d.cts.map +1 -1
- package/dist/manifest/validation.d.mts.map +1 -1
- package/dist/manifest/validation.mjs +1 -2
- package/dist/manifest/validation.mjs.map +1 -1
- package/dist/manifest/validator-types.cjs.map +1 -1
- package/dist/manifest/validator-types.d.cts +1 -1
- package/dist/manifest/validator-types.d.cts.map +1 -1
- package/dist/manifest/validator-types.d.mts +1 -1
- package/dist/manifest/validator-types.d.mts.map +1 -1
- package/dist/manifest/validator-types.mjs.map +1 -1
- package/dist/manifest/validator.cjs.map +1 -1
- package/dist/manifest/validator.d.cts +1 -1
- package/dist/manifest/validator.d.cts.map +1 -1
- package/dist/manifest/validator.d.mts +1 -1
- package/dist/manifest/validator.d.mts.map +1 -1
- package/dist/manifest/validator.mjs.map +1 -1
- package/dist/manifest/validators/platform-version.cjs +1 -1
- package/dist/manifest/validators/platform-version.cjs.map +1 -1
- package/dist/manifest/validators/platform-version.mjs +1 -1
- package/dist/manifest/validators/platform-version.mjs.map +1 -1
- package/dist/mock.cjs +0 -3
- package/dist/mock.cjs.map +1 -1
- package/dist/mock.d.cts.map +1 -1
- package/dist/mock.d.mts.map +1 -1
- package/dist/mock.mjs +0 -3
- package/dist/mock.mjs.map +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.cjs.map +1 -1
- package/dist/node.mjs +1 -1
- package/dist/node.mjs.map +1 -1
- package/dist/post-process.cjs.map +1 -1
- package/dist/post-process.d.cts.map +1 -1
- package/dist/post-process.d.mts.map +1 -1
- package/dist/post-process.mjs.map +1 -1
- package/dist/snaps.cjs +21 -14
- package/dist/snaps.cjs.map +1 -1
- package/dist/snaps.d.cts +2 -8
- package/dist/snaps.d.cts.map +1 -1
- package/dist/snaps.d.mts +2 -8
- package/dist/snaps.d.mts.map +1 -1
- package/dist/snaps.mjs +22 -14
- package/dist/snaps.mjs.map +1 -1
- package/dist/types.cjs +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +3 -3
- package/dist/types.mjs.map +1 -1
- package/dist/ui.cjs +7 -5
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.d.cts.map +1 -1
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +7 -5
- package/dist/ui.mjs.map +1 -1
- package/dist/virtual-file/VirtualFile.cjs.map +1 -1
- package/dist/virtual-file/VirtualFile.mjs.map +1 -1
- package/package.json +11 -25
- package/dist/namespace.cjs +0 -136
- package/dist/namespace.cjs.map +0 -1
- package/dist/namespace.d.cts +0 -130
- package/dist/namespace.d.cts.map +0 -1
- package/dist/namespace.d.mts +0 -130
- package/dist/namespace.d.mts.map +0 -1
- package/dist/namespace.mjs +0 -126
- package/dist/namespace.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator-types.d.mts","sourceRoot":"","sources":["../../src/manifest/validator-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"validator-types.d.mts","sourceRoot":"","sources":["../../src/manifest/validator-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,yBAAqB;AACjD,OAAO,KAAK,EAAE,UAAU,EAAE,uBAAmB;AAC7C,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,qBAAiB;AAIhE,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE;IACjC,QAAQ,EAAE,YAAY,CAAC;CACxB,KAAK,UAAU,CAAC;IAAE,QAAQ,EAAE,YAAY,CAAA;CAAE,CAAC,CAAC;AAE7C,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG,SAAS,CAAC;AAEpD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,MAAM,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,YAAY,KAAK,IAAI,CAAC;CACvD,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,YAAY,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,EAAE,iBAAiB,CAAC;IAE5B;;;;;OAKG;IACH,cAAc,CAAC,EAAE,CACf,KAAK,EAAE,oBAAoB,EAC3B,OAAO,EAAE,gBAAgB,KACtB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1B;;;;;OAKG;IACH,aAAa,CAAC,EAAE,CACd,KAAK,EAAE,SAAS,EAChB,OAAO,EAAE,gBAAgB,KACtB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator-types.mjs","sourceRoot":"","sources":["../../src/manifest/validator-types.ts"],"names":[],"mappings":"","sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"validator-types.mjs","sourceRoot":"","sources":["../../src/manifest/validator-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { SnapManifest } from './validation';\nimport type { Promisable } from '../promise';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\n\n// Eslint uses patch based fixing, but it's too complex for our needs.\n// https://eslint.org/docs/latest/extend/custom-rules#applying-fixes\nexport type ValidatorFix = (files: {\n manifest: SnapManifest;\n}) => Promisable<{ manifest: SnapManifest }>;\n\nexport type ValidatorSeverity = 'error' | 'warning';\n\nexport type ValidatorContext = {\n report: (message: string, fix?: ValidatorFix) => void;\n};\n\nexport type ValidatorReport = {\n severity: ValidatorSeverity;\n message: string;\n fix?: ValidatorFix;\n};\n\nexport type ValidatorMeta = {\n severity: ValidatorSeverity;\n\n /**\n * 1. Run the validator on unverified files to ensure that the files are structurally sound.\n *\n * @param files - Files to be verified\n * @param context - Validator context to report errors\n */\n structureCheck?: (\n files: UnvalidatedSnapFiles,\n context: ValidatorContext,\n ) => void | Promise<void>;\n\n /**\n * 2. Run the validator after the files were checked to be structurally sound.\n *\n * @param files - Files to be verified\n * @param context - Validator context to report errors\n */\n semanticCheck?: (\n files: SnapFiles,\n context: ValidatorContext,\n ) => void | Promise<void>;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.cjs","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAyC;
|
|
1
|
+
{"version":3,"file":"validator.cjs","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAAyC;AASzC,0EAAkD;AAQlD,MAAM,OAAO;IAAb;QACE,YAAO,GAAsB,EAAE,CAAC;QAEhC,gCAAoC,SAAS,EAAC;IAkBhD,CAAC;IAhBC,MAAM,CAAC,OAAe,EAAE,GAAkB;QACxC,IAAA,cAAM,EAAC,uBAAA,IAAI,6BAAc,KAAK,SAAS,CAAC,CAAC;QACzC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;YAChB,QAAQ,EAAE,uBAAA,IAAI,6BAAc;YAC5B,OAAO;YACP,GAAG;SACJ,CAAC,CAAC;IACL,CAAC;IAED,mBAAmB,CAAC,QAAyC;QAC3D,uBAAA,IAAI,yBAAiB,QAAQ,CAAC,QAAQ,MAAA,CAAC;IACzC,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC;IACpE,CAAC;CACF;;AAED;;;;;;;;GAQG;AACH,iEAAiE;AACjE,8DAA8D;AAC9D,+BAA+B;AACxB,KAAK,UAAU,aAAa,CACjC,KAA2B,EAC3B,QAAyB,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAEzD,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;IAE9B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,OAAO,CAAC,mBAAmB,CAAC;YAC1B,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACxB,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC9C,CAAC;IACD,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;QACtB,OAAO;YACL,OAAO,EAAE,OAAO,CAAC,OAAO;SACzB,CAAC;IACJ,CAAC;IAED,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,OAAO,CAAC,mBAAmB,CAAC;YAC1B,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACxB,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC,KAAkB,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;IACD,OAAO;QACL,KAAK,EAAE,KAAkB;QACzB,OAAO,EAAE,OAAO,CAAC,OAAO;KACzB,CAAC;AACJ,CAAC;AA5BD,sCA4BC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,OAAyB;IAChD,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACtD,CAAC;AAFD,4BAEC","sourcesContent":["import { assert } from '@metamask/utils';\n\nimport type {\n ValidatorContext,\n ValidatorFix,\n ValidatorMeta,\n ValidatorReport,\n ValidatorSeverity,\n} from './validator-types';\nimport * as defaultValidators from './validators';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\n\nexport type ValidatorResults = {\n files?: SnapFiles;\n reports: ValidatorReport[];\n};\n\nclass Context implements ValidatorContext {\n reports: ValidatorReport[] = [];\n\n #nextSeverity?: ValidatorSeverity = undefined;\n\n report(message: string, fix?: ValidatorFix): void {\n assert(this.#nextSeverity !== undefined);\n this.reports.push({\n severity: this.#nextSeverity,\n message,\n fix,\n });\n }\n\n prepareForValidator(settings: { severity: ValidatorSeverity }) {\n this.#nextSeverity = settings.severity;\n }\n\n get hasErrors() {\n return this.reports.some((report) => report.severity === 'error');\n }\n}\n\n/**\n * Verify that snap files are completely valid.\n * First it runs validators on unparsed files to check structure.\n * Secondly it runs validators on parsed files to check semantics.\n *\n * @param files - All files required to run a snap.\n * @param rules - Validators to run.\n * @returns The validation results.\n */\n// TODO(ritave): snap.manifest.json and package.json should check\n// json parsing as well instead of assuming it's\n// already parsed\nexport async function runValidators(\n files: UnvalidatedSnapFiles,\n rules: ValidatorMeta[] = Object.values(defaultValidators),\n): Promise<ValidatorResults> {\n const context = new Context();\n\n for (const rule of rules) {\n context.prepareForValidator({\n severity: rule.severity,\n });\n await rule.structureCheck?.(files, context);\n }\n if (context.hasErrors) {\n return {\n reports: context.reports,\n };\n }\n\n for (const rule of rules) {\n context.prepareForValidator({\n severity: rule.severity,\n });\n await rule.semanticCheck?.(files as SnapFiles, context);\n }\n return {\n files: files as SnapFiles,\n reports: context.reports,\n };\n}\n\n/**\n * Get whether any reports has pending fixes.\n *\n * @param results - Results of the validation run.\n * @returns Whether there are fixes pending.\n */\nexport function hasFixes(results: ValidatorResults): boolean {\n return results.reports.some((report) => report.fix);\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { SnapFiles, UnvalidatedSnapFiles } from "../types.cjs";
|
|
2
1
|
import type { ValidatorMeta, ValidatorReport } from "./validator-types.cjs";
|
|
2
|
+
import type { SnapFiles, UnvalidatedSnapFiles } from "../types.cjs";
|
|
3
3
|
export type ValidatorResults = {
|
|
4
4
|
files?: SnapFiles;
|
|
5
5
|
reports: ValidatorReport[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.d.cts","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"validator.d.cts","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,aAAa,EACb,eAAe,EAEhB,8BAA0B;AAE3B,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,qBAAiB;AAEhE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,OAAO,EAAE,eAAe,EAAE,CAAC;CAC5B,CAAC;AAyBF;;;;;;;;GAQG;AAIH,wBAAsB,aAAa,CACjC,KAAK,EAAE,oBAAoB,EAC3B,KAAK,GAAE,aAAa,EAAqC,GACxD,OAAO,CAAC,gBAAgB,CAAC,CAyB3B;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAE3D"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { SnapFiles, UnvalidatedSnapFiles } from "../types.mjs";
|
|
2
1
|
import type { ValidatorMeta, ValidatorReport } from "./validator-types.mjs";
|
|
2
|
+
import type { SnapFiles, UnvalidatedSnapFiles } from "../types.mjs";
|
|
3
3
|
export type ValidatorResults = {
|
|
4
4
|
files?: SnapFiles;
|
|
5
5
|
reports: ValidatorReport[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.d.mts","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"validator.d.mts","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,aAAa,EACb,eAAe,EAEhB,8BAA0B;AAE3B,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,qBAAiB;AAEhE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,OAAO,EAAE,eAAe,EAAE,CAAC;CAC5B,CAAC;AAyBF;;;;;;;;GAQG;AAIH,wBAAsB,aAAa,CACjC,KAAK,EAAE,oBAAoB,EAC3B,KAAK,GAAE,aAAa,EAAqC,GACxD,OAAO,CAAC,gBAAgB,CAAC,CAyB3B;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAE3D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.mjs","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"validator.mjs","sourceRoot":"","sources":["../../src/manifest/validator.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,wBAAwB;AASzC,OAAO,KAAK,iBAAiB,+BAAqB;AAQlD,MAAM,OAAO;IAAb;QACE,YAAO,GAAsB,EAAE,CAAC;QAEhC,gCAAoC,SAAS,EAAC;IAkBhD,CAAC;IAhBC,MAAM,CAAC,OAAe,EAAE,GAAkB;QACxC,MAAM,CAAC,uBAAA,IAAI,6BAAc,KAAK,SAAS,CAAC,CAAC;QACzC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;YAChB,QAAQ,EAAE,uBAAA,IAAI,6BAAc;YAC5B,OAAO;YACP,GAAG;SACJ,CAAC,CAAC;IACL,CAAC;IAED,mBAAmB,CAAC,QAAyC;QAC3D,uBAAA,IAAI,yBAAiB,QAAQ,CAAC,QAAQ,MAAA,CAAC;IACzC,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC;IACpE,CAAC;CACF;;AAED;;;;;;;;GAQG;AACH,iEAAiE;AACjE,8DAA8D;AAC9D,+BAA+B;AAC/B,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,KAA2B,EAC3B,QAAyB,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAEzD,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;IAE9B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,OAAO,CAAC,mBAAmB,CAAC;YAC1B,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACxB,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC9C,CAAC;IACD,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;QACtB,OAAO;YACL,OAAO,EAAE,OAAO,CAAC,OAAO;SACzB,CAAC;IACJ,CAAC;IAED,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,OAAO,CAAC,mBAAmB,CAAC;YAC1B,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACxB,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC,KAAkB,EAAE,OAAO,CAAC,CAAC;IAC1D,CAAC;IACD,OAAO;QACL,KAAK,EAAE,KAAkB;QACzB,OAAO,EAAE,OAAO,CAAC,OAAO;KACzB,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAyB;IAChD,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import { assert } from '@metamask/utils';\n\nimport type {\n ValidatorContext,\n ValidatorFix,\n ValidatorMeta,\n ValidatorReport,\n ValidatorSeverity,\n} from './validator-types';\nimport * as defaultValidators from './validators';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\n\nexport type ValidatorResults = {\n files?: SnapFiles;\n reports: ValidatorReport[];\n};\n\nclass Context implements ValidatorContext {\n reports: ValidatorReport[] = [];\n\n #nextSeverity?: ValidatorSeverity = undefined;\n\n report(message: string, fix?: ValidatorFix): void {\n assert(this.#nextSeverity !== undefined);\n this.reports.push({\n severity: this.#nextSeverity,\n message,\n fix,\n });\n }\n\n prepareForValidator(settings: { severity: ValidatorSeverity }) {\n this.#nextSeverity = settings.severity;\n }\n\n get hasErrors() {\n return this.reports.some((report) => report.severity === 'error');\n }\n}\n\n/**\n * Verify that snap files are completely valid.\n * First it runs validators on unparsed files to check structure.\n * Secondly it runs validators on parsed files to check semantics.\n *\n * @param files - All files required to run a snap.\n * @param rules - Validators to run.\n * @returns The validation results.\n */\n// TODO(ritave): snap.manifest.json and package.json should check\n// json parsing as well instead of assuming it's\n// already parsed\nexport async function runValidators(\n files: UnvalidatedSnapFiles,\n rules: ValidatorMeta[] = Object.values(defaultValidators),\n): Promise<ValidatorResults> {\n const context = new Context();\n\n for (const rule of rules) {\n context.prepareForValidator({\n severity: rule.severity,\n });\n await rule.structureCheck?.(files, context);\n }\n if (context.hasErrors) {\n return {\n reports: context.reports,\n };\n }\n\n for (const rule of rules) {\n context.prepareForValidator({\n severity: rule.severity,\n });\n await rule.semanticCheck?.(files as SnapFiles, context);\n }\n return {\n files: files as SnapFiles,\n reports: context.reports,\n };\n}\n\n/**\n * Get whether any reports has pending fixes.\n *\n * @param results - Results of the validation run.\n * @returns Whether there are fixes pending.\n */\nexport function hasFixes(results: ValidatorResults): boolean {\n return results.reports.some((report) => report.fix);\n}\n"]}
|
|
@@ -14,7 +14,7 @@ exports.platformVersion = {
|
|
|
14
14
|
// file to avoid potentially loading the wrong version of the Snaps SDK.
|
|
15
15
|
const require = (0, module_1.createRequire)(files.manifest.path);
|
|
16
16
|
const packageJson = require.resolve('@metamask/snaps-sdk/package.json');
|
|
17
|
-
// eslint-disable-next-line import/no-dynamic-require
|
|
17
|
+
// eslint-disable-next-line import-x/no-dynamic-require
|
|
18
18
|
const actualVersion = require(packageJson).version;
|
|
19
19
|
if (!manifestPlatformVersion) {
|
|
20
20
|
context.report('The "platformVersion" field is missing from the manifest.', ({ manifest }) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-version.cjs","sourceRoot":"","sources":["../../../src/manifest/validators/platform-version.ts"],"names":[],"mappings":";;;AAAA,mCAAuC;AAIvC;;;GAGG;AACU,QAAA,eAAe,GAAkB;IAC5C,QAAQ,EAAE,OAAO;IACjB,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO;QAChC,MAAM,uBAAuB,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,eAAe,CAAC;QAEtE,2EAA2E;QAC3E,wEAAwE;QACxE,MAAM,OAAO,GAAG,IAAA,sBAAa,EAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAEnD,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAC;QACxE,
|
|
1
|
+
{"version":3,"file":"platform-version.cjs","sourceRoot":"","sources":["../../../src/manifest/validators/platform-version.ts"],"names":[],"mappings":";;;AAAA,mCAAuC;AAIvC;;;GAGG;AACU,QAAA,eAAe,GAAkB;IAC5C,QAAQ,EAAE,OAAO;IACjB,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO;QAChC,MAAM,uBAAuB,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,eAAe,CAAC;QAEtE,2EAA2E;QAC3E,wEAAwE;QACxE,MAAM,OAAO,GAAG,IAAA,sBAAa,EAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAEnD,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAC;QACxE,uDAAuD;QACvD,MAAM,aAAa,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC;QAEnD,IAAI,CAAC,uBAAuB,EAAE,CAAC;YAC7B,OAAO,CAAC,MAAM,CACZ,2DAA2D,EAC3D,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;gBACf,QAAQ,CAAC,eAAe,GAAG,aAAa,CAAC;gBACzC,OAAO,EAAE,QAAQ,EAAE,CAAC;YACtB,CAAC,CACF,CAAC;YAEF,OAAO;QACT,CAAC;QAED,IAAI,uBAAuB,KAAK,aAAa,EAAE,CAAC;YAC9C,OAAO,CAAC,MAAM,CACZ,6FAA6F,uBAAuB,gBAAgB,aAAa,IAAI,EACrJ,KAAK,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE;gBACrB,QAAQ,CAAC,eAAe,GAAG,aAAa,CAAC;gBACzC,OAAO,EAAE,QAAQ,EAAE,CAAC;YACtB,CAAC,CACF,CAAC;QACJ,CAAC;IACH,CAAC;CACF,CAAC","sourcesContent":["import { createRequire } from 'module';\n\nimport type { ValidatorMeta } from '../validator-types';\n\n/**\n * Check if the platform version in manifest matches the version of the Snaps\n * SDK.\n */\nexport const platformVersion: ValidatorMeta = {\n severity: 'error',\n async semanticCheck(files, context) {\n const manifestPlatformVersion = files.manifest.result.platformVersion;\n\n // Create a require function in the context of the location of the manifest\n // file to avoid potentially loading the wrong version of the Snaps SDK.\n const require = createRequire(files.manifest.path);\n\n const packageJson = require.resolve('@metamask/snaps-sdk/package.json');\n // eslint-disable-next-line import-x/no-dynamic-require\n const actualVersion = require(packageJson).version;\n\n if (!manifestPlatformVersion) {\n context.report(\n 'The \"platformVersion\" field is missing from the manifest.',\n ({ manifest }) => {\n manifest.platformVersion = actualVersion;\n return { manifest };\n },\n );\n\n return;\n }\n\n if (manifestPlatformVersion !== actualVersion) {\n context.report(\n `The \"platformVersion\" field in the manifest must match the version of the Snaps SDK. Got \"${manifestPlatformVersion}\", expected \"${actualVersion}\".`,\n async ({ manifest }) => {\n manifest.platformVersion = actualVersion;\n return { manifest };\n },\n );\n }\n },\n};\n"]}
|
|
@@ -11,7 +11,7 @@ export const platformVersion = {
|
|
|
11
11
|
// file to avoid potentially loading the wrong version of the Snaps SDK.
|
|
12
12
|
const require = createRequire(files.manifest.path);
|
|
13
13
|
const packageJson = require.resolve('@metamask/snaps-sdk/package.json');
|
|
14
|
-
// eslint-disable-next-line import/no-dynamic-require
|
|
14
|
+
// eslint-disable-next-line import-x/no-dynamic-require
|
|
15
15
|
const actualVersion = require(packageJson).version;
|
|
16
16
|
if (!manifestPlatformVersion) {
|
|
17
17
|
context.report('The "platformVersion" field is missing from the manifest.', ({ manifest }) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-version.mjs","sourceRoot":"","sources":["../../../src/manifest/validators/platform-version.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe;AAIvC;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAkB;IAC5C,QAAQ,EAAE,OAAO;IACjB,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO;QAChC,MAAM,uBAAuB,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,eAAe,CAAC;QAEtE,2EAA2E;QAC3E,wEAAwE;QACxE,MAAM,OAAO,GAAG,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAEnD,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAC;QACxE,
|
|
1
|
+
{"version":3,"file":"platform-version.mjs","sourceRoot":"","sources":["../../../src/manifest/validators/platform-version.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe;AAIvC;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAkB;IAC5C,QAAQ,EAAE,OAAO;IACjB,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO;QAChC,MAAM,uBAAuB,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,eAAe,CAAC;QAEtE,2EAA2E;QAC3E,wEAAwE;QACxE,MAAM,OAAO,GAAG,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAEnD,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAC;QACxE,uDAAuD;QACvD,MAAM,aAAa,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC;QAEnD,IAAI,CAAC,uBAAuB,EAAE,CAAC;YAC7B,OAAO,CAAC,MAAM,CACZ,2DAA2D,EAC3D,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;gBACf,QAAQ,CAAC,eAAe,GAAG,aAAa,CAAC;gBACzC,OAAO,EAAE,QAAQ,EAAE,CAAC;YACtB,CAAC,CACF,CAAC;YAEF,OAAO;QACT,CAAC;QAED,IAAI,uBAAuB,KAAK,aAAa,EAAE,CAAC;YAC9C,OAAO,CAAC,MAAM,CACZ,6FAA6F,uBAAuB,gBAAgB,aAAa,IAAI,EACrJ,KAAK,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE;gBACrB,QAAQ,CAAC,eAAe,GAAG,aAAa,CAAC;gBACzC,OAAO,EAAE,QAAQ,EAAE,CAAC;YACtB,CAAC,CACF,CAAC;QACJ,CAAC;IACH,CAAC;CACF,CAAC","sourcesContent":["import { createRequire } from 'module';\n\nimport type { ValidatorMeta } from '../validator-types';\n\n/**\n * Check if the platform version in manifest matches the version of the Snaps\n * SDK.\n */\nexport const platformVersion: ValidatorMeta = {\n severity: 'error',\n async semanticCheck(files, context) {\n const manifestPlatformVersion = files.manifest.result.platformVersion;\n\n // Create a require function in the context of the location of the manifest\n // file to avoid potentially loading the wrong version of the Snaps SDK.\n const require = createRequire(files.manifest.path);\n\n const packageJson = require.resolve('@metamask/snaps-sdk/package.json');\n // eslint-disable-next-line import-x/no-dynamic-require\n const actualVersion = require(packageJson).version;\n\n if (!manifestPlatformVersion) {\n context.report(\n 'The \"platformVersion\" field is missing from the manifest.',\n ({ manifest }) => {\n manifest.platformVersion = actualVersion;\n return { manifest };\n },\n );\n\n return;\n }\n\n if (manifestPlatformVersion !== actualVersion) {\n context.report(\n `The \"platformVersion\" field in the manifest must match the version of the Snaps SDK. Got \"${manifestPlatformVersion}\", expected \"${actualVersion}\".`,\n async ({ manifest }) => {\n manifest.platformVersion = actualVersion;\n return { manifest };\n },\n );\n }\n },\n};\n"]}
|
package/dist/mock.cjs
CHANGED
|
@@ -19,7 +19,6 @@ exports.ALL_APIS = [
|
|
|
19
19
|
* @returns A mocked snap provider.
|
|
20
20
|
*/
|
|
21
21
|
function getMockSnapGlobal() {
|
|
22
|
-
// eslint-disable-next-line @typescript-eslint/require-await
|
|
23
22
|
return { request: async () => true };
|
|
24
23
|
}
|
|
25
24
|
/**
|
|
@@ -29,7 +28,6 @@ function getMockSnapGlobal() {
|
|
|
29
28
|
*/
|
|
30
29
|
function getMockEthereumProvider() {
|
|
31
30
|
const mockProvider = new events_1.default();
|
|
32
|
-
// eslint-disable-next-line @typescript-eslint/require-await
|
|
33
31
|
mockProvider.request = async () => true;
|
|
34
32
|
return mockProvider;
|
|
35
33
|
}
|
|
@@ -50,7 +48,6 @@ const mockFunction = () => true;
|
|
|
50
48
|
class MockClass {
|
|
51
49
|
}
|
|
52
50
|
const handler = {
|
|
53
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
54
51
|
construct(Target, args) {
|
|
55
52
|
return new Proxy(new Target(...args), handler);
|
|
56
53
|
},
|
package/dist/mock.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock.cjs","sourceRoot":"","sources":["../src/mock.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA4B;AAC5B,oDAAkC;AAElC,iEAA0D;AAE1D,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;AAEpD,QAAA,QAAQ,GAAa;IAChC,GAAG,uCAAkB;IACrB,GA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AC;AACJ,CAAC,CAAC;AALW,QAAA,sBAAsB,0BAKjC","sourcesContent":["import crypto from 'crypto';\nimport EventEmitter from 'events';\n\nimport { DEFAULT_ENDOWMENTS } from './default-endowments';\n\nconst NETWORK_APIS = ['fetch', 'Request', 'Headers', 'Response'];\n\nexport const ALL_APIS: string[] = [\n ...DEFAULT_ENDOWMENTS,\n ...NETWORK_APIS,\n 'WebAssembly',\n];\n\ntype MockSnapGlobal = {\n request: () => Promise<any>;\n};\n\ntype MockEthereumProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap API, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapGlobal(): MockSnapGlobal {\n return { request: async () => true };\n}\n\n/**\n * Get a mock Ethereum provider, that always returns `true` for requests.\n *\n * @returns A mocked ethereum provider.\n */\nfunction getMockEthereumProvider(): MockEthereumProvider {\n const mockProvider = new EventEmitter() as Partial<MockEthereumProvider>;\n mockProvider.request = async () => true;\n return mockProvider as MockEthereumProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\n */\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\n */\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we\n// have types for them and can use that to generate mocks if needed.\nconst mockWindow: Record<string, unknown> = {\n crypto,\n SubtleCrypto: MockClass,\n};\n\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\n */\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? mockWindow[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\n */\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() },\n );\n};\n"]}
|
package/dist/mock.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock.d.cts","sourceRoot":"","sources":["../src/mock.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,QAAQ,EAAE,MAAM,EAI5B,CAAC;
|
|
1
|
+
{"version":3,"file":"mock.d.cts","sourceRoot":"","sources":["../src/mock.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,QAAQ,EAAE,MAAM,EAI5B,CAAC;AA8BF;;;;;GAKG;AACH,eAAO,MAAM,aAAa,UAAW,GAAG,YAC0B,CAAC;AAmEnE;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,2BAKlC,CAAC"}
|
package/dist/mock.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock.d.mts","sourceRoot":"","sources":["../src/mock.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,QAAQ,EAAE,MAAM,EAI5B,CAAC;
|
|
1
|
+
{"version":3,"file":"mock.d.mts","sourceRoot":"","sources":["../src/mock.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,QAAQ,EAAE,MAAM,EAI5B,CAAC;AA8BF;;;;;GAKG;AACH,eAAO,MAAM,aAAa,UAAW,GAAG,YAC0B,CAAC;AAmEnE;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,2BAKlC,CAAC"}
|
package/dist/mock.mjs
CHANGED
|
@@ -13,7 +13,6 @@ export const ALL_APIS = [
|
|
|
13
13
|
* @returns A mocked snap provider.
|
|
14
14
|
*/
|
|
15
15
|
function getMockSnapGlobal() {
|
|
16
|
-
// eslint-disable-next-line @typescript-eslint/require-await
|
|
17
16
|
return { request: async () => true };
|
|
18
17
|
}
|
|
19
18
|
/**
|
|
@@ -23,7 +22,6 @@ function getMockSnapGlobal() {
|
|
|
23
22
|
*/
|
|
24
23
|
function getMockEthereumProvider() {
|
|
25
24
|
const mockProvider = new EventEmitter();
|
|
26
|
-
// eslint-disable-next-line @typescript-eslint/require-await
|
|
27
25
|
mockProvider.request = async () => true;
|
|
28
26
|
return mockProvider;
|
|
29
27
|
}
|
|
@@ -43,7 +41,6 @@ const mockFunction = () => true;
|
|
|
43
41
|
class MockClass {
|
|
44
42
|
}
|
|
45
43
|
const handler = {
|
|
46
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
47
44
|
construct(Target, args) {
|
|
48
45
|
return new Proxy(new Target(...args), handler);
|
|
49
46
|
},
|
package/dist/mock.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock.mjs","sourceRoot":"","sources":["../src/mock.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,eAAe;AAC5B,OAAO,YAAY,eAAe;AAElC,OAAO,EAAE,kBAAkB,EAAE,iCAA6B;AAE1D,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAA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AG,CAAC,EAAE,CAAC,EAC7D,EAAE,IAAI,EAAE,iBAAiB,EAAE,EAAE,QAAQ,EAAE,uBAAuB,EAAE,EAAE,CACnE,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import crypto from 'crypto';\nimport EventEmitter from 'events';\n\nimport { DEFAULT_ENDOWMENTS } from './default-endowments';\n\nconst NETWORK_APIS = ['fetch', 'Request', 'Headers', 'Response'];\n\nexport const ALL_APIS: string[] = [\n ...DEFAULT_ENDOWMENTS,\n ...NETWORK_APIS,\n 'WebAssembly',\n];\n\ntype MockSnapGlobal = {\n request: () => Promise<any>;\n};\n\ntype MockEthereumProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap API, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapGlobal(): MockSnapGlobal {\n return { request: async () => true };\n}\n\n/**\n * Get a mock Ethereum provider, that always returns `true` for requests.\n *\n * @returns A mocked ethereum provider.\n */\nfunction getMockEthereumProvider(): MockEthereumProvider {\n const mockProvider = new EventEmitter() as Partial<MockEthereumProvider>;\n mockProvider.request = async () => true;\n return mockProvider as MockEthereumProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\n */\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\n */\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we\n// have types for them and can use that to generate mocks if needed.\nconst mockWindow: Record<string, unknown> = {\n crypto,\n SubtleCrypto: MockClass,\n};\n\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\n */\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? mockWindow[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\n */\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() },\n );\n};\n"]}
|
package/dist/node.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
/* eslint-disable import/export */
|
|
2
|
+
/* eslint-disable import-x/export */
|
|
3
3
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
4
4
|
if (k2 === undefined) k2 = k;
|
|
5
5
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
package/dist/node.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.cjs","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":";AAAA,
|
|
1
|
+
{"version":3,"file":"node.cjs","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":";AAAA,oCAAoC;;;;;;;;;;;;;;;;AAEpC,8CAAkB;AAClB,6CAAuB;AACvB,2CAAqB;AACrB,sDAAgC;AAChC,6CAAuB;AACvB,qDAA+B;AAC/B,0DAAoC","sourcesContent":["/* eslint-disable import-x/export */\n\nexport * from '.';\nexport * from './eval';\nexport * from './fs';\nexport * from './manifest/node';\nexport * from './mock';\nexport * from './post-process';\nexport * from './virtual-file/node';\n"]}
|
package/dist/node.mjs
CHANGED
package/dist/node.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.mjs","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"node.mjs","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,oCAAoC;AAEpC,4BAAkB;AAClB,2BAAuB;AACvB,yBAAqB;AACrB,oCAAgC;AAChC,2BAAuB;AACvB,mCAA+B;AAC/B,wCAAoC","sourcesContent":["/* eslint-disable import-x/export */\n\nexport * from '.';\nexport * from './eval';\nexport * from './fs';\nexport * from './manifest/node';\nexport * from './mock';\nexport * from './post-process';\nexport * from './virtual-file/node';\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-process.cjs","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AAEA,sCAAsD;AAEtD,wCAOsB;AAgDtB,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,sNAAgM,CAAA;AAClM,CAAC,EAFW,kBAAkB,kCAAlB,kBAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,iDAAiD,CAAC;AAEtE,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,IAAA,uBAAe,EAAC,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAExE,MAAM,WAAW,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEtC,CAAC,CAAC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int/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"]}
|
|
1
|
+
{"version":3,"file":"post-process.cjs","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":";;;AACA,sCAAsD;AAEtD,wCAOsB;AAgDtB,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,sNAAgM,CAAA;AAClM,CAAC,EAFW,kBAAkB,kCAAlB,kBAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,iDAAiD,CAAC;AAEtE,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,IAAA,uBAAe,EAAC,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAExE,MAAM,WAAW,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEtC,CAAC,CAAC;AAEH,MAAM,iBAAiB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAE5C,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,eAAQ,CAAC,SAAS,CAAC;;CAEpD,CAAC,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,SAAS,WAAW,CAAC,KAAa;IAChC,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACxC,OAAO,CACL,MAAM;QACJ,oEAAoE;QACpE,sEAAsE;SACrE,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,EAAE,I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,EAAE;YAC/B,kDAAkD;YAClD,UAAU,EAAE,KAAK;YAEjB,UAAU,EAAE;gBACV,sEAAsE;gBACtE,UAAU,EAAE,IAAI;gBAEhB,sEAAsE;gBACtE,wEAAwE;gBACxE,aAAa,EAAE,CAAC,aAAa;aAC9B;YAED,mEAAmE;YACnE,yEAAyE;YACzE,OAAO,EAAE,KAAK;YAEd,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnE,cAAc;YACd,UAAU;YAEV,OAAO,EAAE;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;AAhSD,8CAgSC","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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-process.d.cts","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"post-process.d.cts","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":"AAYA;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,cAAc,CAAC,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;IACtC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,SAAS,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAC/B,cAAc,CAAC,EAAE,SAAS,CAAC;CAC5B,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,SAAS,GAAG,IAAI,CAAC;IAC7B,QAAQ,EAAE,kBAAkB,EAAE,CAAC;CAChC,CAAC;AAEF,oBAAY,kBAAkB;IAC5B,gBAAgB,gLAAgL;CACjM;AA+HD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,EACE,aAAoB,EACpB,SAAS,EAAE,UAAU,EACrB,cAAc,GACf,GAAE,OAAO,CAAC,kBAAkB,CAAM,GAClC,mBAAmB,CAyRrB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"post-process.d.mts","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"post-process.d.mts","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":"AAYA;;;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AAS,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":["// 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"]}
|
|
1
|
+
{"version":3,"file":"post-process.mjs","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,oBAAoB;AAEtD,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,eAAe,EAChB,qBAAqB;AAgDtB,MAAM,CAAN,IAAY,kBAEX;AAFD,WAAY,kBAAkB;IAC5B,sNAAgM,CAAA;AAClM,CAAC,EAFW,kBAAkB,KAAlB,kBAAkB,QAE7B;AAED,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAM,WAAW,GAAG,iDAAiD,CAAC;AAEtE,4EAA4E;AAC5E,cAAc;AACd,MAAM,sBAAsB,GAAG,eAAe,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAExE,MAAM,WAAW,GAAG,QAAQ,CAAC,SAAS,CAAC;;CAEtC,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C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBAExE,IAAI,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC/B,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;gBAChC,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;IAEF,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,EAAE;YAC/B,kDAAkD;YAClD,UAAU,EAAE,KAAK;YAEjB,UAAU,EAAE;gBACV,sEAAsE;gBACtE,UAAU,EAAE,IAAI;gBAEhB,sEAAsE;gBACtE,wEAAwE;gBACxE,aAAa,EAAE,CAAC,aAAa;aAC9B;YAED,mEAAmE;YACnE,yEAAyE;YACzE,OAAO,EAAE,KAAK;YAEd,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnE,cAAc;YACd,UAAU;YAEV,OAAO,EAAE;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"]}
|