@metamask/snaps-cli 0.13.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -1
- package/README.md +3 -2
- package/dist/cmds/build/buildHandler.js +1 -1
- package/dist/cmds/build/buildHandler.js.map +1 -1
- package/dist/cmds/build/bundle.d.ts +1 -0
- package/dist/cmds/build/bundle.js +19 -6
- 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 +16 -4
- package/dist/cmds/eval/eval-worker.js.map +1 -1
- package/dist/cmds/eval/mock.js +3 -4
- package/dist/cmds/eval/mock.js.map +1 -1
- package/dist/cmds/index.d.ts +1 -0
- package/dist/cmds/init/index.js +5 -1
- 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 +7 -18
- 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/dist/utils/misc.js +3 -2
- package/dist/utils/misc.js.map +1 -1
- package/dist/utils/snap-config.d.ts +1 -0
- package/dist/utils/snap-config.js +3 -3
- package/dist/utils/snap-config.js.map +1 -1
- package/package.json +12 -11
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.16.0]
|
|
10
|
+
### Changed
|
|
11
|
+
- **BREAKING:** Snaps are now required to export `onRpcRequest` to receive RPC requests ([#481](https://github.com/MetaMask/snaps-skunkworks/pull/481), [#533](https://github.com/MetaMask/snaps-skunkworks/pull/533), [#538](https://github.com/MetaMask/snaps-skunkworks/pull/538), [#541](https://github.com/MetaMask/snaps-skunkworks/pull/541), [#544](https://github.com/MetaMask/snaps-skunkworks/pull/544))
|
|
12
|
+
- The type of the function is available in `@metamask/snap-types` as `OnRpcRequestHandler`.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
- Fix importing local files in TypeScript Snaps ([#527](https://github.com/MetaMask/snaps-skunkworks/pull/527))
|
|
16
|
+
- Fix `build` command when the CLI is installed globally ([#542](https://github.com/MetaMask/snaps-skunkworks/pull/542))
|
|
17
|
+
|
|
18
|
+
## [0.15.0]
|
|
19
|
+
### Added
|
|
20
|
+
- Add support for building TypeScript Snaps ([#443](https://github.com/MetaMask/snaps-skunkworks/pull/443))
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
- Fix an issue where comment stripping would break for large files ([#468](https://github.com/MetaMask/snaps-skunkworks/pull/468))
|
|
24
|
+
|
|
25
|
+
## [0.14.0]
|
|
26
|
+
### Changed
|
|
27
|
+
- **BREAKING:** Increase TypeScript compilation target to ES2020 ([#449](https://github.com/MetaMask/snaps-skunkworks/pull/449))
|
|
28
|
+
- This should not be breaking for consumers on any non-deprecated browser or Node.js version.
|
|
29
|
+
|
|
9
30
|
## [0.13.0]
|
|
10
31
|
### Changed
|
|
11
32
|
- No changes this release.
|
|
@@ -173,7 +194,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
173
194
|
- Example snaps ([#72](https://github.com/MetaMask/snaps-skunkworks/pull/72))
|
|
174
195
|
- The examples now live in their own package, [`@metamask/snap-examples`](https://npmjs.com/package/@metamask/snap-examples).
|
|
175
196
|
|
|
176
|
-
[Unreleased]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.
|
|
197
|
+
[Unreleased]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.16.0...HEAD
|
|
198
|
+
[0.16.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.15.0...v0.16.0
|
|
199
|
+
[0.15.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.14.0...v0.15.0
|
|
200
|
+
[0.14.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.13.0...v0.14.0
|
|
177
201
|
[0.13.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.12.0...v0.13.0
|
|
178
202
|
[0.12.0]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.11.1...v0.12.0
|
|
179
203
|
[0.11.1]: https://github.com/MetaMask/snaps-skunkworks/compare/v0.11.0...v0.11.1
|
package/README.md
CHANGED
|
@@ -112,7 +112,7 @@ The defaults can be overwritten using the `snap.config.json` [config file](#conf
|
|
|
112
112
|
|
|
113
113
|
### Configuration File
|
|
114
114
|
|
|
115
|
-
`snap.config.js`
|
|
115
|
+
`snap.config.js` should be placed in the project root directory. It can override cli options - the property `cliOptions` should have string keys matching command arguments. Values become argument defaults, which can still be overridden on the command line.
|
|
116
116
|
|
|
117
117
|
Example:
|
|
118
118
|
|
|
@@ -126,7 +126,7 @@ module.exports = {
|
|
|
126
126
|
};
|
|
127
127
|
```
|
|
128
128
|
|
|
129
|
-
|
|
129
|
+
If you want to customize the Browserify build process, you can provide `bundlerCustomizer` property. It's a function that takes one argument - [browserify object](https://github.com/browserify/browserify#api-example) which we use internally to bundle the snap. You can transform it in any way you want, for example adding plugins.
|
|
130
130
|
|
|
131
131
|
Example:
|
|
132
132
|
|
|
@@ -159,3 +159,4 @@ The configuration file should not be published.
|
|
|
159
159
|
- Arguments
|
|
160
160
|
- `src` must be a file path when specified
|
|
161
161
|
- `dist` and `root` must be directory paths when specified
|
|
162
|
+
- `transpilationMode` must be at least `localOnly` for TypeScript Snaps
|
|
@@ -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)({ ...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,EAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,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"]}
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.bundle = void 0;
|
|
7
7
|
const browserify_1 = __importDefault(require("browserify"));
|
|
8
|
+
const snaps_browserify_plugin_1 = __importDefault(require("@metamask/snaps-browserify-plugin"));
|
|
8
9
|
const builders_1 = require("../../builders");
|
|
9
10
|
const utils_1 = require("./utils");
|
|
10
11
|
// We need to statically import all Browserify transforms and all Babel presets
|
|
@@ -25,9 +26,18 @@ function bundle(src, dest, argv, bundlerTransform) {
|
|
|
25
26
|
const { sourceMaps: debug, transpilationMode } = argv;
|
|
26
27
|
const babelifyOptions = (0, utils_1.processDependencies)(argv);
|
|
27
28
|
return new Promise((resolve, _reject) => {
|
|
28
|
-
const bundler = (0, browserify_1.default)(src, {
|
|
29
|
+
const bundler = (0, browserify_1.default)(src, {
|
|
30
|
+
debug,
|
|
31
|
+
extensions: ['.js', '.ts'],
|
|
32
|
+
// Standalone is required to properly support Snaps using module.exports
|
|
33
|
+
standalone: '<snap>',
|
|
34
|
+
});
|
|
29
35
|
if (transpilationMode !== builders_1.TranspilationModes.none) {
|
|
30
|
-
bundler.transform(require('babelify'),
|
|
36
|
+
bundler.transform(require('babelify'), {
|
|
37
|
+
global: transpilationMode === builders_1.TranspilationModes.localAndDeps,
|
|
38
|
+
extensions: ['.js', '.ts'],
|
|
39
|
+
presets: [
|
|
40
|
+
require('@babel/preset-typescript'),
|
|
31
41
|
[
|
|
32
42
|
require('@babel/preset-env'),
|
|
33
43
|
{
|
|
@@ -36,16 +46,19 @@ function bundle(src, dest, argv, bundlerTransform) {
|
|
|
36
46
|
},
|
|
37
47
|
},
|
|
38
48
|
],
|
|
39
|
-
],
|
|
49
|
+
],
|
|
50
|
+
plugins: [
|
|
40
51
|
require('@babel/plugin-transform-runtime'),
|
|
41
52
|
require('@babel/plugin-proposal-class-properties'),
|
|
42
53
|
require('@babel/plugin-proposal-object-rest-spread'),
|
|
43
54
|
require('@babel/plugin-proposal-optional-chaining'),
|
|
44
55
|
require('@babel/plugin-proposal-nullish-coalescing-operator'),
|
|
45
|
-
]
|
|
56
|
+
],
|
|
57
|
+
...babelifyOptions,
|
|
58
|
+
});
|
|
46
59
|
}
|
|
47
|
-
bundlerTransform
|
|
48
|
-
bundler.plugin(
|
|
60
|
+
bundlerTransform?.(bundler);
|
|
61
|
+
bundler.plugin(snaps_browserify_plugin_1.default, {
|
|
49
62
|
stripComments: argv.stripComments,
|
|
50
63
|
transformHtmlComments: argv.transformHtmlComments,
|
|
51
64
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../../src/cmds/build/bundle.ts"],"names":[],"mappings":";;;;;;AAAA,4DAA0D;AAC1D,6CAAoD;AAEpD,mCAA+D;AAE/D,+EAA+E;AAC/E,mEAAmE;AACnE,mHAAmH;AAEnH;;;;;;;;;;GAUG;AACH,SAAgB,MAAM,CACpB,GAAW,EACX,IAAY,EACZ,IAAe,EACf,gBAAsD;IAEtD,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IACtD,MAAM,eAAe,GAAG,IAAA,2BAAmB,EAAC,IAAW,CAAC,CAAC;IACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;QACtC,MAAM,OAAO,GAAG,IAAA,oBAAU,EAAC,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;
|
|
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/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AAC,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\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?.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,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,IAAI,CAAC,YAAY,IAAI,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE;QACvE,OAAO,MAAM,CAAC;KACf;IACD,MAAM,KAAK,GAAa,uBAAuB,CAAC,YAAY,CAAC,CAAC;IAC9D,MAAM,GAAG,oBAAoB,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;IAC7C,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;IAChD,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC;AAVD,kDAUC;AAED;;;;GAIG;AACH,SAAgB,uBAAuB,CAAC,YAAsB;IAC5D,OAAO,YAAY,CAAC,GAAG,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,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 * @param argv\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 regex string\n * @param dependencies\n * @returns a regexp string\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 * @param dependencies\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\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,10 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
const worker_threads_1 = require("worker_threads");
|
|
4
3
|
const fs_1 = require("fs");
|
|
5
|
-
const mock_1 = require("./mock");
|
|
6
4
|
// eslint-disable-next-line import/no-unassigned-import
|
|
7
5
|
require("ses/lockdown");
|
|
6
|
+
const worker_threads_1 = require("worker_threads");
|
|
7
|
+
const mock_1 = require("./mock");
|
|
8
8
|
lockdown({
|
|
9
9
|
consoleTaming: 'unsafe',
|
|
10
10
|
errorTaming: 'unsafe',
|
|
@@ -15,12 +15,24 @@ lockdown({
|
|
|
15
15
|
if (worker_threads_1.parentPort !== null) {
|
|
16
16
|
worker_threads_1.parentPort.on('message', (message) => {
|
|
17
17
|
const { snapFilePath } = message;
|
|
18
|
-
|
|
18
|
+
const snapModule = { exports: {} };
|
|
19
|
+
new Compartment({
|
|
20
|
+
...getMockEndowments(),
|
|
21
|
+
module: snapModule,
|
|
22
|
+
exports: snapModule.exports,
|
|
23
|
+
}).evaluate((0, fs_1.readFileSync)(snapFilePath, 'utf8'));
|
|
24
|
+
if (!snapModule.exports?.onRpcRequest) {
|
|
25
|
+
console.warn("The Snap doesn't have onRpcRequest export defined");
|
|
26
|
+
}
|
|
19
27
|
setTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits
|
|
20
28
|
});
|
|
21
29
|
}
|
|
22
30
|
function getMockEndowments() {
|
|
23
31
|
const endowments = (0, mock_1.generateMockEndowments)();
|
|
24
|
-
return
|
|
32
|
+
return {
|
|
33
|
+
...endowments,
|
|
34
|
+
window: endowments,
|
|
35
|
+
self: endowments,
|
|
36
|
+
};
|
|
25
37
|
}
|
|
26
38
|
//# sourceMappingURL=eval-worker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../../../src/cmds/eval/eval-worker.ts"],"names":[],"mappings":";;AAAA,
|
|
1
|
+
{"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../../../src/cmds/eval/eval-worker.ts"],"names":[],"mappings":";;AAAA,2BAAkC;AAClC,uDAAuD;AACvD,wBAAsB;AACtB,mDAA4C;AAC5C,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,IAAI,2BAAU,KAAK,IAAI,EAAE;IACvB,2BAAU,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAiC,EAAE,EAAE;QAC7D,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;QAEjC,MAAM,UAAU,GAAsB,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;QAEtD,IAAI,WAAW,CAAC;YACd,GAAG,iBAAiB,EAAE;YACtB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,UAAU,CAAC,OAAO;SAC5B,CAAC,CAAC,QAAQ,CAAC,IAAA,iBAAY,EAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC;QAEhD,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,YAAY,EAAE;YACrC,OAAO,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAC;SACnE;QAED,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,8BAA8B;IACzE,CAAC,CAAC,CAAC;CACJ;AAED,SAAS,iBAAiB;IACxB,MAAM,UAAU,GAAG,IAAA,6BAAsB,GAAE,CAAC;IAC5C,OAAO;QACL,GAAG,UAAU;QACb,MAAM,EAAE,UAAU;QAClB,IAAI,EAAE,UAAU;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import { readFileSync } from 'fs';\n// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\nimport { parentPort } from 'worker_threads';\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\nif (parentPort !== null) {\n parentPort.on('message', (message: { snapFilePath: string }) => {\n const { snapFilePath } = message;\n\n const snapModule: { exports?: any } = { exports: {} };\n\n new Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n }).evaluate(readFileSync(snapFilePath, 'utf8'));\n\n if (!snapModule.exports?.onRpcRequest) {\n console.warn(\"The Snap doesn't have onRpcRequest export defined\");\n }\n\n setTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n });\n}\n\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n"]}
|
package/dist/cmds/eval/mock.js
CHANGED
|
@@ -11,11 +11,10 @@ const NETWORK_APIS = ['fetch', 'WebSocket'];
|
|
|
11
11
|
exports.ALL_APIS = [...snap_controllers_1.DEFAULT_ENDOWMENTS, ...NETWORK_APIS];
|
|
12
12
|
function getMockSnapProvider() {
|
|
13
13
|
const mockProvider = new events_1.default();
|
|
14
|
-
mockProvider.registerRpcMessageHandler = () => true;
|
|
15
14
|
mockProvider.request = async () => true;
|
|
16
15
|
return mockProvider;
|
|
17
16
|
}
|
|
18
|
-
const isConstructor = (value) =>
|
|
17
|
+
const isConstructor = (value) => Boolean(typeof value?.prototype?.constructor?.name === 'string');
|
|
19
18
|
exports.isConstructor = isConstructor;
|
|
20
19
|
const mockFunction = () => true;
|
|
21
20
|
class MockClass {
|
|
@@ -44,7 +43,7 @@ const generateMockEndowment = (key) => {
|
|
|
44
43
|
return globalValue;
|
|
45
44
|
}
|
|
46
45
|
// Fall back to mockWindow for certain APIs not exposed in global in Node.JS
|
|
47
|
-
const globalOrMocked = globalValue
|
|
46
|
+
const globalOrMocked = globalValue ?? mockWindow[key];
|
|
48
47
|
const type = typeof globalOrMocked;
|
|
49
48
|
const isFunction = type === 'function';
|
|
50
49
|
if (isFunction && (0, exports.isConstructor)(globalOrMocked)) {
|
|
@@ -57,7 +56,7 @@ const generateMockEndowment = (key) => {
|
|
|
57
56
|
return globalOrMocked;
|
|
58
57
|
};
|
|
59
58
|
const generateMockEndowments = () => {
|
|
60
|
-
return exports.ALL_APIS.reduce((acc, cur) => (
|
|
59
|
+
return exports.ALL_APIS.reduce((acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }), { wallet: getMockSnapProvider() });
|
|
61
60
|
};
|
|
62
61
|
exports.generateMockEndowments = generateMockEndowments;
|
|
63
62
|
//# 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;AAO3E,SAAS,mBAAmB;IAC1B,MAAM,YAAY,GAAG,IAAI,gBAAY,EAA+B,CAAC;IACrE,YAAY,CAAC,
|
|
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;AAO3E,SAAS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,GAAG,OAAO,cAAc,CAAC;IACnC,MAAM,UAAU,GAAG,IAAI,KAAK,UAAU,CAAC;IACvC,IAAI,UAAU,IAAI,IAAA,qBAAa,EAAC,cAAc,CAAC,EAAE;QAC/C,OAAO,iBAAiB,CAAC,cAAc,CAAC,CAAC;KAC1C;SAAM,IAAI,UAAU,IAAI,CAAC,cAAc,EAAE;QACxC,qCAAqC;QACrC,OAAO,YAAY,CAAC;KACrB;IACD,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAEK,MAAM,sBAAsB,GAAG,GAAG,EAAE;IACzC,OAAO,gBAAQ,CAAC,MAAM,CACpB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,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 registerRpcMessageHandler: () => any;\n request: () => Promise<any>;\n};\n\nfunction getMockSnapProvider(): MockSnapProvider {\n const mockProvider = new EventEmitter() as Partial<MockSnapProvider>;\n mockProvider.request = async () => true;\n return mockProvider as MockSnapProvider;\n}\n\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\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\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\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\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/index.d.ts
CHANGED
package/dist/cmds/init/index.js
CHANGED
|
@@ -8,7 +8,11 @@ const initHandler_1 = require("./initHandler");
|
|
|
8
8
|
async function init(argv) {
|
|
9
9
|
console.log();
|
|
10
10
|
const newArgs = await (0, initHandler_1.initHandler)(argv);
|
|
11
|
-
await (0, buildHandler_1.build)(
|
|
11
|
+
await (0, buildHandler_1.build)({
|
|
12
|
+
...newArgs,
|
|
13
|
+
manifest: false,
|
|
14
|
+
eval: true,
|
|
15
|
+
});
|
|
12
16
|
await (0, initHandler_1.updateManifestShasum)();
|
|
13
17
|
console.log('\nSnap project successfully initiated!');
|
|
14
18
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/init/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,wDAA8C;AAC9C,+CAAkE;AAelE,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;AAelE,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,EAAC;QACV,GAAG,OAAO;QACV,QAAQ,EAAE,KAAK;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IAEH,MAAM,IAAA,kCAAoB,GAAE,CAAC;IAE7B,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;AACxD,CAAC;AA1BD,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,CAAC;IACjD,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;CACzC,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { build } from '../build/buildHandler';\nimport { initHandler, updateManifestShasum } from './initHandler';\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 },\n handler: (argv: YargsArgs) => init(argv),\n};\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"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
{
|
|
2
2
|
"html": "<!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 const response = 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",
|
|
3
|
-
"source": "
|
|
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
|
}
|
|
@@ -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;AAE5B,uCAMqB;AACrB,iEAAkE;AAClE,8EAA4C;AAC5C,2CAIqB;AAEd,KAAK,UAAU,WAAW,CAAC,IAAe;IAC/C,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;IAE5C,MAAM,WAAW,GAAG,MAAM,IAAA,4BAAgB,GAAE,CAAC;IAE7C,MAAM,IAAA,mCAAuB,GAAE,CAAC;IAEhC,OAAO,CAAC,GAAG,CAAC,qBAAqB,mCAAgB,CAAC,QAAQ,QAAQ,CAAC,CAAC;IAEpE,MAAM,CAAC,YAAY,EAAE,QAAQ,CAAC,GAAG,MAAM,IAAA,6BAAiB,EAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAE5E,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;SAClC,IAAI,EAAE;SACN,MAAM,CAAC,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE;QACtB,MAAM,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAA4B,CAAC,CAAC;QACrD,OAAO,MAAM,CAAC;IAChB,CAAC,EAAE,EAAe,CAAC,CAAC;IAEtB,IAAI;QACF,MAAM,aAAE,CAAC,SAAS,CAChB,mCAAgB,CAAC,QAAQ,EACzB,GAAG,IAAI,CAAC,SAAS,CAAC,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAC7C,CAAC;KACH;I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S,CAAC,mBAAW,EAAE,iBAAiB,CAAC,CAAC;QACnD,OAAO,CAAC,GAAG,CAAC,gBAAgB,mBAAW,eAAe,CAAC,CAAC;KACzD;IAAC,OAAO,GAAG,EAAE;QACZ,IAAA,gBAAQ,EAAC,gCAAgC,mBAAW,IAAI,EAAE,GAAG,CAAC,CAAC;QAC/D,MAAM,GAAG,CAAC;KACX;IAED,IAAA,mBAAW,GAAE,CAAC;IACd,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,EAAE,CAAC;AACjC,CAAC;AA5ED,kCA4EC;AAED;;;GAGG;AACI,KAAK,UAAU,oBAAoB;IACxC,MAAM,QAAQ,GAAG,CAAC,MAAM,IAAA,oBAAY,EAClC,mCAAgB,CAAC,QAAQ,CAC1B,CAAiB,CAAC;IAEnB,MAAM,cAAc,GAAG,MAAM,aAAE,CAAC,QAAQ,CACtC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EACrC,MAAM,CACP,CAAC;IAEF,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG,IAAA,sCAAmB,EAAC,cAAc,CAAC,CAAC;IAC7D,MAAM,aAAE,CAAC,SAAS,CAChB,mCAAgB,CAAC,QAAQ,EACzB,IAAI,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 template from './init-template.json';\nimport {\n asyncPackageInit,\n buildSnapManifest,\n prepareWorkingDirectory,\n} from './initUtils';\n\nexport async function initHandler(argv: YargsArgs) {\n console.log(`MetaMask Snaps: Initialize\\n`);\n\n const packageJson = await asyncPackageInit();\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 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 try {\n if (pathUtils.basename(src) !== src) {\n await mkdirp(pathUtils.dirname(src));\n }\n\n await fs.writeFile(src, template.source);\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('index.html', template.html);\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 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 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', { ...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,EAAE,EAAE,GAAG,kBAAQ,CAAC,aAAa,EAAE,KAAK,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,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,15 +1,4 @@
|
|
|
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
|
-
};
|
|
13
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
3
|
exports.getWritableManifest = exports.manifestHandler = void 0;
|
|
15
4
|
const fs_1 = require("fs");
|
|
@@ -33,12 +22,12 @@ const ManifestSortOrder = {
|
|
|
33
22
|
* @param argv - The Yargs `argv` object.
|
|
34
23
|
*/
|
|
35
24
|
async function manifestHandler({ writeManifest, }) {
|
|
36
|
-
var _a, _b, _c;
|
|
37
25
|
let didUpdate = false;
|
|
38
26
|
let hasWarnings = false;
|
|
39
27
|
const unvalidatedManifest = await readSnapJsonFile(utils_1.NpmSnapFileNames.Manifest);
|
|
40
28
|
const iconPath = unvalidatedManifest && typeof unvalidatedManifest === 'object'
|
|
41
|
-
?
|
|
29
|
+
? unvalidatedManifest.source?.location?.npm
|
|
30
|
+
?.iconPath
|
|
42
31
|
: undefined;
|
|
43
32
|
const snapFiles = {
|
|
44
33
|
manifest: unvalidatedManifest,
|
|
@@ -61,7 +50,7 @@ async function manifestHandler({ writeManifest, }) {
|
|
|
61
50
|
for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {
|
|
62
51
|
manifest = fixManifest(partiallyValidatedFiles, error);
|
|
63
52
|
try {
|
|
64
|
-
(0, utils_1.validateNpmSnapManifest)(
|
|
53
|
+
(0, utils_1.validateNpmSnapManifest)({ ...partiallyValidatedFiles, manifest }, errorPrefix);
|
|
65
54
|
isInvalid = false;
|
|
66
55
|
}
|
|
67
56
|
catch (nextValidationError) {
|
|
@@ -142,10 +131,10 @@ async function readSnapJsonFile(snapJsonFileName) {
|
|
|
142
131
|
* @returns The contents of the bundle file, if any.
|
|
143
132
|
*/
|
|
144
133
|
async function getSnapSourceCode(manifest) {
|
|
145
|
-
var _a, _b, _c;
|
|
146
134
|
if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {
|
|
147
135
|
/* istanbul ignore next: optional chaining */
|
|
148
|
-
const sourceFilePath =
|
|
136
|
+
const sourceFilePath = manifest.source?.location
|
|
137
|
+
?.npm?.filePath;
|
|
149
138
|
try {
|
|
150
139
|
return sourceFilePath
|
|
151
140
|
? await fs_1.promises.readFile(sourceFilePath, 'utf8')
|
|
@@ -200,8 +189,8 @@ function fixManifest(snapFiles, error) {
|
|
|
200
189
|
* @returns The disk-ready manifest.
|
|
201
190
|
*/
|
|
202
191
|
function getWritableManifest(manifest) {
|
|
203
|
-
const { repository
|
|
204
|
-
return Object.keys(repository ?
|
|
192
|
+
const { repository, ...remaining } = manifest;
|
|
193
|
+
return Object.keys(repository ? { ...remaining, repository } : remaining)
|
|
205
194
|
.sort((a, b) => ManifestSortOrder[a] - ManifestSortOrder[b])
|
|
206
195
|
.reduce((outManifest, key) => {
|
|
207
196
|
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;;;;;;GAMG;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,CAAC,MAAA,MAAA,MAAC,mBAA6C,CAAC,MAAM,0CAAE,QAAQ,0CAAE,GAAG,0CAChE,QAAQ;QACd,CAAC,CAAC,SAAS,CAAC;IAEhB,MAAM,SAAS,GAAyB;QACtC,QAAQ,EAAE,mBAAmB;QAC7B,WAAW,EAAE,MAAM,gBAAgB,CAAC,wBAAgB,CAAC,WAAW,CAAC;QACjE,UAAU,EAAE,MAAM,iBAAiB,CAAC,mBAAmB,CAAC;QACxD,OAAO,EAAE,QA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3B,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 */\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 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,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;GAMG;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,m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,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 */\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 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"]}
|
|
@@ -40,7 +40,7 @@ async function watch(argv) {
|
|
|
40
40
|
await (0, manifestHandler_1.manifestHandler)(argv);
|
|
41
41
|
}
|
|
42
42
|
if (shouldEval) {
|
|
43
|
-
await (0, evalHandler_1.snapEval)(
|
|
43
|
+
await (0, evalHandler_1.snapEval)({ ...argv, bundle: outfilePath });
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
46
|
catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|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cesContent":["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';\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 { dist, eval: shouldEval, manifest, outfileName, src } = 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', buildSnap)\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/dist/utils/misc.js
CHANGED
|
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.trimPathString = exports.writeError = exports.logWarning = exports.logError = exports.sanitizeInputs = exports.booleanStringToBoolean = exports.setSnapGlobals = exports.CONFIG_FILE = exports.permRequestKeys = exports.deepClone = void 0;
|
|
7
7
|
const fs_1 = require("fs");
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const utils_1 = require("@metamask/utils");
|
|
9
10
|
const rfdc_1 = __importDefault(require("rfdc"));
|
|
10
11
|
exports.deepClone = (0, rfdc_1.default)({ proto: false, circles: false });
|
|
11
12
|
exports.permRequestKeys = [
|
|
@@ -42,10 +43,10 @@ function setSnapGlobals(argv) {
|
|
|
42
43
|
else {
|
|
43
44
|
global.snaps.isWatching = false;
|
|
44
45
|
}
|
|
45
|
-
if (
|
|
46
|
+
if ((0, utils_1.hasProperty)(argv, 'verboseErrors')) {
|
|
46
47
|
global.snaps.verboseErrors = booleanStringToBoolean(argv.verboseErrors);
|
|
47
48
|
}
|
|
48
|
-
if (
|
|
49
|
+
if ((0, utils_1.hasProperty)(argv, 'suppressWarnings')) {
|
|
49
50
|
global.snaps.suppressWarnings = booleanStringToBoolean(argv.suppressWarnings);
|
|
50
51
|
}
|
|
51
52
|
}
|
package/dist/utils/misc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"misc.js","sourceRoot":"","sources":["../../src/utils/misc.ts"],"names":[],"mappings":";;;;;;AAAA,2BAA4C;AAC5C,gDAAwB;AACxB,gDAAwB;AAGX,QAAA,SAAS,GAAG,IAAA,cAAI,EAAC,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;AAEnD,QAAA,eAAe,GAAG;IAC7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AED,qCAAqC;IACrC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE;QAC5B,0EAA0E;QAC1E,uEAAuE;QACvE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;KACjB;AACH,CAAC;AA1BD,gCA0BC;AAED;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,UAAkB;IAC/C,OAAO,UAAU,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC;AACnD,CAAC;AAFD,wCAEC","sourcesContent":["import { promises as filesystem } from 'fs';\nimport path from 'path';\nimport { hasProperty } from '@metamask/utils';\nimport rfdc from 'rfdc';\nimport { Arguments } from 'yargs';\n\nexport const deepClone = rfdc({ proto: false, circles: false });\n\nexport const permRequestKeys = [\n '@context',\n 'id',\n 'parentCapability',\n 'invoker',\n 'date',\n 'caveats',\n 'proof',\n];\n\nexport const CONFIG_FILE = 'snap.config.js';\n\n// CLI arguments whose values are file paths\nconst pathArguments = new Set([\n 'src',\n 's',\n 'dist',\n 'd',\n 'bundle',\n 'b',\n 'root',\n 'r',\n]);\n\n/**\n * Sets global variable snaps which tracks user settings:\n * watch mode activation, verbose errors messages, and whether to suppress warnings.\n *\n * @param argv - arguments as an object generated by yargs\n */\nexport function setSnapGlobals(argv: Arguments) {\n if (['w', 'watch'].includes(argv._[0] as string)) {\n global.snaps.isWatching = true;\n } else {\n global.snaps.isWatching = false;\n }\n\n if (hasProperty(argv, 'verboseErrors')) {\n global.snaps.verboseErrors = booleanStringToBoolean(argv.verboseErrors);\n }\n\n if (hasProperty(argv, 'suppressWarnings')) {\n global.snaps.suppressWarnings = booleanStringToBoolean(\n argv.suppressWarnings,\n );\n }\n}\n\n/**\n * Attempts to convert a string to a boolean and throws if the value is invalid.\n *\n * @param value - The value to convert to a boolean.\n * @return `true` if the value is the string `\"true\"`, `false` if it is the\n * string `\"false\"`, the value if it is already a boolean, or an error\n * otherwise.\n */\nexport function booleanStringToBoolean(value: unknown): boolean {\n if (typeof value === 'boolean') {\n return value;\n } else if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n }\n\n throw new Error(\n `Expected a boolean or the strings \"true\" or \"false\". Received: \"${value}\"`,\n );\n}\n\n/**\n * Sanitizes inputs. Currently normalizes \"./\" paths to \".\".\n * Yargs handles other path normalization as specified in builders.\n *\n * @param argv - arguments as an object generated by yargs\n */\nexport function sanitizeInputs(argv: Arguments) {\n Object.keys(argv).forEach((key) => {\n if (typeof argv[key] === 'string') {\n // Node's path.normalize() does not do this\n if (argv[key] === './') {\n argv[key] = '.';\n }\n\n if (pathArguments.has(key)) {\n argv[key] = path.normalize(argv[key] as string);\n }\n }\n });\n}\n\n/**\n * Logs an error message to console. Logs original error if it exists and\n * the verboseErrors global is true.\n *\n * @param msg - The error message\n * @param err - The original error\n */\nexport function logError(msg: string, err?: Error): void {\n console.error(msg);\n if (err && global.snaps.verboseErrors) {\n console.error(err);\n }\n}\n\n/**\n * Logs a warning message to console.\n *\n * @param msg - The warning message\n */\nexport function logWarning(msg: string, error?: Error): void {\n if (msg && !global.snaps.suppressWarnings) {\n console.warn(msg);\n if (error && global.snaps.verboseErrors) {\n console.error(error);\n }\n }\n}\n\n/**\n * Logs an error, attempts to unlink the destination file, and exits.\n *\n * @param prefix - The message prefix\n * @param msg - The error message\n * @param err - The original error\n * @param destFilePath - The output file path\n */\nexport async function writeError(\n prefix: string,\n msg: string,\n err: Error,\n destFilePath?: string,\n): Promise<void> {\n let processedPrefix = prefix;\n if (!prefix.endsWith(' ')) {\n processedPrefix += ' ';\n }\n\n logError(processedPrefix + msg, err);\n try {\n if (destFilePath) {\n await filesystem.unlink(destFilePath);\n }\n } catch (unlinkError) {\n logError(`${processedPrefix}Failed to unlink mangled file.`, unlinkError);\n }\n\n // unless the watcher is active, exit\n if (!global.snaps.isWatching) {\n // TODO(ritave): Remove process exit and change into collapse of functions\n // https://github.com/MetaMask/snaps-skunkworks/issues/81\n process.exit(1);\n }\n}\n\n/**\n * Trims leading and trailing periods \".\" and forward slashes \"/\" from the\n * given path string.\n *\n * @param pathString - The path string to trim.\n * @returns - The trimmed path string.\n */\nexport function trimPathString(pathString: string): string {\n return pathString.replace(/^[./]+|[./]+$/gu, '');\n}\n"]}
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.applyConfig = exports.loadConfig = void 0;
|
|
7
7
|
const path_1 = __importDefault(require("path"));
|
|
8
|
+
const utils_1 = require("@metamask/utils");
|
|
8
9
|
const yargs_parser_1 = __importDefault(require("yargs-parser"));
|
|
9
10
|
const builders_1 = __importDefault(require("../builders"));
|
|
10
11
|
const misc_1 = require("./misc");
|
|
@@ -66,12 +67,11 @@ function applyConfig(snapConfig, processArgv, yargsArgv, yargsInstance) {
|
|
|
66
67
|
delete parsedProcessArgv._; // irrelevant yargs parser artifact
|
|
67
68
|
const commandOptions = new Set(Object.keys(options));
|
|
68
69
|
const shouldSetArg = (key) => {
|
|
69
|
-
return
|
|
70
|
-
!Object.prototype.hasOwnProperty.call(parsedProcessArgv, key));
|
|
70
|
+
return commandOptions.has(key) && !(0, utils_1.hasProperty)(parsedProcessArgv, key);
|
|
71
71
|
};
|
|
72
72
|
const cfg = snapConfig.cliOptions || {};
|
|
73
73
|
for (const key of Object.keys(cfg)) {
|
|
74
|
-
if (
|
|
74
|
+
if ((0, utils_1.hasProperty)(builders_1.default, key)) {
|
|
75
75
|
if (shouldSetArg(key)) {
|
|
76
76
|
yargsArgv[key] = cfg[key];
|
|
77
77
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snap-config.js","sourceRoot":"","sources":["../../src/utils/snap-config.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;
|
|
1
|
+
{"version":3,"file":"snap-config.js","sourceRoot":"","sources":["../../src/utils/snap-config.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AACxB,2CAA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ACrB,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,GACpC,aACD,CAAC,UAAU,EAGX,CAAC;IAEF,MAAM,iBAAiB,GAAG,IAAA,sBAAU,EAAC,WAAW,EAAE;QAChD,KAAK,EAAE,OAAO;KACf,CAA4B,CAAC;IAC9B,OAAO,iBAAiB,CAAC,CAAC,CAAC,CAAC,mCAAmC;IAE/D,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAErD,MAAM,YAAY,GAAG,CAAC,GAAW,EAAW,EAAE;QAC5C,OAAO,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAA,mBAAW,EAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC;IACzE,CAAC,CAAC;IAEF,MAAM,GAAG,GAA4B,UAAU,CAAC,UAAU,IAAI,EAAE,CAAC;IACjE,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAClC,IAAI,IAAA,mBAAW,EAAC,kBAAQ,EAAE,GAAG,CAAC,EAAE;YAC9B,IAAI,YAAY,CAAC,GAAG,CAAC,EAAE;gBACrB,SAAS,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;aAC3B;SACF;aAAM;YACL,IAAA,eAAQ,EACN,4DAA4D,GAAG,qBAAqB,kBAAW,uCAAuC,CACvI,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACjB;KACF;AACH,CAAC;AAhDD,kCAgDC","sourcesContent":["import path from 'path';\nimport { hasProperty } from '@metamask/utils';\nimport type browserify from 'browserify';\nimport { Arguments } from 'yargs';\nimport yargsParse from 'yargs-parser';\nimport yargs from 'yargs/yargs';\nimport builders from '../builders';\nimport { CONFIG_FILE, logError } from './misc';\nimport { isSnapConfig } from './snap-config.__GENERATED__';\n\n/** @see {isSnapConfig} ts-auto-guard:type-guard */\nexport type SnapConfig = {\n cliOptions?: Record<string, unknown>;\n bundlerCustomizer?: (bundler: browserify.BrowserifyObject) => void;\n};\n\nlet snapConfigCache: SnapConfig | undefined;\n\nexport function loadConfig(cached = true): SnapConfig {\n if (snapConfigCache !== undefined && cached === true) {\n return snapConfigCache;\n }\n\n let config: any;\n try {\n // eslint-disable-next-line node/global-require, import/no-dynamic-require, @typescript-eslint/no-require-imports\n config = require(path.resolve(process.cwd(), CONFIG_FILE));\n } catch (err: any) {\n if (err.code === 'MODULE_NOT_FOUND') {\n snapConfigCache = {};\n return snapConfigCache;\n }\n logError(`Error during parsing of ${CONFIG_FILE}`, err);\n return process.exit(1);\n }\n\n if (!isSnapConfig(config)) {\n logError(\n `Can't validate ${CONFIG_FILE}. Ensure it's a proper javascript file and abides with the structure of a snap configuration file`,\n );\n return process.exit(1);\n }\n snapConfigCache = config;\n return config;\n}\n\n// Note that the below function is necessary because yarg's .config() function\n// leaves much to be desired.\n//\n// In particular, it will set all properties included in the config file\n// regardless of the command, which fails during validation.\n\n/**\n * Attempts to read configuration options for package.json and the config file,\n * and apply them to argv if they weren't already set.\n *\n * Arguments are only set per the snap-cli config file if they were not specified\n * on the command line.\n */\nexport function applyConfig(\n snapConfig: SnapConfig,\n processArgv: string[],\n yargsArgv: Arguments,\n yargsInstance: typeof yargs,\n): void {\n // Instances of yargs has a number of undocumented functions, including\n // getOptions. This function returns an object with properties \"key\" and\n // \"alias\", which specify the options associated with the current command and\n // their aliases, respectively.\n //\n // We leverage this to ensure that the config is only applied to args that are\n // valid for the current command, and that weren't specified by the user on\n // the command line.\n //\n // If we set args that aren't valid for the current command, yargs will error\n // during validation.\n const { alias: aliases, key: options } = (\n yargsInstance as any\n ).getOptions() as {\n alias: Record<string, string[]>;\n key: Record<string, unknown>;\n };\n\n const parsedProcessArgv = yargsParse(processArgv, {\n alias: aliases,\n }) as Record<string, unknown>;\n delete parsedProcessArgv._; // irrelevant yargs parser artifact\n\n const commandOptions = new Set(Object.keys(options));\n\n const shouldSetArg = (key: string): boolean => {\n return commandOptions.has(key) && !hasProperty(parsedProcessArgv, key);\n };\n\n const cfg: Record<string, unknown> = snapConfig.cliOptions || {};\n for (const key of Object.keys(cfg)) {\n if (hasProperty(builders, key)) {\n if (shouldSetArg(key)) {\n yargsArgv[key] = cfg[key];\n }\n } else {\n logError(\n `Error: Encountered unrecognized config property \"options.${key}\" in config file \"${CONFIG_FILE}\". Remove the property and try again.`,\n );\n process.exit(1);\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "A CLI for developing MetaMask Snaps.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"build:post-tsc": "yarn build:chmod && yarn build:readme",
|
|
27
27
|
"build:clean": "yarn clean && yarn build",
|
|
28
28
|
"build:watch": "tsc-watch --onSuccess 'yarn build:chmod'",
|
|
29
|
-
"clean": "rimraf dist/* src/**/*__GENERATED__*",
|
|
29
|
+
"clean": "rimraf '*.tsbuildinfo' 'dist/*' 'src/**/*__GENERATED__*'",
|
|
30
30
|
"test": "yarn build:init-template && jest",
|
|
31
31
|
"posttest": "jest-it-up",
|
|
32
32
|
"test:watch": "yarn test --watch",
|
|
@@ -46,13 +46,13 @@
|
|
|
46
46
|
"@babel/plugin-proposal-optional-chaining": "^7.16.7",
|
|
47
47
|
"@babel/plugin-transform-runtime": "^7.16.7",
|
|
48
48
|
"@babel/preset-env": "^7.16.7",
|
|
49
|
-
"@
|
|
50
|
-
"@metamask/snap-controllers": "^0.
|
|
51
|
-
"@metamask/snaps-browserify-plugin": "^0.
|
|
49
|
+
"@babel/preset-typescript": "^7.16.7",
|
|
50
|
+
"@metamask/snap-controllers": "^0.16.0",
|
|
51
|
+
"@metamask/snaps-browserify-plugin": "^0.16.0",
|
|
52
|
+
"@metamask/utils": "^2.0.0",
|
|
52
53
|
"babelify": "^10.0.0",
|
|
53
54
|
"browserify": "^17.0.0",
|
|
54
55
|
"chokidar": "^3.0.2",
|
|
55
|
-
"fast-deep-equal": "^2.0.1",
|
|
56
56
|
"init-package-json": "^1.10.3",
|
|
57
57
|
"is-url": "^1.2.4",
|
|
58
58
|
"mkdirp": "^1.0.4",
|
|
@@ -64,8 +64,8 @@
|
|
|
64
64
|
"yargs-parser": "^20.2.2"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
|
-
"@lavamoat/allow-scripts": "^
|
|
68
|
-
"@metamask/auto-changelog": "^2.
|
|
67
|
+
"@lavamoat/allow-scripts": "^2.0.3",
|
|
68
|
+
"@metamask/auto-changelog": "^2.6.0",
|
|
69
69
|
"@metamask/eslint-config": "^8.0.0",
|
|
70
70
|
"@metamask/eslint-config-jest": "^8.0.0",
|
|
71
71
|
"@metamask/eslint-config-nodejs": "^8.0.0",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"@types/browserify": "^12.0.36",
|
|
74
74
|
"@types/init-package-json": "^1.10.0",
|
|
75
75
|
"@types/is-url": "^1.2.28",
|
|
76
|
-
"@types/jest": "^
|
|
76
|
+
"@types/jest": "^27.5.1",
|
|
77
77
|
"@types/mkdirp": "^1.0.2",
|
|
78
78
|
"@types/node": "^14.14.25",
|
|
79
79
|
"@types/rimraf": "^3.0.0",
|
|
@@ -89,13 +89,14 @@
|
|
|
89
89
|
"eslint-plugin-node": "^11.1.0",
|
|
90
90
|
"eslint-plugin-prettier": "^3.4.0",
|
|
91
91
|
"execa": "^5.1.1",
|
|
92
|
-
"jest": "^
|
|
92
|
+
"jest": "^27.5.1",
|
|
93
93
|
"jest-it-up": "^2.0.0",
|
|
94
94
|
"patch-package": "^6.4.7",
|
|
95
95
|
"prettier": "^2.3.2",
|
|
96
|
+
"prettier-plugin-packagejson": "^2.2.11",
|
|
96
97
|
"rimraf": "^3.0.2",
|
|
97
98
|
"ts-auto-guard": "^2.3.0",
|
|
98
|
-
"ts-jest": "^
|
|
99
|
+
"ts-jest": "^27.1.5",
|
|
99
100
|
"ts-node": "^9.1.1",
|
|
100
101
|
"tsc-watch": "^4.5.0",
|
|
101
102
|
"typescript": "^4.4.0"
|