@metamask/snaps-utils 0.35.1-flask.1 → 1.0.0-prerelease.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 +5 -46
- package/dist/{esm/array.js → array.js} +7 -3
- package/dist/array.js.map +1 -0
- package/dist/{types/caveats.d.ts → caveats.d.ts} +4 -0
- package/dist/caveats.js +35 -0
- package/dist/caveats.js.map +1 -0
- package/dist/checksum.js +42 -0
- package/dist/checksum.js.map +1 -0
- package/dist/cronjob.js +71 -0
- package/dist/cronjob.js.map +1 -0
- package/dist/deep-clone.js +9 -0
- package/dist/deep-clone.js.map +1 -0
- package/dist/{esm/default-endowments.js → default-endowments.js} +6 -3
- package/dist/default-endowments.js.map +1 -0
- package/dist/entropy.js +8 -0
- package/dist/entropy.js.map +1 -0
- package/dist/{cjs/eval-worker.js → eval-worker.js} +21 -22
- package/dist/eval-worker.js.map +1 -0
- package/dist/eval.js +27 -0
- package/dist/eval.js.map +1 -0
- package/dist/{esm/fs.js → fs.js} +56 -33
- package/dist/fs.js.map +1 -0
- package/dist/{types/handlers.d.ts → handlers.d.ts} +42 -5
- package/dist/handlers.js +3 -0
- package/dist/handlers.js.map +1 -0
- package/dist/{types/iframe.d.ts → iframe.d.ts} +2 -3
- package/dist/{esm/iframe.js → iframe.js} +18 -16
- package/dist/iframe.js.map +1 -0
- package/dist/iframe.test.browser.js +15 -0
- package/dist/iframe.test.browser.js.map +1 -0
- package/dist/{types/index.browser.d.ts → index.browser.d.ts} +1 -2
- package/dist/index.browser.js +37 -0
- package/dist/index.browser.js.map +1 -0
- package/dist/{types/index.d.ts → index.d.ts} +1 -2
- package/dist/index.executionenv.js +22 -0
- package/dist/index.executionenv.js.map +1 -0
- package/dist/index.js +42 -0
- package/dist/index.js.map +1 -0
- package/dist/json-rpc.js +46 -0
- package/dist/json-rpc.js.map +1 -0
- package/dist/json.d.ts +9 -0
- package/dist/json.js +18 -0
- package/dist/json.js.map +1 -0
- package/dist/{esm/logging.js → logging.js} +14 -6
- package/dist/logging.js.map +1 -0
- package/dist/manifest/index.browser.js +18 -0
- package/dist/manifest/index.browser.js.map +1 -0
- package/dist/manifest/index.js +19 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/{esm/manifest → manifest}/manifest.js +113 -98
- package/dist/manifest/manifest.js.map +1 -0
- package/dist/{types/manifest → manifest}/validation.d.ts +73 -31
- package/dist/manifest/validation.js +141 -0
- package/dist/manifest/validation.js.map +1 -0
- package/dist/{esm/mock.js → mock.js} +40 -42
- package/dist/mock.js.map +1 -0
- package/dist/namespace.d.ts +275 -0
- package/dist/namespace.js +225 -0
- package/dist/namespace.js.map +1 -0
- package/dist/notification.d.ts +66 -0
- package/dist/notification.js +58 -0
- package/dist/notification.js.map +1 -0
- package/dist/{types/npm.d.ts → npm.d.ts} +2 -0
- package/dist/npm.js +74 -0
- package/dist/npm.js.map +1 -0
- package/dist/path.js +21 -0
- package/dist/path.js.map +1 -0
- package/dist/{esm/post-process.js → post-process.js} +99 -110
- package/dist/post-process.js.map +1 -0
- package/dist/{types/snaps.d.ts → snaps.d.ts} +2 -9
- package/dist/snaps.js +202 -0
- package/dist/snaps.js.map +1 -0
- package/dist/{types/types.d.ts → types.d.ts} +5 -2
- package/dist/types.js +103 -0
- package/dist/types.js.map +1 -0
- package/dist/{esm/versions.js → versions.js} +18 -15
- package/dist/versions.js.map +1 -0
- package/dist/{esm/virtual-file → virtual-file}/VirtualFile.js +33 -47
- package/dist/virtual-file/VirtualFile.js.map +1 -0
- package/dist/virtual-file/index.browser.js +18 -0
- package/dist/virtual-file/index.browser.js.map +1 -0
- package/dist/virtual-file/index.js +19 -0
- package/dist/virtual-file/index.js.map +1 -0
- package/dist/virtual-file/toVirtualFile.js +30 -0
- package/dist/virtual-file/toVirtualFile.js.map +1 -0
- package/package.json +32 -61
- package/dist/cjs/array.js +0 -23
- package/dist/cjs/array.js.map +0 -1
- package/dist/cjs/caveats.js +0 -33
- package/dist/cjs/caveats.js.map +0 -1
- package/dist/cjs/checksum.js +0 -38
- package/dist/cjs/checksum.js.map +0 -1
- package/dist/cjs/cronjob.js +0 -84
- package/dist/cjs/cronjob.js.map +0 -1
- package/dist/cjs/deep-clone.js +0 -22
- package/dist/cjs/deep-clone.js.map +0 -1
- package/dist/cjs/default-endowments.js +0 -49
- package/dist/cjs/default-endowments.js.map +0 -1
- package/dist/cjs/entropy.js +0 -23
- package/dist/cjs/entropy.js.map +0 -1
- package/dist/cjs/enum.js +0 -16
- package/dist/cjs/enum.js.map +0 -1
- package/dist/cjs/eval-worker.js.map +0 -1
- package/dist/cjs/eval.js +0 -29
- package/dist/cjs/eval.js.map +0 -1
- package/dist/cjs/fs.js +0 -126
- package/dist/cjs/fs.js.map +0 -1
- package/dist/cjs/handlers.js +0 -6
- package/dist/cjs/handlers.js.map +0 -1
- package/dist/cjs/icon.js +0 -37
- package/dist/cjs/icon.js.map +0 -1
- package/dist/cjs/iframe.js +0 -59
- package/dist/cjs/iframe.js.map +0 -1
- package/dist/cjs/index.browser.js +0 -40
- package/dist/cjs/index.browser.js.map +0 -1
- package/dist/cjs/index.executionenv.js +0 -24
- package/dist/cjs/index.executionenv.js.map +0 -1
- package/dist/cjs/index.js +0 -45
- package/dist/cjs/index.js.map +0 -1
- package/dist/cjs/json-rpc.js +0 -46
- package/dist/cjs/json-rpc.js.map +0 -1
- package/dist/cjs/json.js +0 -16
- package/dist/cjs/json.js.map +0 -1
- package/dist/cjs/logging.js +0 -40
- package/dist/cjs/logging.js.map +0 -1
- package/dist/cjs/manifest/index.browser.js +0 -20
- package/dist/cjs/manifest/index.browser.js.map +0 -1
- package/dist/cjs/manifest/index.js +0 -21
- package/dist/cjs/manifest/index.js.map +0 -1
- package/dist/cjs/manifest/manifest.js +0 -239
- package/dist/cjs/manifest/manifest.js.map +0 -1
- package/dist/cjs/manifest/validation.js +0 -183
- package/dist/cjs/manifest/validation.js.map +0 -1
- package/dist/cjs/mock.js +0 -128
- package/dist/cjs/mock.js.map +0 -1
- package/dist/cjs/namespace.js +0 -124
- package/dist/cjs/namespace.js.map +0 -1
- package/dist/cjs/npm.js +0 -81
- package/dist/cjs/npm.js.map +0 -1
- package/dist/cjs/path.js +0 -21
- package/dist/cjs/path.js.map +0 -1
- package/dist/cjs/post-process.js +0 -328
- package/dist/cjs/post-process.js.map +0 -1
- package/dist/cjs/snaps.js +0 -230
- package/dist/cjs/snaps.js.map +0 -1
- package/dist/cjs/types.js +0 -117
- package/dist/cjs/types.js.map +0 -1
- package/dist/cjs/validation.js +0 -22
- package/dist/cjs/validation.js.map +0 -1
- package/dist/cjs/versions.js +0 -47
- package/dist/cjs/versions.js.map +0 -1
- package/dist/cjs/virtual-file/VirtualFile.js +0 -85
- package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
- package/dist/cjs/virtual-file/index.browser.js +0 -20
- package/dist/cjs/virtual-file/index.browser.js.map +0 -1
- package/dist/cjs/virtual-file/index.js +0 -21
- package/dist/cjs/virtual-file/index.js.map +0 -1
- package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
- package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
- package/dist/esm/array.js.map +0 -1
- package/dist/esm/caveats.js +0 -23
- package/dist/esm/caveats.js.map +0 -1
- package/dist/esm/checksum.js +0 -36
- package/dist/esm/checksum.js.map +0 -1
- package/dist/esm/cronjob.js +0 -66
- package/dist/esm/cronjob.js.map +0 -1
- package/dist/esm/deep-clone.js +0 -7
- package/dist/esm/deep-clone.js.map +0 -1
- package/dist/esm/default-endowments.js.map +0 -1
- package/dist/esm/entropy.js +0 -6
- package/dist/esm/entropy.js.map +0 -1
- package/dist/esm/enum.js +0 -12
- package/dist/esm/enum.js.map +0 -1
- package/dist/esm/eval-worker.js +0 -47
- package/dist/esm/eval-worker.js.map +0 -1
- package/dist/esm/eval.js +0 -25
- package/dist/esm/eval.js.map +0 -1
- package/dist/esm/fs.js.map +0 -1
- package/dist/esm/handlers.js +0 -3
- package/dist/esm/handlers.js.map +0 -1
- package/dist/esm/icon.js +0 -11
- package/dist/esm/icon.js.map +0 -1
- package/dist/esm/iframe.js.map +0 -1
- package/dist/esm/index.browser.js +0 -23
- package/dist/esm/index.browser.js.map +0 -1
- package/dist/esm/index.executionenv.js +0 -7
- package/dist/esm/index.executionenv.js.map +0 -1
- package/dist/esm/index.js +0 -28
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/json-rpc.js +0 -39
- package/dist/esm/json-rpc.js.map +0 -1
- package/dist/esm/json.js +0 -17
- package/dist/esm/json.js.map +0 -1
- package/dist/esm/logging.js.map +0 -1
- package/dist/esm/manifest/index.browser.js +0 -3
- package/dist/esm/manifest/index.browser.js.map +0 -1
- package/dist/esm/manifest/index.js +0 -4
- package/dist/esm/manifest/index.js.map +0 -1
- package/dist/esm/manifest/manifest.js.map +0 -1
- package/dist/esm/manifest/validation.js +0 -152
- package/dist/esm/manifest/validation.js.map +0 -1
- package/dist/esm/mock.js.map +0 -1
- package/dist/esm/namespace.js +0 -110
- package/dist/esm/namespace.js.map +0 -1
- package/dist/esm/npm.js +0 -70
- package/dist/esm/npm.js.map +0 -1
- package/dist/esm/path.js +0 -17
- package/dist/esm/path.js.map +0 -1
- package/dist/esm/post-process.js.map +0 -1
- package/dist/esm/snaps.js +0 -215
- package/dist/esm/snaps.js.map +0 -1
- package/dist/esm/types.js +0 -85
- package/dist/esm/types.js.map +0 -1
- package/dist/esm/validation.js +0 -17
- package/dist/esm/validation.js.map +0 -1
- package/dist/esm/versions.js.map +0 -1
- package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
- package/dist/esm/virtual-file/index.browser.js +0 -3
- package/dist/esm/virtual-file/index.browser.js.map +0 -1
- package/dist/esm/virtual-file/index.js +0 -4
- package/dist/esm/virtual-file/index.js.map +0 -1
- package/dist/esm/virtual-file/toVirtualFile.js +0 -26
- package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
- package/dist/types/enum.d.ts +0 -30
- package/dist/types/icon.d.ts +0 -4
- package/dist/types/json.d.ts +0 -13
- package/dist/types/namespace.d.ts +0 -124
- package/dist/types/validation.d.ts +0 -8
- /package/dist/{types/array.d.ts → array.d.ts} +0 -0
- /package/dist/{types/checksum.d.ts → checksum.d.ts} +0 -0
- /package/dist/{types/cronjob.d.ts → cronjob.d.ts} +0 -0
- /package/dist/{types/deep-clone.d.ts → deep-clone.d.ts} +0 -0
- /package/dist/{types/default-endowments.d.ts → default-endowments.d.ts} +0 -0
- /package/dist/{types/entropy.d.ts → entropy.d.ts} +0 -0
- /package/dist/{types/eval-worker.d.ts → eval-worker.d.ts} +0 -0
- /package/dist/{types/eval.d.ts → eval.d.ts} +0 -0
- /package/dist/{types/fs.d.ts → fs.d.ts} +0 -0
- /package/dist/{types/iframe.test.browser.d.ts → iframe.test.browser.d.ts} +0 -0
- /package/dist/{types/index.executionenv.d.ts → index.executionenv.d.ts} +0 -0
- /package/dist/{types/json-rpc.d.ts → json-rpc.d.ts} +0 -0
- /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
- /package/dist/{types/manifest → manifest}/index.browser.d.ts +0 -0
- /package/dist/{types/manifest → manifest}/index.d.ts +0 -0
- /package/dist/{types/manifest → manifest}/manifest.d.ts +0 -0
- /package/dist/{types/mock.d.ts → mock.d.ts} +0 -0
- /package/dist/{types/path.d.ts → path.d.ts} +0 -0
- /package/dist/{types/post-process.d.ts → post-process.d.ts} +0 -0
- /package/dist/{types/versions.d.ts → versions.d.ts} +0 -0
- /package/dist/{types/virtual-file → virtual-file}/VirtualFile.d.ts +0 -0
- /package/dist/{types/virtual-file → virtual-file}/index.browser.d.ts +0 -0
- /package/dist/{types/virtual-file → virtual-file}/index.d.ts +0 -0
- /package/dist/{types/virtual-file → virtual-file}/toVirtualFile.d.ts +0 -0
package/dist/npm.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateNpmSnap = exports.SnapFileNameFromKey = exports.EXPECTED_SNAP_FILES = exports.SVG_MAX_BYTE_SIZE_TEXT = exports.SVG_MAX_BYTE_SIZE = void 0;
|
|
4
|
+
const manifest_1 = require("./manifest/manifest");
|
|
5
|
+
const validation_1 = require("./manifest/validation");
|
|
6
|
+
const types_1 = require("./types");
|
|
7
|
+
exports.SVG_MAX_BYTE_SIZE = 100000;
|
|
8
|
+
exports.SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(exports.SVG_MAX_BYTE_SIZE / 1000)}kb`;
|
|
9
|
+
exports.EXPECTED_SNAP_FILES = [
|
|
10
|
+
'manifest',
|
|
11
|
+
'packageJson',
|
|
12
|
+
'sourceCode',
|
|
13
|
+
];
|
|
14
|
+
exports.SnapFileNameFromKey = {
|
|
15
|
+
manifest: types_1.NpmSnapFileNames.Manifest,
|
|
16
|
+
packageJson: types_1.NpmSnapFileNames.PackageJson,
|
|
17
|
+
sourceCode: 'source code bundle',
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Validates the files extracted from an npm Snap package tarball by ensuring
|
|
21
|
+
* that they're non-empty and that the Json files match their respective schemas
|
|
22
|
+
* and the Snaps publishing specification.
|
|
23
|
+
*
|
|
24
|
+
* @param snapFiles - The object containing the expected Snap file contents,
|
|
25
|
+
* if any.
|
|
26
|
+
* @param errorPrefix - The prefix of the error message.
|
|
27
|
+
* @returns A tuple of the Snap manifest object and the Snap source code.
|
|
28
|
+
*/
|
|
29
|
+
function validateNpmSnap(snapFiles, errorPrefix) {
|
|
30
|
+
exports.EXPECTED_SNAP_FILES.forEach((key) => {
|
|
31
|
+
if (!snapFiles[key]) {
|
|
32
|
+
throw new Error(`${errorPrefix ?? ''}Missing file "${exports.SnapFileNameFromKey[key]}".`);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
// Typecast: We are assured that the required files exist if we get here.
|
|
36
|
+
const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
|
|
37
|
+
try {
|
|
38
|
+
(0, validation_1.assertIsSnapManifest)(manifest.result);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
42
|
+
}
|
|
43
|
+
const validatedManifest = manifest;
|
|
44
|
+
const { iconPath } = validatedManifest.result.source.location.npm;
|
|
45
|
+
if (iconPath && !svgIcon) {
|
|
46
|
+
throw new Error(`Missing file "${iconPath}".`);
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
(0, types_1.assertIsNpmSnapPackageJson)(packageJson.result);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
throw new Error(`${errorPrefix ?? ''}${error.message}`);
|
|
53
|
+
}
|
|
54
|
+
const validatedPackageJson = packageJson;
|
|
55
|
+
(0, manifest_1.validateNpmSnapManifest)({
|
|
56
|
+
manifest: validatedManifest,
|
|
57
|
+
packageJson: validatedPackageJson,
|
|
58
|
+
sourceCode,
|
|
59
|
+
svgIcon,
|
|
60
|
+
});
|
|
61
|
+
if (svgIcon) {
|
|
62
|
+
if (Buffer.byteLength(svgIcon.value, 'utf8') > exports.SVG_MAX_BYTE_SIZE) {
|
|
63
|
+
throw new Error(`${errorPrefix ?? ''}The specified SVG icon exceeds the maximum size of ${exports.SVG_MAX_BYTE_SIZE_TEXT}.`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
manifest: validatedManifest,
|
|
68
|
+
packageJson: validatedPackageJson,
|
|
69
|
+
sourceCode,
|
|
70
|
+
svgIcon,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
exports.validateNpmSnap = validateNpmSnap;
|
|
74
|
+
//# sourceMappingURL=npm.js.map
|
package/dist/npm.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../src/npm.ts"],"names":[],"mappings":";;;AAAA,kDAA8D;AAC9D,sDAA6D;AAC7D,mCAKiB;AA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A,kCAA0B,EAAC,WAAW,CAAC,MAAM,CAAC,CAAC;KAChD;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,GAAG,WAAW,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACzD;IACD,MAAM,oBAAoB,GAAG,WAAW,CAAC;IAEzC,IAAA,kCAAuB,EAAC;QACtB,QAAQ,EAAE,iBAAiB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,UAAU;QACV,OAAO;KACR,CAAC,CAAC;IAEH,IAAI,OAAO,EAAE;QACX,IAAI,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,yBAAiB,EAAE;YAChE,MAAM,IAAI,KAAK,CACb,GACE,WAAW,IAAI,EACjB,sDAAsD,8BAAsB,GAAG,CAChF,CAAC;SACH;KACF;IAED,OAAO;QACL,QAAQ,EAAE,iBAAiB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC;AAxDD,0CAwDC","sourcesContent":["import { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport {\n assertIsNpmSnapPackageJson,\n NpmSnapFileNames,\n SnapFiles,\n UnvalidatedSnapFiles,\n} from './types';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon } = snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n });\n\n if (svgIcon) {\n if (Buffer.byteLength(svgIcon.value, 'utf8') > SVG_MAX_BYTE_SIZE) {\n throw new Error(\n `${\n errorPrefix ?? ''\n }The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"]}
|
package/dist/path.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normalizeRelative = void 0;
|
|
4
|
+
const utils_1 = require("@metamask/utils");
|
|
5
|
+
/**
|
|
6
|
+
* Normalizes relative paths by optionally removing `./` prefix.
|
|
7
|
+
*
|
|
8
|
+
* @param path - Path to make normalize.
|
|
9
|
+
* @returns The same path, with `./` prefix remove.
|
|
10
|
+
*/
|
|
11
|
+
// TODO(ritave): Include NodeJS path polyfill and use path.normalize as well
|
|
12
|
+
function normalizeRelative(path) {
|
|
13
|
+
(0, utils_1.assert)(!path.startsWith('/'));
|
|
14
|
+
(0, utils_1.assert)(path.search(/:|\/\//u) === -1, `Path "${path}" potentially an URI instead of local relative`);
|
|
15
|
+
if (path.startsWith('./')) {
|
|
16
|
+
return path.slice(2);
|
|
17
|
+
}
|
|
18
|
+
return path;
|
|
19
|
+
}
|
|
20
|
+
exports.normalizeRelative = normalizeRelative;
|
|
21
|
+
//# sourceMappingURL=path.js.map
|
package/dist/path.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"path.js","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":";;;AAAA,2CAAyC;AAEzC;;;;;GAKG;AACH,4EAA4E;AAC5E,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,IAAA,cAAM,EAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9B,IAAA,cAAM,EACJ,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAC7B,SAAS,IAAI,gDAAgD,CAC9D,CAAC;IAEF,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QACzB,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KACtB;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAXD,8CAWC","sourcesContent":["import { assert } from '@metamask/utils';\n\n/**\n * Normalizes relative paths by optionally removing `./` prefix.\n *\n * @param path - Path to make normalize.\n * @returns The same path, with `./` prefix remove.\n */\n// TODO(ritave): Include NodeJS path polyfill and use path.normalize as well\nexport function normalizeRelative(path: string): string {\n assert(!path.startsWith('/'));\n assert(\n path.search(/:|\\/\\//u) === -1,\n `Path \"${path}\" potentially an URI instead of local relative`,\n );\n\n if (path.startsWith('./')) {\n return path.slice(2);\n }\n return path;\n}\n"]}
|
|
@@ -1,27 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.postProcessBundle = exports.PostProcessWarning = void 0;
|
|
1
4
|
// eslint-disable-next-line @typescript-eslint/no-shadow
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
(function(PostProcessWarning) {
|
|
6
|
-
PostProcessWarning["UnsafeMathRandom"] =
|
|
7
|
-
})(PostProcessWarning || (PostProcessWarning = {}));
|
|
5
|
+
const core_1 = require("@babel/core");
|
|
6
|
+
const types_1 = require("@babel/types");
|
|
7
|
+
var PostProcessWarning;
|
|
8
|
+
(function (PostProcessWarning) {
|
|
9
|
+
PostProcessWarning["UnsafeMathRandom"] = "`Math.random` was detected in the bundle. This is not a secure source of randomness.";
|
|
10
|
+
})(PostProcessWarning = exports.PostProcessWarning || (exports.PostProcessWarning = {}));
|
|
8
11
|
// The RegEx below consists of multiple groups joined by a boolean OR.
|
|
9
12
|
// Each part consists of two groups which capture a part of each string
|
|
10
13
|
// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.
|
|
11
14
|
const TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\(.*?\))/gu;
|
|
12
15
|
// An empty template element, i.e., a part of a template literal without any
|
|
13
16
|
// value ("").
|
|
14
|
-
const EMPTY_TEMPLATE_ELEMENT = templateElement({
|
|
15
|
-
|
|
16
|
-
cooked: ''
|
|
17
|
-
});
|
|
18
|
-
const evalWrapper = template.statement(`
|
|
17
|
+
const EMPTY_TEMPLATE_ELEMENT = (0, types_1.templateElement)({ raw: '', cooked: '' });
|
|
18
|
+
const evalWrapper = core_1.template.statement(`
|
|
19
19
|
(1, REF)(ARGS)
|
|
20
20
|
`);
|
|
21
|
-
const objectEvalWrapper = template.statement(`
|
|
21
|
+
const objectEvalWrapper = core_1.template.statement(`
|
|
22
22
|
(1, OBJECT.REF)
|
|
23
23
|
`);
|
|
24
|
-
const regeneratorRuntimeWrapper = template.statement(`
|
|
24
|
+
const regeneratorRuntimeWrapper = core_1.template.statement(`
|
|
25
25
|
var regeneratorRuntime;
|
|
26
26
|
`);
|
|
27
27
|
/**
|
|
@@ -35,11 +35,13 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
35
35
|
* @returns The string split into an array, in a way that it can be joined
|
|
36
36
|
* together to form the same string, but with the tokens separated into single
|
|
37
37
|
* array elements.
|
|
38
|
-
*/
|
|
38
|
+
*/
|
|
39
|
+
function breakTokens(value) {
|
|
39
40
|
const tokens = value.split(TOKEN_REGEX);
|
|
40
|
-
return tokens
|
|
41
|
-
|
|
42
|
-
|
|
41
|
+
return (tokens
|
|
42
|
+
// TODO: The `split` above results in some values being `undefined`.
|
|
43
|
+
// There may be a better solution to avoid having to filter those out.
|
|
44
|
+
.filter((token) => token !== '' && token !== undefined));
|
|
43
45
|
}
|
|
44
46
|
/**
|
|
45
47
|
* Breaks up tokens that would otherwise result in SES errors. The tokens are
|
|
@@ -51,59 +53,47 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
51
53
|
* @param value - The string value to break up.
|
|
52
54
|
* @returns The string split into a tuple consisting of the new template
|
|
53
55
|
* elements and string literal expressions.
|
|
54
|
-
*/
|
|
56
|
+
*/
|
|
57
|
+
function breakTokensTemplateLiteral(value) {
|
|
55
58
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
56
59
|
// @ts-ignore `matchAll` is not available in ES2017, but this code
|
|
57
60
|
// should only be used in environments where the function is supported.
|
|
58
61
|
const matches = Array.from(value.matchAll(TOKEN_REGEX));
|
|
59
62
|
if (matches.length > 0) {
|
|
60
|
-
const output = matches.reduce(([elements, expressions], rawMatch, index, values)=>{
|
|
61
|
-
const [, first, last] = rawMatch.filter((raw)=>raw !== undefined);
|
|
63
|
+
const output = matches.reduce(([elements, expressions], rawMatch, index, values) => {
|
|
64
|
+
const [, first, last] = rawMatch.filter((raw) => raw !== undefined);
|
|
62
65
|
// Slice the text in front of the match, which does not need to be
|
|
63
66
|
// broken up.
|
|
64
|
-
const prefix = value.slice(index === 0
|
|
67
|
+
const prefix = value.slice(index === 0
|
|
68
|
+
? 0
|
|
69
|
+
: values[index - 1].index + values[index - 1][0].length, rawMatch.index);
|
|
65
70
|
return [
|
|
66
71
|
[
|
|
67
72
|
...elements,
|
|
68
|
-
templateElement({
|
|
73
|
+
(0, types_1.templateElement)({
|
|
69
74
|
raw: getRawTemplateValue(prefix),
|
|
70
|
-
cooked: prefix
|
|
75
|
+
cooked: prefix,
|
|
71
76
|
}),
|
|
72
|
-
EMPTY_TEMPLATE_ELEMENT
|
|
77
|
+
EMPTY_TEMPLATE_ELEMENT,
|
|
73
78
|
],
|
|
74
|
-
[
|
|
75
|
-
...expressions,
|
|
76
|
-
stringLiteral(first),
|
|
77
|
-
stringLiteral(last)
|
|
78
|
-
]
|
|
79
|
+
[...expressions, (0, types_1.stringLiteral)(first), (0, types_1.stringLiteral)(last)],
|
|
79
80
|
];
|
|
80
|
-
}, [
|
|
81
|
-
[],
|
|
82
|
-
[]
|
|
83
|
-
]);
|
|
81
|
+
}, [[], []]);
|
|
84
82
|
// Add the text after the last match to the output.
|
|
85
83
|
const lastMatch = matches[matches.length - 1];
|
|
86
84
|
const suffix = value.slice(lastMatch.index + lastMatch[0].length);
|
|
87
85
|
return [
|
|
88
86
|
[
|
|
89
87
|
...output[0],
|
|
90
|
-
templateElement({
|
|
91
|
-
raw: getRawTemplateValue(suffix),
|
|
92
|
-
cooked: suffix
|
|
93
|
-
})
|
|
88
|
+
(0, types_1.templateElement)({ raw: getRawTemplateValue(suffix), cooked: suffix }),
|
|
94
89
|
],
|
|
95
|
-
output[1]
|
|
90
|
+
output[1],
|
|
96
91
|
];
|
|
97
92
|
}
|
|
98
93
|
// If there are no matches, simply return the original value.
|
|
99
94
|
return [
|
|
100
|
-
[
|
|
101
|
-
|
|
102
|
-
raw: getRawTemplateValue(value),
|
|
103
|
-
cooked: value
|
|
104
|
-
})
|
|
105
|
-
],
|
|
106
|
-
[]
|
|
95
|
+
[(0, types_1.templateElement)({ raw: getRawTemplateValue(value), cooked: value })],
|
|
96
|
+
[],
|
|
107
97
|
];
|
|
108
98
|
}
|
|
109
99
|
/**
|
|
@@ -113,7 +103,8 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
113
103
|
* @see https://github.com/babel/babel/issues/9242#issuecomment-532529613
|
|
114
104
|
* @param value - The cooked string to get the raw string for.
|
|
115
105
|
* @returns The value as raw value.
|
|
116
|
-
*/
|
|
106
|
+
*/
|
|
107
|
+
function getRawTemplateValue(value) {
|
|
117
108
|
return value.replace(/\\|`|\$\{/gu, '\\$&');
|
|
118
109
|
}
|
|
119
110
|
/**
|
|
@@ -139,19 +130,23 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
139
130
|
* map will be generated instead.
|
|
140
131
|
* @returns An object containing the modified code, and source map, or null if
|
|
141
132
|
* the provided code is null.
|
|
142
|
-
*/
|
|
133
|
+
*/
|
|
134
|
+
function postProcessBundle(code, { stripComments = true, sourceMap: sourceMaps, inputSourceMap, } = {}) {
|
|
143
135
|
const warnings = new Set();
|
|
144
|
-
const pre = ({ ast })=>{
|
|
145
|
-
ast.comments?.forEach((comment)=>{
|
|
136
|
+
const pre = ({ ast }) => {
|
|
137
|
+
ast.comments?.forEach((comment) => {
|
|
146
138
|
// Break up tokens that could be parsed as HTML comment terminators. The
|
|
147
139
|
// regular expressions below are written strangely so as to avoid the
|
|
148
140
|
// appearance of such tokens in our source code. For reference:
|
|
149
141
|
// https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
|
|
150
|
-
comment.value = comment.value
|
|
142
|
+
comment.value = comment.value
|
|
143
|
+
.replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')
|
|
144
|
+
.replace(new RegExp(`${'--'}>`, 'gu'), '-- >')
|
|
145
|
+
.replace(/import(\(.*\))/gu, 'import\\$1');
|
|
151
146
|
});
|
|
152
147
|
};
|
|
153
148
|
const visitor = {
|
|
154
|
-
FunctionExpression
|
|
149
|
+
FunctionExpression(path) {
|
|
155
150
|
const { node } = path;
|
|
156
151
|
// Browserify provides the `Buffer` global as an argument to modules that
|
|
157
152
|
// use it, but this does not work in SES. Since we pass in `Buffer` as an
|
|
@@ -164,52 +159,61 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
164
159
|
// TODO: Since we're working on the AST level, we could check the scope
|
|
165
160
|
// of the function expression, and possibly prevent false positives?
|
|
166
161
|
if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {
|
|
167
|
-
node.params = node.params.filter((param)
|
|
162
|
+
node.params = node.params.filter((param) => !(param.type === 'Identifier' && param.name === 'Buffer'));
|
|
168
163
|
}
|
|
169
164
|
},
|
|
170
|
-
CallExpression
|
|
165
|
+
CallExpression(path) {
|
|
171
166
|
const { node } = path;
|
|
172
167
|
// Replace `eval(foo)` with `(1, eval)(foo)`.
|
|
173
168
|
if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {
|
|
174
169
|
path.replaceWith(evalWrapper({
|
|
175
170
|
REF: node.callee,
|
|
176
|
-
ARGS: node.arguments
|
|
171
|
+
ARGS: node.arguments,
|
|
177
172
|
}));
|
|
178
173
|
}
|
|
179
174
|
// Detect the use of `Math.random()` and add a warning.
|
|
180
|
-
if (node.callee.type === 'MemberExpression' &&
|
|
175
|
+
if (node.callee.type === 'MemberExpression' &&
|
|
176
|
+
node.callee.object.type === 'Identifier' &&
|
|
177
|
+
node.callee.object.name === 'Math' &&
|
|
178
|
+
node.callee.property.type === 'Identifier' &&
|
|
179
|
+
node.callee.property.name === 'random') {
|
|
181
180
|
warnings.add(PostProcessWarning.UnsafeMathRandom);
|
|
182
181
|
}
|
|
183
182
|
},
|
|
184
|
-
MemberExpression
|
|
183
|
+
MemberExpression(path) {
|
|
185
184
|
const { node } = path;
|
|
186
185
|
// Replace `object.eval(foo)` with `(1, object.eval)(foo)`.
|
|
187
|
-
if (node.property.type === 'Identifier' &&
|
|
188
|
-
|
|
186
|
+
if (node.property.type === 'Identifier' &&
|
|
187
|
+
node.property.name === 'eval' &&
|
|
188
|
+
// We only apply this to MemberExpressions that are the callee of CallExpression
|
|
189
|
+
path.parent.type === 'CallExpression' &&
|
|
190
|
+
path.parent.callee === node) {
|
|
189
191
|
path.replaceWith(objectEvalWrapper({
|
|
190
192
|
OBJECT: node.object,
|
|
191
|
-
REF: node.property
|
|
193
|
+
REF: node.property,
|
|
192
194
|
}));
|
|
193
195
|
}
|
|
194
196
|
},
|
|
195
|
-
Identifier
|
|
197
|
+
Identifier(path) {
|
|
196
198
|
const { node } = path;
|
|
197
199
|
// Insert `regeneratorRuntime` global if it's used in the code.
|
|
198
200
|
if (node.name === 'regeneratorRuntime') {
|
|
199
|
-
const program = path.findParent((parent)=>parent.node.type === 'Program');
|
|
201
|
+
const program = path.findParent((parent) => parent.node.type === 'Program');
|
|
200
202
|
// We know that `program` is a Program node here, but this keeps
|
|
201
203
|
// TypeScript happy.
|
|
202
204
|
if (program?.node.type === 'Program') {
|
|
203
205
|
const body = program.node.body[0];
|
|
204
206
|
// This stops it from inserting `regeneratorRuntime` multiple times.
|
|
205
|
-
if (body.type === 'VariableDeclaration' &&
|
|
207
|
+
if (body.type === 'VariableDeclaration' &&
|
|
208
|
+
body.declarations[0].id.name ===
|
|
209
|
+
'regeneratorRuntime') {
|
|
206
210
|
return;
|
|
207
211
|
}
|
|
208
212
|
program?.node.body.unshift(regeneratorRuntimeWrapper());
|
|
209
213
|
}
|
|
210
214
|
}
|
|
211
215
|
},
|
|
212
|
-
TemplateLiteral
|
|
216
|
+
TemplateLiteral(path) {
|
|
213
217
|
const { node } = path;
|
|
214
218
|
// This checks if the template literal was visited before. Without this,
|
|
215
219
|
// it would cause an infinite loop resulting in a stack overflow. We can't
|
|
@@ -222,7 +226,7 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
222
226
|
// For reference:
|
|
223
227
|
// - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
|
|
224
228
|
// - https://github.com/MetaMask/snaps-monorepo/issues/505
|
|
225
|
-
const [replacementQuasis, replacementExpressions] = node.quasis.reduce(([elements, expressions], quasi, index)=>{
|
|
229
|
+
const [replacementQuasis, replacementExpressions] = node.quasis.reduce(([elements, expressions], quasi, index) => {
|
|
226
230
|
// Note: Template literals have two variants, "cooked" and "raw". Here
|
|
227
231
|
// we use the cooked version.
|
|
228
232
|
// https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
|
|
@@ -230,35 +234,23 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
230
234
|
// Only update the node if something changed.
|
|
231
235
|
if (tokens[0].length <= 1) {
|
|
232
236
|
return [
|
|
233
|
-
[
|
|
234
|
-
|
|
235
|
-
quasi
|
|
236
|
-
],
|
|
237
|
-
[
|
|
238
|
-
...expressions,
|
|
239
|
-
node.expressions[index]
|
|
240
|
-
]
|
|
237
|
+
[...elements, quasi],
|
|
238
|
+
[...expressions, node.expressions[index]],
|
|
241
239
|
];
|
|
242
240
|
}
|
|
243
241
|
return [
|
|
244
|
-
[
|
|
245
|
-
...elements,
|
|
246
|
-
...tokens[0]
|
|
247
|
-
],
|
|
242
|
+
[...elements, ...tokens[0]],
|
|
248
243
|
[
|
|
249
244
|
...expressions,
|
|
250
245
|
...tokens[1],
|
|
251
|
-
node.expressions[index]
|
|
252
|
-
]
|
|
246
|
+
node.expressions[index],
|
|
247
|
+
],
|
|
253
248
|
];
|
|
254
|
-
}, [
|
|
255
|
-
|
|
256
|
-
[]
|
|
257
|
-
]);
|
|
258
|
-
path.replaceWith(templateLiteral(replacementQuasis, replacementExpressions.filter((expression)=>expression !== undefined)));
|
|
249
|
+
}, [[], []]);
|
|
250
|
+
path.replaceWith((0, types_1.templateLiteral)(replacementQuasis, replacementExpressions.filter((expression) => expression !== undefined)));
|
|
259
251
|
path.setData('visited', true);
|
|
260
252
|
},
|
|
261
|
-
StringLiteral
|
|
253
|
+
StringLiteral(path) {
|
|
262
254
|
const { node } = path;
|
|
263
255
|
// Break up tokens that could be parsed as HTML comment terminators, or
|
|
264
256
|
// `import()` statements.
|
|
@@ -270,29 +262,25 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
270
262
|
if (tokens.length <= 1) {
|
|
271
263
|
return;
|
|
272
264
|
}
|
|
273
|
-
const replacement = tokens
|
|
265
|
+
const replacement = tokens
|
|
266
|
+
.slice(1)
|
|
267
|
+
.reduce((acc, value) => (0, types_1.binaryExpression)('+', acc, (0, types_1.stringLiteral)(value)), (0, types_1.stringLiteral)(tokens[0]));
|
|
274
268
|
path.replaceWith(replacement);
|
|
275
269
|
path.skip();
|
|
276
270
|
},
|
|
277
|
-
BinaryExpression
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
if (
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
271
|
+
BinaryExpression(path) {
|
|
272
|
+
const source = path.getSource();
|
|
273
|
+
// Throw an error if HTML comments are used as a binary expression.
|
|
274
|
+
if (source.includes('<!--') || source.includes('-->')) {
|
|
275
|
+
throw new Error('Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +
|
|
276
|
+
'these comments is ambiguous, and differs per browser and environment. If you want ' +
|
|
277
|
+
'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +
|
|
278
|
+
'and `a < ! --b`.');
|
|
285
279
|
}
|
|
286
|
-
|
|
287
|
-
const expression = code.slice(node.left.argument.end, node.right.start);
|
|
288
|
-
if (expression.includes('-->')) {
|
|
289
|
-
throw new Error(errorMessage);
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
}
|
|
280
|
+
},
|
|
293
281
|
};
|
|
294
282
|
try {
|
|
295
|
-
const file = transformSync(code, {
|
|
283
|
+
const file = (0, core_1.transformSync)(code, {
|
|
296
284
|
// Prevent Babel from searching for a config file.
|
|
297
285
|
configFile: false,
|
|
298
286
|
parserOpts: {
|
|
@@ -300,7 +288,7 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
300
288
|
strictMode: true,
|
|
301
289
|
// If this is disabled, the AST does not include any comments. This is
|
|
302
290
|
// useful for performance reasons, and we use it for stripping comments.
|
|
303
|
-
attachComment: !stripComments
|
|
291
|
+
attachComment: !stripComments,
|
|
304
292
|
},
|
|
305
293
|
// By default, Babel optimises bundles that exceed 500 KB, but that
|
|
306
294
|
// results in characters which look like HTML comments, which breaks SES.
|
|
@@ -311,11 +299,11 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
311
299
|
inputSourceMap,
|
|
312
300
|
sourceMaps,
|
|
313
301
|
plugins: [
|
|
314
|
-
()=>({
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
]
|
|
302
|
+
() => ({
|
|
303
|
+
pre,
|
|
304
|
+
visitor,
|
|
305
|
+
}),
|
|
306
|
+
],
|
|
319
307
|
});
|
|
320
308
|
if (!file?.code) {
|
|
321
309
|
throw new Error('Bundled code is empty.');
|
|
@@ -323,11 +311,12 @@ const regeneratorRuntimeWrapper = template.statement(`
|
|
|
323
311
|
return {
|
|
324
312
|
code: file.code,
|
|
325
313
|
sourceMap: file.map,
|
|
326
|
-
warnings: Array.from(warnings)
|
|
314
|
+
warnings: Array.from(warnings),
|
|
327
315
|
};
|
|
328
|
-
}
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
329
318
|
throw new Error(`Failed to post process code:\n${error.message}`);
|
|
330
319
|
}
|
|
331
320
|
}
|
|
332
|
-
|
|
321
|
+
exports.postProcessBundle = postProcessBundle;
|
|
333
322
|
//# sourceMappingURL=post-process.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"post-process.js","sourceRoot":"","sources":["../src/post-process.ts"],"names":[],"mappings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EAAE;gBACP,GAAG,EAAE,CAAC,CAAC;oBACL,GAAG;oBACH,OAAO;iBACR,CAAC;aACH;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;SAC3C;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;KACH;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KACnE;AACH,CAAC;AApQD,8CAoQC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { transformSync, Node, Visitor, template, PluginObj } from '@babel/core';\nimport {\n binaryExpression,\n Expression,\n Identifier,\n stringLiteral,\n TemplateElement,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const source = path.getSource();\n\n // Throw an error if HTML comments are used as a binary expression.\n if (source.includes('<!--') || source.includes('-->')) {\n throw new Error(\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 }\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"]}
|
|
@@ -28,7 +28,7 @@ export declare enum SnapStatusEvents {
|
|
|
28
28
|
Update = "UPDATE"
|
|
29
29
|
}
|
|
30
30
|
export declare type StatusContext = {
|
|
31
|
-
snapId:
|
|
31
|
+
snapId: string;
|
|
32
32
|
};
|
|
33
33
|
export declare type StatusEvents = {
|
|
34
34
|
type: SnapStatusEvents;
|
|
@@ -60,7 +60,7 @@ export declare type Snap = {
|
|
|
60
60
|
/**
|
|
61
61
|
* The ID of the Snap.
|
|
62
62
|
*/
|
|
63
|
-
id:
|
|
63
|
+
id: SnapId;
|
|
64
64
|
/**
|
|
65
65
|
* The initial permissions of the Snap, which will be requested when it is
|
|
66
66
|
* installed.
|
|
@@ -140,13 +140,6 @@ declare const snapIdSymbol: unique symbol;
|
|
|
140
140
|
* @returns The snap prefix from a snap id, e.g. `npm:`.
|
|
141
141
|
*/
|
|
142
142
|
export declare function getSnapPrefix(snapId: string): SnapIdPrefixes;
|
|
143
|
-
/**
|
|
144
|
-
* Strips snap prefix from a full snap ID.
|
|
145
|
-
*
|
|
146
|
-
* @param snapId - The snap ID to strip.
|
|
147
|
-
* @returns The stripped snap ID.
|
|
148
|
-
*/
|
|
149
|
-
export declare function stripSnapPrefix(snapId: string): string;
|
|
150
143
|
/**
|
|
151
144
|
* Assert that the given value is a valid snap ID.
|
|
152
145
|
*
|