@metamask/snaps-cli 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cmds/build/buildHandler.js +1 -1
- package/dist/cmds/build/buildHandler.js.map +1 -1
- package/dist/cmds/build/bundle.js +4 -10
- package/dist/cmds/build/bundle.js.map +1 -1
- package/dist/cmds/build/utils.js +1 -1
- package/dist/cmds/build/utils.js.map +1 -1
- package/dist/cmds/eval/eval-worker.js +4 -11
- package/dist/cmds/eval/eval-worker.js.map +1 -1
- package/dist/cmds/eval/mock.js +3 -3
- package/dist/cmds/eval/mock.js.map +1 -1
- package/dist/cmds/init/index.js +1 -5
- package/dist/cmds/init/index.js.map +1 -1
- package/dist/cmds/init/init-template.json +1 -1
- package/dist/cmds/init/initHandler.js +1 -1
- package/dist/cmds/init/initHandler.js.map +1 -1
- package/dist/cmds/manifest/index.js +1 -1
- package/dist/cmds/manifest/index.js.map +1 -1
- package/dist/cmds/manifest/manifestHandler.js +18 -7
- package/dist/cmds/manifest/manifestHandler.js.map +1 -1
- package/dist/cmds/watch/watchHandler.js +1 -1
- package/dist/cmds/watch/watchHandler.js.map +1 -1
- package/package.json +3 -3
|
@@ -26,7 +26,7 @@ async function build(argv) {
|
|
|
26
26
|
const outfilePath = (0, utils_1.getOutfilePath)(dist, outfileName);
|
|
27
27
|
const result = await (0, bundle_1.bundle)(src, outfilePath, argv, (0, utils_1.loadConfig)().bundlerCustomizer);
|
|
28
28
|
if (result && argv.eval) {
|
|
29
|
-
await (0, evalHandler_1.snapEval)({
|
|
29
|
+
await (0, evalHandler_1.snapEval)(Object.assign(Object.assign({}, argv), { bundle: outfilePath }));
|
|
30
30
|
}
|
|
31
31
|
if (argv.manifest) {
|
|
32
32
|
await (0, manifestHandler_1.manifestHandler)(argv);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildHandler.js","sourceRoot":"","sources":["../../../src/cmds/build/buildHandler.ts"],"names":[],"mappings":";;;AACA,uCAMqB;AACrB,qDAA+C;AAC/C,iEAA8D;AAC9D,qCAAkC;AAElC;;;;;;;;;;GAUG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACxC,IAAI,WAAW,EAAE;QACf,IAAA,2BAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,wBAAgB,EAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAA,uBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAElC,MAAM,WAAW,GAAG,IAAA,sBAAc,EAAC,IAAI,EAAE,WAAqB,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,IAAA,eAAM,EACzB,GAAG,EACH,WAAW,EACX,IAAI,EACJ,IAAA,kBAAU,GAAE,CAAC,iBAAiB,CAC/B,CAAC;IACF,IAAI,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE;QACvB,MAAM,IAAA,sBAAQ,
|
|
1
|
+
{"version":3,"file":"buildHandler.js","sourceRoot":"","sources":["../../../src/cmds/build/buildHandler.ts"],"names":[],"mappings":";;;AACA,uCAMqB;AACrB,qDAA+C;AAC/C,iEAA8D;AAC9D,qCAAkC;AAElC;;;;;;;;;;GAUG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACxC,IAAI,WAAW,EAAE;QACf,IAAA,2BAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,wBAAgB,EAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAA,uBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAElC,MAAM,WAAW,GAAG,IAAA,sBAAc,EAAC,IAAI,EAAE,WAAqB,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,IAAA,eAAM,EACzB,GAAG,EACH,WAAW,EACX,IAAI,EACJ,IAAA,kBAAU,GAAE,CAAC,iBAAiB,CAC/B,CAAC;IACF,IAAI,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE;QACvB,MAAM,IAAA,sBAAQ,kCAAM,IAAI,KAAE,MAAM,EAAE,WAAW,IAAG,CAAC;KAClD;IAED,IAAI,IAAI,CAAC,QAAQ,EAAE;QACjB,MAAM,IAAA,iCAAe,EAAC,IAAI,CAAC,CAAC;KAC7B;AACH,CAAC;AAtBD,sBAsBC","sourcesContent":["import { YargsArgs } from '../../types/yargs';\nimport {\n getOutfilePath,\n loadConfig,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '../../utils';\nimport { snapEval } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\nimport { bundle } from './bundle';\n\n/**\n * Builds all files in the given source directory to the given destination\n * directory.\n *\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - Argv from Yargs.\n * @param argv.src - The source file path.\n * @param argv.dist - The output directory path.\n * @param argv.outfileName - The output file name.\n */\nexport async function build(argv: YargsArgs): Promise<void> {\n const { src, dist, outfileName } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n\n const outfilePath = getOutfilePath(dist, outfileName as string);\n const result = await bundle(\n src,\n outfilePath,\n argv,\n loadConfig().bundlerCustomizer,\n );\n if (result && argv.eval) {\n await snapEval({ ...argv, bundle: outfilePath });\n }\n\n if (argv.manifest) {\n await manifestHandler(argv);\n }\n}\n"]}
|
|
@@ -34,10 +34,7 @@ function bundle(src, dest, argv, bundlerTransform) {
|
|
|
34
34
|
standalone: '<snap>',
|
|
35
35
|
});
|
|
36
36
|
if (transpilationMode !== builders_1.TranspilationModes.none) {
|
|
37
|
-
bundler.transform(require('babelify'), {
|
|
38
|
-
global: transpilationMode === builders_1.TranspilationModes.localAndDeps,
|
|
39
|
-
extensions: ['.js', '.ts'],
|
|
40
|
-
presets: [
|
|
37
|
+
bundler.transform(require('babelify'), Object.assign({ global: transpilationMode === builders_1.TranspilationModes.localAndDeps, extensions: ['.js', '.ts'], presets: [
|
|
41
38
|
require('@babel/preset-typescript'),
|
|
42
39
|
[
|
|
43
40
|
require('@babel/preset-env'),
|
|
@@ -47,18 +44,15 @@ function bundle(src, dest, argv, bundlerTransform) {
|
|
|
47
44
|
},
|
|
48
45
|
},
|
|
49
46
|
],
|
|
50
|
-
],
|
|
51
|
-
plugins: [
|
|
47
|
+
], plugins: [
|
|
52
48
|
require('@babel/plugin-transform-runtime'),
|
|
53
49
|
require('@babel/plugin-proposal-class-properties'),
|
|
54
50
|
require('@babel/plugin-proposal-object-rest-spread'),
|
|
55
51
|
require('@babel/plugin-proposal-optional-chaining'),
|
|
56
52
|
require('@babel/plugin-proposal-nullish-coalescing-operator'),
|
|
57
|
-
],
|
|
58
|
-
...babelifyOptions,
|
|
59
|
-
});
|
|
53
|
+
] }, babelifyOptions));
|
|
60
54
|
}
|
|
61
|
-
bundlerTransform
|
|
55
|
+
bundlerTransform === null || bundlerTransform === void 0 ? void 0 : bundlerTransform(bundler);
|
|
62
56
|
bundler.plugin(snaps_browserify_plugin_1.default, {
|
|
63
57
|
stripComments: argv.stripComments,
|
|
64
58
|
transformHtmlComments: argv.transformHtmlComments,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../../src/cmds/build/bundle.ts"],"names":[],"mappings":";;;;;;AAAA,4DAA0D;AAC1D,gGAAuD;AACvD,6CAAoD;AAEpD,mCAA+D;AAE/D,+EAA+E;AAC/E,mEAAmE;AACnE,mHAAmH;AAEnH;;;;;;;;;;;GAWG;AACH,SAAgB,MAAM,CACpB,GAAW,EACX,IAAY,EACZ,IAAe,EACf,gBAAsD;IAEtD,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IACtD,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EAC7D,UAAU,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,EAC1B,OAAO,EAAE;oBACP,OAAO,CAAC,0BAA0B,CAAC;oBACnC;wBACE,OAAO,CAAC,mBAAmB,CAAC;wBAC5B;4BACE,OAAO,EAAE;gCACP,QAAQ,EAAE,CAAC,cAAc,EAAE,eAAe,CAAC;6BAC5C;yBACF;qBACF;iBACF,EACD,OAAO,EAAE;oBACP,OAAO,CAAC,iCAAiC,CAAC;oBAC1C,OAAO,CAAC,yCAAyC,CAAC;oBAClD,OAAO,CAAC,2CAA2C,CAAC;oBACpD,OAAO,CAAC,0CAA0C,CAAC;oBACnD,OAAO,CAAC,oDAAoD,CAAC;iBAC9D,IACG,eAAuB,EAC3B,CAAC;SACJ;QAED,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAG,OAAO,CAAC,CAAC;QAE5B,OAAO,CAAC,MAAM,CAAC,iCAAM,EAAE;YACrB,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;SAClD,CAAC,CAAC;QAEH,OAAO,CAAC,MAAM,CACZ,KAAK,EAAE,WAAW,EAAE,YAAoB,EAAE,EAAE,CAC1C,MAAM,IAAA,uBAAe,EAAC;YACpB,WAAW;YACX,YAAY;YACZ,GAAG;YACH,IAAI;YACJ,OAAO;SACR,CAAC,CACL,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AA5DD,wBA4DC","sourcesContent":["import browserify, { BrowserifyObject } from 'browserify';\nimport plugin from '@metamask/snaps-browserify-plugin';\nimport { TranspilationModes } from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { processDependencies, writeBundleFile } from './utils';\n\n// We need to statically import all Browserify transforms and all Babel presets\n// and plugins, and calling `require` is the sanest way to do that.\n/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n\n/**\n * Builds a Snap bundle JS file from its JavaScript source.\n *\n * @param src - The source file path.\n * @param dest - The destination file path.\n * @param argv - Arguments as an object generated by `yargs`.\n * @param argv.sourceMaps - Whether to output sourcemaps.\n * @param argv.stripComments - Whether to remove comments from code.\n * @param argv.transpilationMode - The Babel transpilation mode.\n * @param bundlerTransform - An optional function which can be used to transform\n * the Browserify instance, e.g., adding a custom transform or plugin.\n */\nexport function bundle(\n src: string,\n dest: string,\n argv: YargsArgs,\n bundlerTransform?: (bundler: BrowserifyObject) => void,\n): Promise<boolean> {\n const { sourceMaps: debug, transpilationMode } = argv;\n const babelifyOptions = processDependencies(argv as any);\n return new Promise((resolve, _reject) => {\n const bundler = browserify(src, {\n debug,\n extensions: ['.js', '.ts'],\n // Standalone is required to properly support Snaps using module.exports\n standalone: '<snap>',\n });\n\n if (transpilationMode !== TranspilationModes.none) {\n bundler.transform(require('babelify'), {\n global: transpilationMode === TranspilationModes.localAndDeps,\n extensions: ['.js', '.ts'],\n presets: [\n require('@babel/preset-typescript'),\n [\n require('@babel/preset-env'),\n {\n targets: {\n browsers: ['chrome >= 66', 'firefox >= 68'],\n },\n },\n ],\n ],\n plugins: [\n require('@babel/plugin-transform-runtime'),\n require('@babel/plugin-proposal-class-properties'),\n require('@babel/plugin-proposal-object-rest-spread'),\n require('@babel/plugin-proposal-optional-chaining'),\n require('@babel/plugin-proposal-nullish-coalescing-operator'),\n ],\n ...(babelifyOptions as any),\n });\n }\n\n bundlerTransform?.(bundler);\n\n bundler.plugin(plugin, {\n stripComments: argv.stripComments,\n transformHtmlComments: argv.transformHtmlComments,\n });\n\n bundler.bundle(\n async (bundleError, bundleBuffer: Buffer) =>\n await writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n }),\n );\n });\n}\n"]}
|
package/dist/cmds/build/utils.js
CHANGED
|
@@ -23,7 +23,7 @@ async function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve,
|
|
|
23
23
|
await (0, misc_1.writeError)('Build error:', bundleError.message, bundleError);
|
|
24
24
|
}
|
|
25
25
|
try {
|
|
26
|
-
await fs_1.promises.writeFile(dest, bundleBuffer
|
|
26
|
+
await fs_1.promises.writeFile(dest, bundleBuffer === null || bundleBuffer === void 0 ? void 0 : bundleBuffer.toString());
|
|
27
27
|
console.log(`Build success: '${src}' bundled as '${dest}'!`);
|
|
28
28
|
resolve(true);
|
|
29
29
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/cmds/build/utils.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AACpC,2CAA8C;AAE9C,6CAAoD;AAUpD;;;;;;;;;;;;;GAaG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,WAAW,EACX,YAAY,EACZ,GAAG,EACH,IAAI,EACJ,OAAO,GACa;IACpB,IAAI,WAAW,EAAE;QACf,MAAM,IAAA,iBAAU,EAAC,cAAc,EAAE,WAAW,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;KACpE;IAED,IAAI;QACF,MAAM,aAAE,CAAC,SAAS,CAAC,IAAI,EAAE,YAAY,
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/cmds/build/utils.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AACpC,2CAA8C;AAE9C,6CAAoD;AAUpD;;;;;;;;;;;;;GAaG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,WAAW,EACX,YAAY,EACZ,GAAG,EACH,IAAI,EACJ,OAAO,GACa;IACpB,IAAI,WAAW,EAAE;QACf,MAAM,IAAA,iBAAU,EAAC,cAAc,EAAE,WAAW,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;KACpE;IAED,IAAI;QACF,MAAM,aAAE,CAAC,SAAS,CAAC,IAAI,EAAE,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,EAAE,CAAC,CAAC;QACnD,OAAO,CAAC,GAAG,CAAC,mBAAmB,GAAG,iBAAiB,IAAI,IAAI,CAAC,CAAC;QAC7D,OAAO,CA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CAAC,CAAC,UAAU,EAAE,EAAE;QACrC,OAAO,UAAU,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;AAJD,0DAIC;AAED;;;;;;;;GAQG;AACH,SAAgB,2BAA2B,CAAC,IAAe;IACzD,IACE,IAAI,CAAC,eAAe;QACpB,IAAI,CAAC,iBAAiB,KAAK,6BAAkB,CAAC,YAAY,EAC1D;QACA,MAAM,IAAI,KAAK,CACb,2FAA2F,CAC5F,CAAC;KACH;AACH,CAAC;AATD,kEASC","sourcesContent":["import { promises as fs } from 'fs';\nimport { writeError } from '../../utils/misc';\nimport { YargsArgs } from '../../types/yargs';\nimport { TranspilationModes } from '../../builders';\n\ntype WriteBundleFileArgs = {\n bundleError: Error;\n bundleBuffer: Buffer;\n src: string;\n dest: string;\n resolve: (value: boolean) => void;\n};\n\n/**\n * Performs postprocessing on the bundle contents and writes them to disk.\n * Intended to be used in the callback passed to the Browserify `.bundle()`\n * call.\n *\n * @param options - Options bag.\n * @param options.bundleError - Any error received from Browserify.\n * @param options.bundleBuffer - The {@link Buffer} with the bundle contents\n * from Browserify.\n * @param options.src - The source file path.\n * @param options.dest - The destination file path.\n * @param options.resolve - A {@link Promise} resolution function, so that we\n * can use promises and `async`/`await` even though Browserify uses callbacks.\n */\nexport async function writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n}: WriteBundleFileArgs) {\n if (bundleError) {\n await writeError('Build error:', bundleError.message, bundleError);\n }\n\n try {\n await fs.writeFile(dest, bundleBuffer?.toString());\n console.log(`Build success: '${src}' bundled as '${dest}'!`);\n resolve(true);\n } catch (error) {\n await writeError('Write error:', error.message, error, dest);\n }\n}\n\n/**\n * Processes dependencies and updates `argv` with an options object.\n *\n * @param argv - The Yargs arguments object.\n * @returns An object with options that can be passed to Babelify.\n */\nexport function processDependencies(argv: YargsArgs) {\n const { depsToTranspile, transpilationMode } = argv;\n const babelifyOptions: Record<string, any> = {};\n if (transpilationMode === TranspilationModes.localAndDeps) {\n const regexpStr = getDependencyRegExp(depsToTranspile as string[]);\n if (regexpStr !== null) {\n babelifyOptions.ignore = [regexpStr];\n }\n }\n return babelifyOptions;\n}\n\n/**\n * Processes a string of space delimited dependencies into one RegExp string.\n *\n * @param dependencies - An array of dependencies to add to the RegExp.\n * @returns A RegExp object.\n */\nexport function getDependencyRegExp(dependencies: string[]): RegExp | null {\n let regexp: string | null = null;\n if (!dependencies || dependencies.includes('.') || !dependencies.length) {\n return regexp;\n }\n const paths: string[] = sanitizeDependencyPaths(dependencies);\n regexp = `/node_modules/(?!${paths.shift()}`;\n paths.forEach((path) => (regexp += `|${path}`));\n regexp += '/)';\n return RegExp(regexp, 'u');\n}\n\n/**\n * Helper function remove any leading and trailing slashes from dependency list.\n *\n * @param dependencies - An array of dependencies to sanitize.\n * @returns An array of sanitized paths.\n */\nexport function sanitizeDependencyPaths(dependencies: string[]): string[] {\n return dependencies.map((dependency) => {\n return dependency.replace(/^[/\\\\]+/u, '').replace(/[/\\\\]+$/u, '');\n });\n}\n\n/**\n * Check the Yargs argv object, to see if the provided options are valid. The\n * options are invalid if both `depsToTranspile` are provided, and\n * `transpilationMode` is not set to `localAndDeps`.\n *\n * @param argv - The Yargs arguments object.\n * @throws If the `depsToTranspile` is set, and `transpilationMode` is not set\n * to `localAndDeps`.\n */\nexport function processInvalidTranspilation(argv: YargsArgs) {\n if (\n argv.depsToTranspile &&\n argv.transpilationMode !== TranspilationModes.localAndDeps\n ) {\n throw new Error(\n '\"depsToTranspile\" can only be specified if \"transpilationMode\" is set to \"localAndDeps\" .',\n );\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var _a;
|
|
2
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
4
|
const fs_1 = require("fs");
|
|
4
5
|
// eslint-disable-next-line import/no-unassigned-import
|
|
@@ -20,20 +21,12 @@ lockdown({
|
|
|
20
21
|
*/
|
|
21
22
|
function getMockEndowments() {
|
|
22
23
|
const endowments = (0, mock_1.generateMockEndowments)();
|
|
23
|
-
return {
|
|
24
|
-
...endowments,
|
|
25
|
-
window: endowments,
|
|
26
|
-
self: endowments,
|
|
27
|
-
};
|
|
24
|
+
return Object.assign(Object.assign({}, endowments), { window: endowments, self: endowments });
|
|
28
25
|
}
|
|
29
26
|
const snapFilePath = process.argv[2];
|
|
30
27
|
const snapModule = { exports: {} };
|
|
31
|
-
new Compartment({
|
|
32
|
-
|
|
33
|
-
module: snapModule,
|
|
34
|
-
exports: snapModule.exports,
|
|
35
|
-
}).evaluate((0, fs_1.readFileSync)(snapFilePath, 'utf8'));
|
|
36
|
-
if (!snapModule.exports?.onRpcRequest) {
|
|
28
|
+
new Compartment(Object.assign(Object.assign({}, getMockEndowments()), { module: snapModule, exports: snapModule.exports })).evaluate((0, fs_1.readFileSync)(snapFilePath, 'utf8'));
|
|
29
|
+
if (!((_a = snapModule.exports) === null || _a === void 0 ? void 0 : _a.onRpcRequest)) {
|
|
37
30
|
console.warn(`The Snap doesn't have an "onRpcRequest" export defined.`);
|
|
38
31
|
}
|
|
39
32
|
setTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../../../src/cmds/eval/eval-worker.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../../../src/cmds/eval/eval-worker.ts"],"names":[],"mappings":";;;AAAA,2BAAkC;AAClC,uDAAuD;AACvD,wBAAsB;AACtB,iCAAgD;AAIhD,QAAQ,CAAC;IACP,aAAa,EAAE,QAAQ;IACvB,WAAW,EAAE,QAAQ;IACrB,UAAU,EAAE,QAAQ;IACpB,UAAU,EAAE,QAAQ;IACpB,cAAc,EAAE,QAAQ;CACzB,CAAC,CAAC;AAEH;;;;;;GAMG;AACH,SAAS,iBAAiB;IACxB,MAAM,UAAU,GAAG,IAAA,6BAAsB,GAAE,CAAC;IAC5C,uCACK,UAAU,KACb,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,UAAU,IAChB;AACJ,CAAC;AAED,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAErC,MAAM,UAAU,GAAsB,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;AAEtD,IAAI,WAAW,iCACV,iBAAiB,EAAE,KACtB,MAAM,EAAE,UAAU,EAClB,OAAO,EAAE,UAAU,CAAC,OAAO,IAC3B,CAAC,QAAQ,CAAC,IAAA,iBAAY,EAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC;AAEhD,IAAI,CAAC,CAAA,MAAA,UAAU,CAAC,OAAO,0CAAE,YAAY,CAAA,EAAE;IACrC,OAAO,CAAC,IAAI,CAAC,yDAAyD,CAAC,CAAC;CACzE;AAED,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,8BAA8B","sourcesContent":["import { readFileSync } from 'fs';\n// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nif (!snapModule.exports?.onRpcRequest) {\n console.warn(`The Snap doesn't have an \"onRpcRequest\" export defined.`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"]}
|
package/dist/cmds/eval/mock.js
CHANGED
|
@@ -25,7 +25,7 @@ function getMockSnapProvider() {
|
|
|
25
25
|
* @param value - The value to check.
|
|
26
26
|
* @returns `true` if the value is a constructor, or `false` otherwise.
|
|
27
27
|
*/
|
|
28
|
-
const isConstructor = (value) => Boolean(typeof value
|
|
28
|
+
const isConstructor = (value) => { var _a, _b; return Boolean(typeof ((_b = (_a = value === null || value === void 0 ? void 0 : value.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) === 'string'); };
|
|
29
29
|
exports.isConstructor = isConstructor;
|
|
30
30
|
/**
|
|
31
31
|
* A function that always returns `true`.
|
|
@@ -74,7 +74,7 @@ const generateMockEndowment = (key) => {
|
|
|
74
74
|
return globalValue;
|
|
75
75
|
}
|
|
76
76
|
// Fall back to mockWindow for certain APIs not exposed in global in Node.JS
|
|
77
|
-
const globalOrMocked = globalValue
|
|
77
|
+
const globalOrMocked = globalValue !== null && globalValue !== void 0 ? globalValue : mockWindow[key];
|
|
78
78
|
const type = typeof globalOrMocked;
|
|
79
79
|
const isFunction = type === 'function';
|
|
80
80
|
if (isFunction && (0, exports.isConstructor)(globalOrMocked)) {
|
|
@@ -92,7 +92,7 @@ const generateMockEndowment = (key) => {
|
|
|
92
92
|
* @returns A map of endowments.
|
|
93
93
|
*/
|
|
94
94
|
const generateMockEndowments = () => {
|
|
95
|
-
return exports.ALL_APIS.reduce((acc, cur) => ({
|
|
95
|
+
return exports.ALL_APIS.reduce((acc, cur) => (Object.assign(Object.assign({}, acc), { [cur]: generateMockEndowment(cur) })), { wallet: getMockSnapProvider() });
|
|
96
96
|
};
|
|
97
97
|
exports.generateMockEndowments = generateMockEndowments;
|
|
98
98
|
//# sourceMappingURL=mock.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock.js","sourceRoot":"","sources":["../../../src/cmds/eval/mock.ts"],"names":[],"mappings":";;;;;;AAAA,oDAAkC;AAClC,oDAA4B;AAC5B,iEAAgE;AAEhE,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AAE/B,QAAA,QAAQ,GAAa,CAAC,GAAG,qCAAkB,EAAE,GAAG,YAAY,CAAC,CAAC;AAM3E;;;;GAIG;AACH,SAAS,mBAAmB;IAC1B,MAAM,YAAY,GAAG,IAAI,gBAAY,EAA+B,CAAC;IACrE,YAAY,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC;IACxC,OAAO,YAAgC,CAAC;AAC1C,CAAC;AAED;;;;;GAKG;AACI,MAAM,aAAa,GAAG,CAAC,KAAU,EAAE,EAAE,
|
|
1
|
+
{"version":3,"file":"mock.js","sourceRoot":"","sources":["../../../src/cmds/eval/mock.ts"],"names":[],"mappings":";;;;;;AAAA,oDAAkC;AAClC,oDAA4B;AAC5B,iEAAgE;AAEhE,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AAE/B,QAAA,QAAQ,GAAa,CAAC,GAAG,qCAAkB,EAAE,GAAG,YAAY,CAAC,CAAC;AAM3E;;;;GAIG;AACH,SAAS,mBAAmB;IAC1B,MAAM,YAAY,GAAG,IAAI,gBAAY,EAA+B,CAAC;IACrE,YAAY,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC;IACxC,OAAO,YAAgC,CAAC;AAC1C,CAAC;AAED;;;;;GAKG;AACI,MAAM,aAAa,GAAG,CAAC,KAAU,EAAE,EAAE,eAC1C,OAAA,OAAO,CAAC,OAAO,CAAA,MAAA,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,SAAS,0CAAE,WAAW,0CAAE,IAAI,CAAA,KAAK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AAU,IAAI,CAAC,cAAc,EAAE;QACxC,qCAAqC;QACrC,OAAO,YAAY,CAAC;KACrB;IACD,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAEF;;;;GAIG;AACI,MAAM,sBAAsB,GAAG,GAAG,EAAE;IACzC,OAAO,gBAAQ,CAAC,MAAM,CACpB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,GAAG,CAAC,IAAG,EAC7D,EAAE,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAClC,CAAC;AACJ,CAAC,CAAC;AALW,QAAA,sBAAsB,0BAKjC","sourcesContent":["import EventEmitter from 'events';\nimport crypto from 'crypto';\nimport { DEFAULT_ENDOWMENTS } from '@metamask/snap-controllers';\n\nconst NETWORK_APIS = ['fetch', 'WebSocket'];\n\nexport const ALL_APIS: string[] = [...DEFAULT_ENDOWMENTS, ...NETWORK_APIS];\n\ntype MockSnapProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap provider, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapProvider(): MockSnapProvider {\n const mockProvider = new EventEmitter() as Partial<MockSnapProvider>;\n mockProvider.request = async () => true;\n return mockProvider as MockSnapProvider;\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 have types for them and can use that to generate mocks if needed\nconst mockWindow = {\n WebSocket: MockClass,\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 as any)[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 { wallet: getMockSnapProvider() },\n );\n};\n"]}
|
package/dist/cmds/init/index.js
CHANGED
|
@@ -16,11 +16,7 @@ const initUtils_1 = require("./initUtils");
|
|
|
16
16
|
async function init(argv) {
|
|
17
17
|
console.log();
|
|
18
18
|
const newArgs = await (0, initHandler_1.initHandler)(argv);
|
|
19
|
-
await (0, buildHandler_1.build)({
|
|
20
|
-
...newArgs,
|
|
21
|
-
manifest: false,
|
|
22
|
-
eval: true,
|
|
23
|
-
});
|
|
19
|
+
await (0, buildHandler_1.build)(Object.assign(Object.assign({}, newArgs), { manifest: false, eval: true }));
|
|
24
20
|
await (0, initHandler_1.updateManifestShasum)();
|
|
25
21
|
console.log('\nSnap project successfully initiated!');
|
|
26
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/init/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,wDAA8C;AAC9C,+CAAkE;AAClE,2CAAiD;AAsBjD;;;;;;GAMG;AACH,KAAK,UAAU,IAAI,CAAC,IAAe;IACjC,OAAO,CAAC,GAAG,EAAE,CAAC;IACd,MAAM,OAAO,GAAG,MAAM,IAAA,yBAAW,EAAC,IAAI,CAAC,CAAC;IAExC,MAAM,IAAA,oBAAK,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/init/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,wDAA8C;AAC9C,+CAAkE;AAClE,2CAAiD;AAsBjD;;;;;;GAMG;AACH,KAAK,UAAU,IAAI,CAAC,IAAe;IACjC,OAAO,CAAC,GAAG,EAAE,CAAC;IACd,MAAM,OAAO,GAAG,MAAM,IAAA,yBAAW,EAAC,IAAI,CAAC,CAAC;IAExC,MAAM,IAAA,oBAAK,kCACN,OAAO,KACV,QAAQ,EAAE,KAAK,EACf,IAAI,EAAE,IAAI,IACV,CAAC;IAEH,MAAM,IAAA,kCAAoB,GAAE,CAAC;IAE7B,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;AACxD,CAAC;AAxCD,iBAAS;IACP,OAAO,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC;IACtB,IAAI,EAAE,yBAAyB;IAC/B,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI;aACD,MAAM,CAAC,KAAK,EAAE,kBAAQ,CAAC,GAAG,CAAC;aAC3B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,aAAa,EAAE,kBAAQ,CAAC,WAAW,CAAC;aAC3C,MAAM,CAAC,UAAU,EAAE,kBAAQ,CAAC,QAAQ,CAAC;aACrC,UAAU,CACT,CAAC,CAAC,SAAoB,EAAE,EAAE;YACxB,IAAA,8BAAkB,EAAC,SAAS,CAAC,CAAC;QAChC,CAAC,CAAQ,EACT,IAAI,CACL,CAAC;IACN,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;CACzC,CAAC","sourcesContent":["import yargs, { Arguments } from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { build } from '../build/buildHandler';\nimport { initHandler, updateManifestShasum } from './initHandler';\nimport { correctDefaultArgs } from './initUtils';\n\nexport = {\n command: ['init', 'i'],\n desc: 'Initialize Snap package',\n builder: (yarg: yargs.Argv) => {\n yarg\n .option('src', builders.src)\n .option('dist', builders.dist)\n .option('port', builders.port)\n .option('outfileName', builders.outfileName)\n .option('template', builders.template)\n .middleware(\n ((yargsArgv: Arguments) => {\n correctDefaultArgs(yargsArgv);\n }) as any,\n true,\n );\n },\n handler: (argv: YargsArgs) => init(argv),\n};\n\n/**\n * The main entrypoint for the init command. This calls the init handler to\n * initialize the snap package, builds the snap, and then updates the manifest\n * with the shasum of the built snap.\n *\n * @param argv - The Yargs arguments object.\n */\nasync function init(argv: YargsArgs): Promise<void> {\n console.log();\n const newArgs = await initHandler(argv);\n\n await build({\n ...newArgs,\n manifest: false,\n eval: true,\n });\n\n await updateManifestShasum();\n\n console.log('\\nSnap project successfully initiated!');\n}\n"]}
|
|
@@ -3,6 +3,6 @@
|
|
|
3
3
|
"source": "module.exports.onRpcRequest = async ({ origin, request }) => {\n switch (request.method) {\n case 'hello':\n return wallet.request({\n method: 'snap_confirm',\n params: [\n {\n prompt: `Hello, ${origin}!`,\n description:\n 'This custom confirmation is just for display purposes.',\n textAreaContent:\n 'But you can edit the snap source code to make it do something, if you want to!',\n },\n ],\n });\n default:\n throw new Error('Method not found.');\n }\n};\n",
|
|
4
4
|
"typescriptHtml": "<!doctype html>\n<html>\n </head>\n <title>Hello, Snaps!</title>\n <link rel=\"icon\" type=\"image/svg\" href=\"./images/icon.svg\"/>\n </head>\n\n <body>\n <h1>Hello, Snaps!</h1>\n <details>\n <summary>Instructions</summary>\n <ul>\n <li>First, click \"Connect\". Then, try out the other buttons!</li>\n <li>Please note that:</li>\n <ul>\n <li>\n The <code>snap.manifest.json</code> and <code>package.json</code> must be located in the server root directory...\n </li>\n <li>\n The Snap bundle must be hosted at the location specified by the <code>location</code> field of <code>snap.manifest.json</code>.\n </li>\n </ul>\n </ul>\n </details>\n <br/>\n\n <button class=\"connect\">Connect</button>\n <button class=\"sendHello\">Send Hello</button>\n </body>\n\n <script>\n const snapId = `local:${window.location.href}`;\n\n const connectButton = document.querySelector('button.connect')\n const sendButton = document.querySelector('button.sendHello')\n\n connectButton.addEventListener('click', connect)\n sendButton.addEventListener('click', send)\n\n // here we get permissions to interact with and install the snap\n async function connect () {\n await ethereum.request({\n method: 'wallet_enable',\n params: [{\n wallet_snap: { [snapId]: {} },\n }]\n })\n }\n\n // here we call the snap's \"hello\" method\n async function send () {\n try {\n await ethereum.request({\n method: 'wallet_invokeSnap',\n params: [snapId, {\n method: 'hello'\n }]\n })\n } catch (err) {\n console.error(err)\n alert('Problem happened: ' + err.message || err)\n }\n }\n </script>\n</html>\n",
|
|
5
5
|
"typescriptSource": "import { OnRpcRequestHandler } from '@metamask/snap-types';\n\nexport const onRpcRequest: OnRpcRequestHandler = ({ origin, request }) => {\n switch (request.method) {\n case 'hello':\n return wallet.request({\n method: 'snap_confirm',\n params: [\n {\n prompt: `Hello, ${origin}!`,\n description:\n 'This custom confirmation is just for display purposes.',\n textAreaContent:\n 'But you can edit the snap source code to make it do something, if you want to!',\n },\n ],\n });\n default:\n throw new Error('Method not found.');\n }\n};\n",
|
|
6
|
-
"typescriptConfig": "{\n \"extends\": \"../../../../tsconfig.packages.json\",\n \"compilerOptions\": {\n \"typeRoots\": [\"../../../../node_modules/@types\"]\n },\n \"files\": [\"
|
|
6
|
+
"typescriptConfig": "{\n \"extends\": \"../../../../tsconfig.packages.json\",\n \"compilerOptions\": {\n \"typeRoots\": [\"../../../../node_modules/@types\"]\n },\n \"files\": [\"./node_modules/@metamask/snap-types/global.d.ts\"],\n \"include\": [\"src\"]\n}\n",
|
|
7
7
|
"icon": "<svg width=\"24\" height=\"25\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M17.037 0H6.975C2.605 0 0 2.617 0 6.987v10.05c0 4.37 2.605 6.975 6.975 6.975h10.05c4.37 0 6.975-2.605 6.975-6.976V6.988C24.012 2.617 21.407 0 17.037 0ZM11.49 17.757c0 .36-.18.684-.492.876a.975.975 0 0 1-.54.156 1.11 1.11 0 0 1-.469-.108l-4.202-2.1a1.811 1.811 0 0 1-.985-1.61v-3.973c0-.36.18-.685.493-.877a1.04 1.04 0 0 1 1.008-.048l4.202 2.101a1.8 1.8 0 0 1 .997 1.609v3.974h-.012Zm-.252-6.423L6.723 8.896a1.045 1.045 0 0 1-.528-.924c0-.384.204-.744.528-.924l4.515-2.438a1.631 1.631 0 0 1 1.524 0l4.515 2.438c.324.18.528.528.528.924s-.204.744-.528.924l-4.515 2.438c-.24.132-.504.192-.768.192a1.54 1.54 0 0 1-.756-.192Zm7.972 3.638c0 .684-.385 1.308-.997 1.608l-4.202 2.101c-.144.072-.3.108-.468.108a.975.975 0 0 1-.54-.156 1.017 1.017 0 0 1-.493-.876v-3.974c0-.684.384-1.309.997-1.609l4.202-2.101a1.04 1.04 0 0 1 1.008.048c.313.192.493.516.493.877v3.974Z\" fill=\"#24272A\"/></svg>"
|
|
8
8
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initHandler.js","sourceRoot":"","sources":["../../../src/cmds/init/initHandler.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAoC;AACpC,gDAA6B;AAC7B,iEAIoC;AACpC,oDAA4B;AA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AAI,CAAC,SAAS,CAAC,IAAA,qCAAmB,EAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CACvD,CAAC;AACJ,CAAC;AAfD,oDAeC","sourcesContent":["import { promises as fs } from 'fs';\nimport pathUtils from 'path';\nimport {\n getSnapSourceShasum,\n NpmSnapFileNames,\n SnapManifest,\n} from '@metamask/snap-controllers';\nimport mkdirp from 'mkdirp';\nimport { YargsArgs } from '../../types/yargs';\nimport {\n closePrompt,\n CONFIG_FILE,\n logError,\n readJsonFile,\n SnapConfig,\n} from '../../utils';\nimport { getWritableManifest } from '../manifest/manifestHandler';\nimport { TemplateType } from '../../builders';\nimport template from './init-template.json';\nimport {\n asyncPackageInit,\n buildSnapManifest,\n isTemplateTypescript,\n prepareWorkingDirectory,\n} from './initUtils';\n\n/**\n * Creates a new snap package, based on one of the provided templates. This\n * creates all the necessary files, like `package.json`, `snap.config.js`, etc.\n * to start developing a snap.\n *\n * @param argv - The Yargs arguments object.\n * @returns The Yargs arguments augmented with the new `dist`, `outfileName` and\n * `src` properties.\n * @throws If initialization of the snap package failed.\n */\nexport async function initHandler(argv: YargsArgs) {\n console.log(`MetaMask Snaps: Initialize\\n`);\n\n const packageJson = await asyncPackageInit(argv);\n\n await prepareWorkingDirectory();\n\n console.log(`\\nInit: Building '${NpmSnapFileNames.Manifest}'...\\n`);\n\n const [snapManifest, _newArgs] = await buildSnapManifest(argv, packageJson);\n\n const newArgs = Object.keys(_newArgs)\n .sort()\n .reduce((sorted, key) => {\n sorted[key] = _newArgs[key as keyof typeof _newArgs];\n return sorted;\n }, {} as YargsArgs);\n\n const isTypeScript = isTemplateTypescript(argv.template as TemplateType);\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(snapManifest, null, 2)}\\n`,\n );\n } catch (err) {\n logError(\n `Init Error: Failed to write '${NpmSnapFileNames.Manifest}'.`,\n err,\n );\n throw err;\n }\n\n console.log(`\\nInit: Created '${NpmSnapFileNames.Manifest}'.`);\n\n // Write main .js entry file\n const { src } = newArgs;\n\n try {\n if (pathUtils.basename(src) !== src) {\n await mkdirp(pathUtils.dirname(src));\n }\n\n await fs.writeFile(\n src,\n isTypeScript ? template.typescriptSource : template.source,\n );\n\n console.log(`Init: Created '${src}'.`);\n } catch (err) {\n logError(`Init Error: Failed to write '${src}'.`, err);\n throw err;\n }\n\n // Write index.html\n try {\n await fs.writeFile(\n 'index.html',\n isTypeScript ? template.typescriptHtml : template.html,\n );\n\n console.log(`Init: Created 'index.html'.`);\n } catch (err) {\n logError(`Init Error: Failed to write 'index.html'.`, err);\n throw err;\n }\n\n // Write tsconfig.json\n if (isTypeScript) {\n try {\n await fs.writeFile('tsconfig.json', template.typescriptConfig);\n console.log(`Init: Created 'tsconfig.json'.`);\n } catch (err) {\n logError(`Init Error: Failed to write 'tsconfig.json'.`, err);\n throw err;\n }\n }\n\n // Write config file\n try {\n const defaultConfig: SnapConfig = {\n cliOptions: newArgs,\n };\n const defaultConfigFile = `module.exports = ${JSON.stringify(\n defaultConfig,\n null,\n 2,\n )}\n `;\n await fs.writeFile(CONFIG_FILE, defaultConfigFile);\n console.log(`Init: Wrote '${CONFIG_FILE}' config file`);\n } catch (err) {\n logError(`Init Error: Failed to write '${CONFIG_FILE}'.`, err);\n throw err;\n }\n\n // Write icon\n const iconPath = 'images/icon.svg';\n try {\n if (pathUtils.basename(iconPath) !== iconPath) {\n await mkdirp(pathUtils.dirname(iconPath));\n }\n await fs.writeFile(iconPath, template.icon);\n\n console.log(`Init: Created '${iconPath}'.`);\n } catch (err) {\n logError(`Init Error: Failed to write '${iconPath}'.`, err);\n throw err;\n }\n\n closePrompt();\n return { ...argv, ...newArgs };\n}\n\n/**\n * This updates the Snap shasum value of the manifest after building the Snap\n * during the init command.\n */\nexport async function updateManifestShasum() {\n const manifest = (await readJsonFile(\n NpmSnapFileNames.Manifest,\n )) as SnapManifest;\n\n const bundleContents = await fs.readFile(\n manifest.source.location.npm.filePath,\n 'utf8',\n );\n\n manifest.source.shasum = getSnapSourceShasum(bundleContents);\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n JSON.stringify(getWritableManifest(manifest), null, 2),\n );\n}\n"]}
|
|
@@ -9,7 +9,7 @@ module.exports = {
|
|
|
9
9
|
command: ['manifest', 'm'],
|
|
10
10
|
desc: 'Validate the snap.manifest.json file',
|
|
11
11
|
builder: (yarg) => {
|
|
12
|
-
yarg.option('writeManifest', {
|
|
12
|
+
yarg.option('writeManifest', Object.assign(Object.assign({}, builders_1.default.writeManifest), { alias: ['fix'] }));
|
|
13
13
|
},
|
|
14
14
|
handler: async (argv) => {
|
|
15
15
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/manifest/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,uCAAuC;AACvC,uDAAoD;AAEpD,iBAAS;IACP,OAAO,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC;IAC1B,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,eAAe,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/manifest/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,uCAAuC;AACvC,uDAAoD;AAEpD,iBAAS;IACP,OAAO,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC;IAC1B,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,eAAe,kCAAO,kBAAQ,CAAC,aAAa,KAAE,KAAK,EAAE,CAAC,KAAK,CAAC,IAAG,CAAC;IAC9E,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,IAAe,EAAE,EAAE;QACjC,IAAI;YACF,MAAM,IAAA,iCAAe,EAAC,IAAI,CAAC,CAAC;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,IAAA,gBAAQ,EAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC3B,MAAM,GAAG,CAAC;SACX;IACH,CAAC;CACF,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { logError } from '../../utils';\nimport { manifestHandler } from './manifestHandler';\n\nexport = {\n command: ['manifest', 'm'],\n desc: 'Validate the snap.manifest.json file',\n builder: (yarg: yargs.Argv) => {\n yarg.option('writeManifest', { ...builders.writeManifest, alias: ['fix'] });\n },\n handler: async (argv: YargsArgs) => {\n try {\n await manifestHandler(argv);\n } catch (err) {\n logError(err.message, err);\n throw err;\n }\n },\n};\n"]}
|
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
|
3
|
+
var t = {};
|
|
4
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
5
|
+
t[p] = s[p];
|
|
6
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
7
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
8
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
9
|
+
t[p[i]] = s[p[i]];
|
|
10
|
+
}
|
|
11
|
+
return t;
|
|
12
|
+
};
|
|
2
13
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
14
|
exports.getWritableManifest = exports.manifestHandler = void 0;
|
|
4
15
|
const fs_1 = require("fs");
|
|
@@ -23,12 +34,12 @@ const ManifestSortOrder = {
|
|
|
23
34
|
* @param argv.writeManifest - Whether to write the fixed manifest to disk.
|
|
24
35
|
*/
|
|
25
36
|
async function manifestHandler({ writeManifest, }) {
|
|
37
|
+
var _a, _b, _c;
|
|
26
38
|
let didUpdate = false;
|
|
27
39
|
let hasWarnings = false;
|
|
28
40
|
const unvalidatedManifest = await readSnapJsonFile(utils_1.NpmSnapFileNames.Manifest);
|
|
29
41
|
const iconPath = unvalidatedManifest && typeof unvalidatedManifest === 'object'
|
|
30
|
-
? unvalidatedManifest.source
|
|
31
|
-
?.iconPath
|
|
42
|
+
? (_c = (_b = (_a = unvalidatedManifest.source) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.npm) === null || _c === void 0 ? void 0 : _c.iconPath
|
|
32
43
|
: undefined;
|
|
33
44
|
const snapFiles = {
|
|
34
45
|
manifest: unvalidatedManifest,
|
|
@@ -51,7 +62,7 @@ async function manifestHandler({ writeManifest, }) {
|
|
|
51
62
|
for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {
|
|
52
63
|
manifest = fixManifest(partiallyValidatedFiles, error);
|
|
53
64
|
try {
|
|
54
|
-
(0, utils_1.validateNpmSnapManifest)({
|
|
65
|
+
(0, utils_1.validateNpmSnapManifest)(Object.assign(Object.assign({}, partiallyValidatedFiles), { manifest }), errorPrefix);
|
|
55
66
|
isInvalid = false;
|
|
56
67
|
}
|
|
57
68
|
catch (nextValidationError) {
|
|
@@ -137,10 +148,10 @@ async function readSnapJsonFile(snapJsonFileName) {
|
|
|
137
148
|
* @returns The contents of the bundle file, if any.
|
|
138
149
|
*/
|
|
139
150
|
async function getSnapSourceCode(manifest) {
|
|
151
|
+
var _a, _b, _c;
|
|
140
152
|
if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {
|
|
141
153
|
/* istanbul ignore next: optional chaining */
|
|
142
|
-
const sourceFilePath = manifest.source
|
|
143
|
-
?.npm?.filePath;
|
|
154
|
+
const sourceFilePath = (_c = (_b = (_a = manifest.source) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.npm) === null || _c === void 0 ? void 0 : _c.filePath;
|
|
144
155
|
try {
|
|
145
156
|
return sourceFilePath
|
|
146
157
|
? await fs_1.promises.readFile(sourceFilePath, 'utf8')
|
|
@@ -195,8 +206,8 @@ function fixManifest(snapFiles, error) {
|
|
|
195
206
|
* @returns The disk-ready manifest.
|
|
196
207
|
*/
|
|
197
208
|
function getWritableManifest(manifest) {
|
|
198
|
-
const { repository,
|
|
199
|
-
return Object.keys(repository ? {
|
|
209
|
+
const { repository } = manifest, remaining = __rest(manifest, ["repository"]);
|
|
210
|
+
return Object.keys(repository ? Object.assign(Object.assign({}, remaining), { repository }) : remaining)
|
|
200
211
|
.sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])
|
|
201
212
|
.reduce((outManifest, key) => {
|
|
202
213
|
outManifest[key] = manifest[key];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifestHandler.js","sourceRoot":"","sources":["../../../src/cmds/manifest/manifestHandler.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAEpC,uEASqD;AACrD,uCAAsD;AAGtD,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAEvC,MAAM,iBAAiB,GAAuC;IAC5D,OAAO,EAAE,CAAC;IACV,YAAY,EAAE,CAAC;IACf,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;;GAOG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,aAAa,GACH;IACV,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,WAAW,GAAG,KAAK,CAAC;IAExB,MAAM,mBAAmB,GAAG,MAAM,gBAAgB,CAAC,wBAAgB,CAAC,QAAQ,CAAC,CAAC;IAE9E,MAAM,QAAQ,GACZ,mBAAmB,IAAI,OAAO,mBAAmB,KAAK,QAAQ;QAC5D,CAAC,CAAE,mBAA6C,CAAC,MAAM,EAAE,QAAQ,EAAE,GAAG;YAClE,EAAE,QAAQ;QACd,CAAC,CAAC,SAAS,CAAC;IAEhB,MAAM,SAAS,GAAyB;QAC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CAAC,WAAW,EAAE,GAAG,EAAE,EAAE;QAC1B,WAAmB,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC1C,OAAO,WAAW,CAAC;IACrB,CAAC,EAAE,EAAkB,CAAC,CAAC;AAC3B,CAAC;AAZD,kDAYC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json, SnapManifest } from '@metamask/snap-controllers';\nimport {\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n validateNpmSnap,\n validateNpmSnapManifest,\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n SnapValidationFailureReason,\n SnapFiles,\n} from '@metamask/snap-controllers/dist/snaps/utils';\nimport { deepClone, readJsonFile } from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\n\nconst errorPrefix = 'Manifest Error: ';\n\nconst ManifestSortOrder: Record<keyof SnapManifest, number> = {\n version: 1,\n proposedName: 2,\n description: 2,\n repository: 3,\n source: 4,\n initialPermissions: 5,\n manifestVersion: 6,\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param argv - The Yargs `argv` object.\n * @param argv.writeManifest - Whether to write the fixed manifest to disk.\n */\nexport async function manifestHandler({\n writeManifest,\n}: YargsArgs): Promise<void> {\n let didUpdate = false;\n let hasWarnings = false;\n\n const unvalidatedManifest = await readSnapJsonFile(NpmSnapFileNames.Manifest);\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(NpmSnapFileNames.PackageJson),\n sourceCode: await getSnapSourceCode(unvalidatedManifest),\n svgIcon: iconPath && (await fs.readFile(iconPath, 'utf8')),\n };\n\n let manifest: SnapManifest | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles, errorPrefix));\n } catch (error) {\n if (writeManifest && error instanceof ProgrammaticallyFixableSnapError) {\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the SnapValidationFailureReason enum, so we only\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(partiallyValidatedFiles, error);\n\n try {\n validateNpmSnapManifest(\n { ...partiallyValidatedFiles, manifest },\n errorPrefix,\n );\n\n isInvalid = false;\n } catch (nextValidationError) {\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal Error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n }\n }\n\n didUpdate = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n logManifestWarning(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n // Validation complete, finish work and notify user.\n\n if (writeManifest) {\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\n`,\n );\n\n if (didUpdate) {\n console.log(`Manifest: Updated snap.manifest.json`);\n }\n } catch (error) {\n throw new Error(\n `${errorPrefix}Failed to update snap.manifest.json: ${error.message}`,\n );\n }\n }\n\n if (hasWarnings) {\n console.log(\n `Manifest Warning: Validation of snap.manifest.json completed with warnings. See above.`,\n );\n } else {\n console.log(`Manifest Success: Validated snap.manifest.json!`);\n }\n\n /**\n * Logs a manifest warning, if `suppressWarnings` is not enabled.\n *\n * @param message - The message to log.\n */\n function logManifestWarning(message: string) {\n if (!global.snaps.suppressWarnings) {\n hasWarnings = true;\n console.warn(`Manifest Warning: ${message}`);\n }\n }\n}\n\n/**\n * Utility function for reading `package.json` or the Snap manifest file.\n * These are assumed to be in the current working directory.\n *\n * @param snapJsonFileName - The name of the file to read.\n * @returns The parsed JSON file.\n */\nasync function readSnapJsonFile(\n snapJsonFileName: NpmSnapFileNames,\n): Promise<Json> {\n try {\n return await readJsonFile(snapJsonFileName);\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `${errorPrefix}Could not find '${snapJsonFileName}'. Please ensure that ` +\n `you are running the command in the project root directory.`,\n );\n }\n throw new Error(`${errorPrefix}${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the bundle file, if any.\n */\nasync function getSnapSourceCode(manifest: Json): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n /* istanbul ignore next: optional chaining */\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(sourceFilePath, 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(\n `Manifest Error: Failed to read Snap bundle file: ${error.message}`,\n );\n }\n }\n return undefined;\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nfunction fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : null;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default:\n // eslint-disable-next-line no-case-declarations\n const failureReason: never = error.reason;\n throw new Error(\n `Unrecognized validation failure reason: '${failureReason}'`,\n );\n }\n\n return manifestCopy;\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n return (\n Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[]\n )\n .sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])\n .reduce((outManifest, key) => {\n (outManifest as any)[key] = manifest[key];\n return outManifest;\n }, {} as SnapManifest);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"manifestHandler.js","sourceRoot":"","sources":["../../../src/cmds/manifest/manifestHandler.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,2BAAoC;AAEpC,uEASqD;AACrD,uCAAsD;AAGtD,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAEvC,MAAM,iBAAiB,GAAuC;IAC5D,OAAO,EAAE,CAAC;IACV,YAAY,EAAE,CAAC;IACf,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CA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,MAAM,IAAI,KAAK,CACb,4CAA4C,aAAa,GAAG,CAC7D,CAAC;KACL;IAED,OAAO,YAAY,CAAC;AACtB,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,mBAAmB,CAAC,QAAsB;IACxD,MAAM,EAAE,UAAU,KAAmB,QAAQ,EAAtB,SAAS,UAAK,QAAQ,EAAvC,cAA4B,CAAW,CAAC;IAC9C,OACE,MAAM,CAAC,IAAI,CACT,UAAU,CAAC,CAAC,iCAAM,SAAS,KAAE,UAAU,IAAG,CAAC,CAAC,SAAS,CAExD;SACE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC;SAC3D,MAAM,CAAC,CAAC,WAAW,EAAE,GAAG,EAAE,EAAE;QAC1B,WAAmB,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC1C,OAAO,WAAW,CAAC;IACrB,CAAC,EAAE,EAAkB,CAAC,CAAC;AAC3B,CAAC;AAZD,kDAYC","sourcesContent":["import { promises as fs } from 'fs';\nimport type { Json, SnapManifest } from '@metamask/snap-controllers';\nimport {\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n validateNpmSnap,\n validateNpmSnapManifest,\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n SnapValidationFailureReason,\n SnapFiles,\n} from '@metamask/snap-controllers/dist/snaps/utils';\nimport { deepClone, readJsonFile } from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\n\nconst errorPrefix = 'Manifest Error: ';\n\nconst ManifestSortOrder: Record<keyof SnapManifest, number> = {\n version: 1,\n proposedName: 2,\n description: 2,\n repository: 3,\n source: 4,\n initialPermissions: 5,\n manifestVersion: 6,\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param argv - The Yargs `argv` object.\n * @param argv.writeManifest - Whether to write the fixed manifest to disk.\n */\nexport async function manifestHandler({\n writeManifest,\n}: YargsArgs): Promise<void> {\n let didUpdate = false;\n let hasWarnings = false;\n\n const unvalidatedManifest = await readSnapJsonFile(NpmSnapFileNames.Manifest);\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(NpmSnapFileNames.PackageJson),\n sourceCode: await getSnapSourceCode(unvalidatedManifest),\n svgIcon: iconPath && (await fs.readFile(iconPath, 'utf8')),\n };\n\n let manifest: SnapManifest | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles, errorPrefix));\n } catch (error) {\n if (writeManifest && error instanceof ProgrammaticallyFixableSnapError) {\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the SnapValidationFailureReason enum, so we only\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(partiallyValidatedFiles, error);\n\n try {\n validateNpmSnapManifest(\n { ...partiallyValidatedFiles, manifest },\n errorPrefix,\n );\n\n isInvalid = false;\n } catch (nextValidationError) {\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal Error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n }\n }\n\n didUpdate = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n logManifestWarning(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n // Validation complete, finish work and notify user.\n\n if (writeManifest) {\n try {\n await fs.writeFile(\n NpmSnapFileNames.Manifest,\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\n`,\n );\n\n if (didUpdate) {\n console.log(`Manifest: Updated snap.manifest.json`);\n }\n } catch (error) {\n throw new Error(\n `${errorPrefix}Failed to update snap.manifest.json: ${error.message}`,\n );\n }\n }\n\n if (hasWarnings) {\n console.log(\n `Manifest Warning: Validation of snap.manifest.json completed with warnings. See above.`,\n );\n } else {\n console.log(`Manifest Success: Validated snap.manifest.json!`);\n }\n\n /**\n * Logs a manifest warning, if `suppressWarnings` is not enabled.\n *\n * @param message - The message to log.\n */\n function logManifestWarning(message: string) {\n if (!global.snaps.suppressWarnings) {\n hasWarnings = true;\n console.warn(`Manifest Warning: ${message}`);\n }\n }\n}\n\n/**\n * Utility function for reading `package.json` or the Snap manifest file.\n * These are assumed to be in the current working directory.\n *\n * @param snapJsonFileName - The name of the file to read.\n * @returns The parsed JSON file.\n */\nasync function readSnapJsonFile(\n snapJsonFileName: NpmSnapFileNames,\n): Promise<Json> {\n try {\n return await readJsonFile(snapJsonFileName);\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `${errorPrefix}Could not find '${snapJsonFileName}'. Please ensure that ` +\n `you are running the command in the project root directory.`,\n );\n }\n throw new Error(`${errorPrefix}${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the bundle file, if any.\n */\nasync function getSnapSourceCode(manifest: Json): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n /* istanbul ignore next: optional chaining */\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(sourceFilePath, 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(\n `Manifest Error: Failed to read Snap bundle file: ${error.message}`,\n );\n }\n }\n return undefined;\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nfunction fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : null;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default:\n // eslint-disable-next-line no-case-declarations\n const failureReason: never = error.reason;\n throw new Error(\n `Unrecognized validation failure reason: '${failureReason}'`,\n );\n }\n\n return manifestCopy;\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n return (\n Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[]\n )\n .sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])\n .reduce((outManifest, key) => {\n (outManifest as any)[key] = manifest[key];\n return outManifest;\n }, {} as SnapManifest);\n}\n"]}
|
|
@@ -41,7 +41,7 @@ async function watch(argv) {
|
|
|
41
41
|
await (0, manifestHandler_1.manifestHandler)(argv);
|
|
42
42
|
}
|
|
43
43
|
if (shouldEval) {
|
|
44
|
-
await (0, evalHandler_1.snapEval)({
|
|
44
|
+
await (0, evalHandler_1.snapEval)(Object.assign(Object.assign({}, argv), { bundle: outfilePath }));
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watchHandler.js","sourceRoot":"","sources":["../../../src/cmds/watch/watchHandler.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAEhC,uCAOqB;AACrB,4CAAyC;AACzC,qDAA+C;AAC/C,iEAA8D;AAC9D,wDAA8C;AAE9C;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EACJ,IAAI,EACJ,IAAI,EAAE,UAAU,EAChB,QAAQ,EACR,WAAW,EACX,GAAG,EACH,KAAK,EAAE,WAAW,GACnB,GAAG,IAAI,CAAC;IACT,IAAI,WAAW,EAAE;QACf,IAAA,2BAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,wBAAgB,EAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAA,uBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,MAAM,OAAO,GACX,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7E,MAAM,WAAW,GAAG,IA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KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,eAAe,IAAI,EAAE,CAAC,CAAC;SAC3D,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAC;SAChE,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC;SAC5D,EAAE,CAAC,OAAO,EAAE,CAAC,KAAY,EAAE,EAAE;QAC5B,IAAA,gBAAQ,EAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC,CAAC;SAED,GAAG,CAAC,OAAO,CAAC,CAAC;IAEhB,OAAO,CAAC,GAAG,CAAC,aAAa,OAAO,kBAAkB,CAAC,CAAC;AACtD,CAAC;AA5ED,sBA4EC","sourcesContent":["import chokidar from 'chokidar';\nimport { YargsArgs } from '../../types/yargs';\nimport {\n getOutfilePath,\n loadConfig,\n logError,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '../../utils';\nimport { bundle } from '../build/bundle';\nimport { snapEval } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\nimport { serve } from '../serve/serveHandler';\n\n/**\n * Watch a directory and its subdirectories for changes, and build when files\n * are added or changed.\n *\n * Ignores 'node_modules' and dotfiles.\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - Arguments as an object generated by Yargs.\n * @param argv.src - The source file path.\n * @param argv.dist - The output directory path.\n * @param argv.'outfileName' - The output file name.\n */\nexport async function watch(argv: YargsArgs): Promise<void> {\n const {\n dist,\n eval: shouldEval,\n manifest,\n outfileName,\n src,\n serve: shouldServe,\n } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n const rootDir =\n src.indexOf('/') === -1 ? '.' : src.substring(0, src.lastIndexOf('/') + 1);\n const outfilePath = getOutfilePath(dist, outfileName as string);\n\n const buildSnap = async (path?: string, logMessage?: string) => {\n if (logMessage !== undefined) {\n console.log(logMessage);\n }\n\n try {\n await bundle(src, outfilePath, argv, loadConfig().bundlerCustomizer);\n\n if (manifest) {\n await manifestHandler(argv);\n }\n\n if (shouldEval) {\n await snapEval({ ...argv, bundle: outfilePath });\n }\n } catch (error) {\n logError(\n `Error ${\n path === undefined\n ? 'during initial build'\n : `while processing \"${path}\"`\n }.`,\n error,\n );\n }\n };\n\n chokidar\n .watch(rootDir, {\n ignoreInitial: true,\n ignored: [\n '**/node_modules/**',\n `**/${dist}/**`,\n `**/test/**`,\n `**/tests/**`,\n `**/*.test.js`,\n `**/*.test.ts`,\n /* istanbul ignore next */\n (str: string) => str !== '.' && str.startsWith('.'),\n ],\n })\n\n .on('ready', async () => {\n await buildSnap();\n if (shouldServe) {\n await serve(argv);\n }\n })\n .on('add', (path) => buildSnap(path, `File added: ${path}`))\n .on('change', (path) => buildSnap(path, `File changed: ${path}`))\n .on('unlink', (path) => console.log(`File removed: ${path}`))\n .on('error', (error: Error) => {\n logError(`Watcher error: ${error.message}`, error);\n })\n\n .add(rootDir);\n\n console.log(`Watching '${rootDir}' for changes...`);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "A CLI for developing MetaMask Snaps.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"@babel/plugin-transform-runtime": "^7.16.7",
|
|
47
47
|
"@babel/preset-env": "^7.16.7",
|
|
48
48
|
"@babel/preset-typescript": "^7.16.7",
|
|
49
|
-
"@metamask/snap-controllers": "^0.
|
|
50
|
-
"@metamask/snaps-browserify-plugin": "^0.
|
|
49
|
+
"@metamask/snap-controllers": "^0.18.0",
|
|
50
|
+
"@metamask/snaps-browserify-plugin": "^0.18.0",
|
|
51
51
|
"@metamask/utils": "^2.0.0",
|
|
52
52
|
"babelify": "^10.0.0",
|
|
53
53
|
"browserify": "^17.0.0",
|