@metamask/snaps-cli 0.8.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -1
- package/README.md +62 -20
- package/dist/builders.d.ts +16 -8
- package/dist/builders.js +66 -41
- package/dist/builders.js.map +1 -1
- package/dist/cli.js +3 -2
- package/dist/cli.js.map +1 -1
- package/dist/cmds/build/buildHandler.js +1 -1
- package/dist/cmds/build/buildHandler.js.map +1 -1
- package/dist/cmds/build/bundle.d.ts +9 -7
- package/dist/cmds/build/bundle.js +35 -31
- package/dist/cmds/build/bundle.js.map +1 -1
- package/dist/cmds/build/index.js +10 -4
- package/dist/cmds/build/index.js.map +1 -1
- package/dist/cmds/build/utils.d.ts +59 -0
- package/dist/cmds/build/utils.js +148 -0
- package/dist/cmds/build/utils.js.map +1 -0
- package/dist/cmds/init/initHandler.d.ts +2 -0
- package/dist/cmds/init/initHandler.js +6 -1
- package/dist/cmds/init/initHandler.js.map +1 -1
- package/dist/cmds/watch/index.js +11 -1
- package/dist/cmds/watch/index.js.map +1 -1
- package/dist/cmds/watch/watchHandler.js +32 -19
- package/dist/cmds/watch/watchHandler.js.map +1 -1
- package/dist/utils/misc.d.ts +10 -1
- package/dist/utils/misc.js +25 -4
- package/dist/utils/misc.js.map +1 -1
- package/dist/utils/snap-config.__GENERATED__.d.ts +2 -0
- package/dist/utils/snap-config.__GENERATED__.js +18 -0
- package/dist/utils/snap-config.__GENERATED__.js.map +1 -0
- package/dist/utils/snap-config.d.ts +8 -1
- package/dist/utils/snap-config.js +39 -32
- package/dist/utils/snap-config.js.map +1 -1
- package/package.json +11 -8
- package/dist/cmds/build/bundleUtils.d.ts +0 -42
- package/dist/cmds/build/bundleUtils.js +0 -95
- package/dist/cmds/build/bundleUtils.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/build/index.ts"],"names":[],"m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ent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { build } from './buildHandler';\nimport { processInvalidTranspilation } from './utils';\n\nexport = {\n command: ['build', 'b'],\n desc: 'Build Snap from source',\n builder: (yarg: yargs.Argv) => {\n yarg\n .option('dist', builders.dist)\n .option('eval', builders.eval)\n .option('manifest', builders.manifest)\n .option('outfileName', builders.outfileName)\n .option('sourceMaps', builders.sourceMaps)\n .option('src', builders.src)\n .option('stripComments', builders.stripComments)\n .option('transpilationMode', builders.transpilationMode)\n .option('depsToTranspile', builders.depsToTranspile)\n .option('transformHtmlComments', builders.transformHtmlComments)\n .option('writeManifest', builders.writeManifest)\n .implies('writeManifest', 'manifest')\n .implies('depsToTranspile', 'transpilationMode')\n .middleware((argv) => processInvalidTranspilation(argv as any));\n },\n handler: (argv: YargsArgs) => build(argv),\n};\n"]}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { Option, YargsArgs } from '../../types/yargs';
|
|
3
|
+
declare type WriteBundleFileArgs = {
|
|
4
|
+
bundleError: Error;
|
|
5
|
+
bundleBuffer: Buffer;
|
|
6
|
+
src: string;
|
|
7
|
+
dest: string;
|
|
8
|
+
resolve: (value: boolean) => void;
|
|
9
|
+
argv: YargsArgs;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Performs postprocessing on the bundle contents and writes them to disk.
|
|
13
|
+
* Intended to be used in the callback passed to the Browserify `.bundle()`
|
|
14
|
+
* call.
|
|
15
|
+
*
|
|
16
|
+
* @param options - Options bag.
|
|
17
|
+
* @param options.bundleError - Any error received from Browserify.
|
|
18
|
+
* @param options.bundleBuffer - The {@link Buffer} with the bundle contents
|
|
19
|
+
* from Browserify.
|
|
20
|
+
* @param options.src - The source file path.
|
|
21
|
+
* @param options.dest - The destination file path.
|
|
22
|
+
* @param options.resolve - A {@link Promise} resolution function, so that we
|
|
23
|
+
* can use promises and `async`/`await` even though Browserify uses callbacks.
|
|
24
|
+
* @param options.argv - The Yargs `argv` object.
|
|
25
|
+
*/
|
|
26
|
+
export declare function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve, argv, }: WriteBundleFileArgs): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* Postprocesses a JavaScript bundle string such that it can be evaluated in SES.
|
|
29
|
+
* Currently:
|
|
30
|
+
* - converts certain dot notation to string notation (for indexing)
|
|
31
|
+
* - makes all direct calls to eval indirect
|
|
32
|
+
* - wraps original bundle in anonymous function
|
|
33
|
+
* - handles certain Babel-related edge cases
|
|
34
|
+
*
|
|
35
|
+
* @param bundleString - The bundle string
|
|
36
|
+
* @param options - post process options
|
|
37
|
+
* @param options.stripComments
|
|
38
|
+
* @returns - The postprocessed bundle string
|
|
39
|
+
*/
|
|
40
|
+
export declare function postProcess(bundleString: string | null, options?: Partial<Option>): string | null;
|
|
41
|
+
/**
|
|
42
|
+
* Processes dependencies and updates argv with an options object
|
|
43
|
+
* @param argv
|
|
44
|
+
*/
|
|
45
|
+
export declare function processDependencies(argv: YargsArgs): Record<string, any>;
|
|
46
|
+
/**
|
|
47
|
+
* Processes a string of space delimited dependencies into one regex string
|
|
48
|
+
* @param dependencies
|
|
49
|
+
* @returns a regexp string
|
|
50
|
+
*/
|
|
51
|
+
export declare function getDependencyRegExp(dependencies: string[]): RegExp | null;
|
|
52
|
+
/**
|
|
53
|
+
* Helper function remove any leading and trailing slashes from dependency list
|
|
54
|
+
* @param dependencies
|
|
55
|
+
* @returns an array of sanitized paths
|
|
56
|
+
*/
|
|
57
|
+
export declare function sanitizeDependencyPaths(dependencies: string[]): string[];
|
|
58
|
+
export declare function processInvalidTranspilation(argv: YargsArgs): void;
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.processInvalidTranspilation = exports.sanitizeDependencyPaths = exports.getDependencyRegExp = exports.processDependencies = exports.postProcess = exports.writeBundleFile = void 0;
|
|
7
|
+
const fs_1 = require("fs");
|
|
8
|
+
const strip_comments_1 = __importDefault(require("@nodefactory/strip-comments"));
|
|
9
|
+
const misc_1 = require("../../utils/misc");
|
|
10
|
+
const builders_1 = require("../../builders");
|
|
11
|
+
/**
|
|
12
|
+
* Performs postprocessing on the bundle contents and writes them to disk.
|
|
13
|
+
* Intended to be used in the callback passed to the Browserify `.bundle()`
|
|
14
|
+
* call.
|
|
15
|
+
*
|
|
16
|
+
* @param options - Options bag.
|
|
17
|
+
* @param options.bundleError - Any error received from Browserify.
|
|
18
|
+
* @param options.bundleBuffer - The {@link Buffer} with the bundle contents
|
|
19
|
+
* from Browserify.
|
|
20
|
+
* @param options.src - The source file path.
|
|
21
|
+
* @param options.dest - The destination file path.
|
|
22
|
+
* @param options.resolve - A {@link Promise} resolution function, so that we
|
|
23
|
+
* can use promises and `async`/`await` even though Browserify uses callbacks.
|
|
24
|
+
* @param options.argv - The Yargs `argv` object.
|
|
25
|
+
*/
|
|
26
|
+
async function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve, argv, }) {
|
|
27
|
+
if (bundleError) {
|
|
28
|
+
await misc_1.writeError('Build error:', bundleError.message, bundleError);
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
await fs_1.promises.writeFile(dest, postProcess(bundleBuffer ? bundleBuffer.toString() : null, {
|
|
32
|
+
stripComments: argv.stripComments,
|
|
33
|
+
transformHtmlComments: argv.transformHtmlComments,
|
|
34
|
+
}));
|
|
35
|
+
if (bundleBuffer) {
|
|
36
|
+
console.log(`Build success: '${src}' bundled as '${dest}'!`);
|
|
37
|
+
}
|
|
38
|
+
resolve(true);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
await misc_1.writeError('Write error:', error.message, error, dest);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
exports.writeBundleFile = writeBundleFile;
|
|
45
|
+
/**
|
|
46
|
+
* Postprocesses a JavaScript bundle string such that it can be evaluated in SES.
|
|
47
|
+
* Currently:
|
|
48
|
+
* - converts certain dot notation to string notation (for indexing)
|
|
49
|
+
* - makes all direct calls to eval indirect
|
|
50
|
+
* - wraps original bundle in anonymous function
|
|
51
|
+
* - handles certain Babel-related edge cases
|
|
52
|
+
*
|
|
53
|
+
* @param bundleString - The bundle string
|
|
54
|
+
* @param options - post process options
|
|
55
|
+
* @param options.stripComments
|
|
56
|
+
* @returns - The postprocessed bundle string
|
|
57
|
+
*/
|
|
58
|
+
function postProcess(bundleString, options = {}) {
|
|
59
|
+
if (typeof bundleString !== 'string') {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
let processedString = bundleString.trim();
|
|
63
|
+
if (options.stripComments) {
|
|
64
|
+
processedString = strip_comments_1.default(processedString);
|
|
65
|
+
}
|
|
66
|
+
// Break up tokens that could be parsed as HTML comment terminators.
|
|
67
|
+
// The regular expressions below are written strangely so as to avoid the
|
|
68
|
+
// appearance of such tokens in our source code.
|
|
69
|
+
// Ref: https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
|
|
70
|
+
// This aggressive hack may change the behavior of programs that contain HTML
|
|
71
|
+
// comment terminators in string literals.
|
|
72
|
+
if (options.transformHtmlComments) {
|
|
73
|
+
processedString = processedString.replace(new RegExp(`<!${'--'}`, 'gu'), '< !--');
|
|
74
|
+
processedString = processedString.replace(new RegExp(`${'--'}>`, 'gu'), '-- >');
|
|
75
|
+
}
|
|
76
|
+
// stuff.eval(otherStuff) => (1, stuff.eval)(otherStuff)
|
|
77
|
+
processedString = processedString.replace(/((?:\b[\w\d]*[\])]?\.)+eval)(\([^)]*\))/gu, '(1, $1)$2');
|
|
78
|
+
// If we don't do the above, the below causes syntax errors if it encounters
|
|
79
|
+
// things of the form: "something.eval(stuff)"
|
|
80
|
+
// eval(stuff) => (1, eval)(stuff)
|
|
81
|
+
processedString = processedString.replace(/(\b)(eval)(\([^)]*\))/gu, '$1(1, $2)$3');
|
|
82
|
+
// Browserify provides the Buffer global as an argument to modules that use
|
|
83
|
+
// it, but this does not work in SES. Since we pass in Buffer as an endowment,
|
|
84
|
+
// we can simply remove the argument.
|
|
85
|
+
processedString = processedString.replace(/^\(function \(Buffer\)\{$/gmu, '(function (){');
|
|
86
|
+
if (processedString.length === 0) {
|
|
87
|
+
throw new Error(`Bundled code is empty after postprocessing.`);
|
|
88
|
+
}
|
|
89
|
+
// handle some cases by declaring missing globals
|
|
90
|
+
// Babel regeneratorRuntime
|
|
91
|
+
if (processedString.indexOf('regeneratorRuntime') !== -1) {
|
|
92
|
+
processedString = `var regeneratorRuntime;\n${processedString}`;
|
|
93
|
+
}
|
|
94
|
+
return processedString;
|
|
95
|
+
}
|
|
96
|
+
exports.postProcess = postProcess;
|
|
97
|
+
/**
|
|
98
|
+
* Processes dependencies and updates argv with an options object
|
|
99
|
+
* @param argv
|
|
100
|
+
*/
|
|
101
|
+
function processDependencies(argv) {
|
|
102
|
+
const { depsToTranspile, transpilationMode } = argv;
|
|
103
|
+
const babelifyOptions = {};
|
|
104
|
+
if (transpilationMode === builders_1.TranspilationModes.localAndDeps) {
|
|
105
|
+
const regexpStr = getDependencyRegExp(depsToTranspile);
|
|
106
|
+
if (regexpStr !== null) {
|
|
107
|
+
babelifyOptions.ignore = [regexpStr];
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return babelifyOptions;
|
|
111
|
+
}
|
|
112
|
+
exports.processDependencies = processDependencies;
|
|
113
|
+
/**
|
|
114
|
+
* Processes a string of space delimited dependencies into one regex string
|
|
115
|
+
* @param dependencies
|
|
116
|
+
* @returns a regexp string
|
|
117
|
+
*/
|
|
118
|
+
function getDependencyRegExp(dependencies) {
|
|
119
|
+
let regexp = null;
|
|
120
|
+
if (!dependencies || dependencies.includes('.') || !dependencies.length) {
|
|
121
|
+
return regexp;
|
|
122
|
+
}
|
|
123
|
+
const paths = sanitizeDependencyPaths(dependencies);
|
|
124
|
+
regexp = `/node_modules/(?!${paths.shift()}`;
|
|
125
|
+
paths.forEach((path) => (regexp += `|${path}`));
|
|
126
|
+
regexp += '/)';
|
|
127
|
+
return RegExp(regexp, 'u');
|
|
128
|
+
}
|
|
129
|
+
exports.getDependencyRegExp = getDependencyRegExp;
|
|
130
|
+
/**
|
|
131
|
+
* Helper function remove any leading and trailing slashes from dependency list
|
|
132
|
+
* @param dependencies
|
|
133
|
+
* @returns an array of sanitized paths
|
|
134
|
+
*/
|
|
135
|
+
function sanitizeDependencyPaths(dependencies) {
|
|
136
|
+
return dependencies.map((dependency) => {
|
|
137
|
+
return dependency.replace(/^[/\\]+/u, '').replace(/[/\\]+$/u, '');
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
exports.sanitizeDependencyPaths = sanitizeDependencyPaths;
|
|
141
|
+
function processInvalidTranspilation(argv) {
|
|
142
|
+
if (argv.depsToTranspile &&
|
|
143
|
+
argv.transpilationMode !== builders_1.TranspilationModes.localAndDeps) {
|
|
144
|
+
throw new Error('"depsToTranspile" can only be specified if "transpilationMode" is set to "localAndDeps" .');
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
exports.processInvalidTranspilation = processInvalidTranspilation;
|
|
148
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/cmds/build/utils.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAoC;AACpC,iFAAwD;AACxD,2CAA8C;AAE9C,6CAAoD;AAWpD;;;;;;;;;;;;;;GAcG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,WAAW,EACX,YAAY,EACZ,GAAG,EACH,IAAI,EACJ,OAAO,EACP,IAAI,GACgB;IACpB,IAAI,W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I,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 stripComments from '@nodefactory/strip-comments';\nimport { writeError } from '../../utils/misc';\nimport { Option, 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 argv: YargsArgs;\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 * @param options.argv - The Yargs `argv` object.\n */\nexport async function writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n argv,\n}: WriteBundleFileArgs) {\n if (bundleError) {\n await writeError('Build error:', bundleError.message, bundleError);\n }\n\n try {\n await fs.writeFile(\n dest,\n postProcess(bundleBuffer ? bundleBuffer.toString() : null, {\n stripComments: argv.stripComments,\n transformHtmlComments: argv.transformHtmlComments,\n }) as string,\n );\n\n if (bundleBuffer) {\n console.log(`Build success: '${src}' bundled as '${dest}'!`);\n }\n resolve(true);\n } catch (error) {\n await writeError('Write error:', error.message, error, dest);\n }\n}\n\n/**\n * Postprocesses a JavaScript bundle string such that it can be evaluated in SES.\n * Currently:\n * - converts certain dot notation to string notation (for indexing)\n * - makes all direct calls to eval indirect\n * - wraps original bundle in anonymous function\n * - handles certain Babel-related edge cases\n *\n * @param bundleString - The bundle string\n * @param options - post process options\n * @param options.stripComments\n * @returns - The postprocessed bundle string\n */\nexport function postProcess(\n bundleString: string | null,\n options: Partial<Option> = {},\n): string | null {\n if (typeof bundleString !== 'string') {\n return null;\n }\n\n let processedString = bundleString.trim();\n\n if (options.stripComments) {\n processedString = stripComments(processedString);\n }\n\n // Break up tokens that could be parsed as HTML comment terminators.\n // The regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code.\n // Ref: https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // This aggressive hack may change the behavior of programs that contain HTML\n // comment terminators in string literals.\n if (options.transformHtmlComments) {\n processedString = processedString.replace(\n new RegExp(`<!${'--'}`, 'gu'),\n '< !--',\n );\n\n processedString = processedString.replace(\n new RegExp(`${'--'}>`, 'gu'),\n '-- >',\n );\n }\n\n // stuff.eval(otherStuff) => (1, stuff.eval)(otherStuff)\n processedString = processedString.replace(\n /((?:\\b[\\w\\d]*[\\])]?\\.)+eval)(\\([^)]*\\))/gu,\n '(1, $1)$2',\n );\n\n // If we don't do the above, the below causes syntax errors if it encounters\n // things of the form: \"something.eval(stuff)\"\n // eval(stuff) => (1, eval)(stuff)\n processedString = processedString.replace(\n /(\\b)(eval)(\\([^)]*\\))/gu,\n '$1(1, $2)$3',\n );\n\n // Browserify provides the Buffer global as an argument to modules that use\n // it, but this does not work in SES. Since we pass in Buffer as an endowment,\n // we can simply remove the argument.\n processedString = processedString.replace(\n /^\\(function \\(Buffer\\)\\{$/gmu,\n '(function (){',\n );\n\n if (processedString.length === 0) {\n throw new Error(`Bundled code is empty after postprocessing.`);\n }\n\n // handle some cases by declaring missing globals\n // Babel regeneratorRuntime\n if (processedString.indexOf('regeneratorRuntime') !== -1) {\n processedString = `var regeneratorRuntime;\\n${processedString}`;\n }\n\n return processedString;\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"]}
|
|
@@ -3,9 +3,11 @@ export declare function initHandler(argv: YargsArgs): Promise<{
|
|
|
3
3
|
[x: string]: unknown;
|
|
4
4
|
sourceMaps: boolean;
|
|
5
5
|
stripComments: boolean;
|
|
6
|
+
transformHtmlComments: boolean;
|
|
6
7
|
port: number;
|
|
7
8
|
dist: string;
|
|
8
9
|
src: string;
|
|
10
|
+
eval: boolean;
|
|
9
11
|
outfileName: string;
|
|
10
12
|
_?: (string | number)[] | undefined;
|
|
11
13
|
$0?: string | undefined;
|
|
@@ -56,7 +56,12 @@ async function initHandler(argv) {
|
|
|
56
56
|
}
|
|
57
57
|
// Write config file
|
|
58
58
|
try {
|
|
59
|
-
|
|
59
|
+
const defaultConfig = {
|
|
60
|
+
cliOptions: newArgs,
|
|
61
|
+
};
|
|
62
|
+
const defaultConfigFile = `module.exports = ${JSON.stringify(defaultConfig, null, 2)}
|
|
63
|
+
`;
|
|
64
|
+
await fs_1.promises.writeFile(utils_1.CONFIG_FILE, defaultConfigFile);
|
|
60
65
|
console.log(`Init: Wrote '${utils_1.CONFIG_FILE}' config file`);
|
|
61
66
|
}
|
|
62
67
|
catch (err) {
|
|
@@ -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,
|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G;AACjC,CAAC;AA5ED,kCA4EC;AAED;;;GAGG;AACI,KAAK,UAAU,oBAAoB;IACxC,MAAM,QAAQ,GAAG,CAAC,MAAM,oBAAY,CAClC,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,sCAAmB,CAAC,cAAc,CAAC,CAAC;IAC7D,MAAM,aAAE,CAAC,SAAS,CAChB,mCAAgB,CAAC,QAAQ,EACzB,IAAI,CAAC,SAAS,CAAC,qCAAmB,CAAC,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"]}
|
package/dist/cmds/watch/index.js
CHANGED
|
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
const builders_1 = __importDefault(require("../../builders"));
|
|
6
|
+
const utils_1 = require("../build/utils");
|
|
6
7
|
const watchHandler_1 = require("./watchHandler");
|
|
7
8
|
module.exports = {
|
|
8
9
|
command: ['watch', 'w'],
|
|
@@ -10,10 +11,19 @@ module.exports = {
|
|
|
10
11
|
builder: (yarg) => {
|
|
11
12
|
yarg
|
|
12
13
|
.option('src', builders_1.default.src)
|
|
14
|
+
.option('eval', builders_1.default.eval)
|
|
13
15
|
.option('dist', builders_1.default.dist)
|
|
14
16
|
.option('outfileName', builders_1.default.outfileName)
|
|
15
17
|
.option('sourceMaps', builders_1.default.sourceMaps)
|
|
16
|
-
.option('stripComments', builders_1.default.stripComments)
|
|
18
|
+
.option('stripComments', builders_1.default.stripComments)
|
|
19
|
+
.option('transformHtmlComments', builders_1.default.transformHtmlComments)
|
|
20
|
+
.option('transpilationMode', builders_1.default.transpilationMode)
|
|
21
|
+
.option('depsToTranspile', builders_1.default.depsToTranspile)
|
|
22
|
+
.option('manifest', builders_1.default.manifest)
|
|
23
|
+
.option('writeManifest', builders_1.default.writeManifest)
|
|
24
|
+
.implies('writeManifest', 'manifest')
|
|
25
|
+
.implies('depsToTranspile', 'transpilationMode')
|
|
26
|
+
.middleware((argv) => utils_1.processInvalidTranspilation(argv));
|
|
17
27
|
},
|
|
18
28
|
handler: (argv) => watchHandler_1.watch(argv),
|
|
19
29
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/watch/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,iDAAuC;AAEvC,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,sBAAsB;IAC5B,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI;aACD,MAAM,CAAC,KAAK,EAAE,kBAAQ,CAAC,GAAG,CAAC;aAC3B,MAAM,CAAC,MAAM,EAAE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AAC,IAAI,EAAE,EAAE,CAAC,mCAA2B,CAAC,IAAW,CAAC,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,oBAAK,CAAC,IAAI,CAAC;CAC1C,CAAC","sourcesContent":["import yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { processInvalidTranspilation } from '../build/utils';\nimport { watch } from './watchHandler';\n\nexport = {\n command: ['watch', 'w'],\n desc: 'Build Snap on change',\n builder: (yarg: yargs.Argv) => {\n yarg\n .option('src', builders.src)\n .option('eval', builders.eval)\n .option('dist', builders.dist)\n .option('outfileName', builders.outfileName)\n .option('sourceMaps', builders.sourceMaps)\n .option('stripComments', builders.stripComments)\n .option('transformHtmlComments', builders.transformHtmlComments)\n .option('transpilationMode', builders.transpilationMode)\n .option('depsToTranspile', builders.depsToTranspile)\n .option('manifest', builders.manifest)\n .option('writeManifest', builders.writeManifest)\n .implies('writeManifest', 'manifest')\n .implies('depsToTranspile', 'transpilationMode')\n .middleware((argv) => processInvalidTranspilation(argv as any));\n },\n handler: (argv: YargsArgs) => watch(argv),\n};\n"]}
|
|
@@ -5,8 +5,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.watch = void 0;
|
|
7
7
|
const chokidar_1 = __importDefault(require("chokidar"));
|
|
8
|
-
const bundle_1 = require("../build/bundle");
|
|
9
8
|
const utils_1 = require("../../utils");
|
|
9
|
+
const bundle_1 = require("../build/bundle");
|
|
10
|
+
const evalHandler_1 = require("../eval/evalHandler");
|
|
11
|
+
const manifestHandler_1 = require("../manifest/manifestHandler");
|
|
10
12
|
/**
|
|
11
13
|
* Watch a directory and its subdirectories for changes, and build when files
|
|
12
14
|
* are added or changed.
|
|
@@ -20,7 +22,7 @@ const utils_1 = require("../../utils");
|
|
|
20
22
|
* @param argv.'outfileName' - The output file name
|
|
21
23
|
*/
|
|
22
24
|
async function watch(argv) {
|
|
23
|
-
const {
|
|
25
|
+
const { dist, eval: shouldEval, manifest, outfileName, src } = argv;
|
|
24
26
|
if (outfileName) {
|
|
25
27
|
utils_1.validateOutfileName(outfileName);
|
|
26
28
|
}
|
|
@@ -28,7 +30,27 @@ async function watch(argv) {
|
|
|
28
30
|
await utils_1.validateDirPath(dist, true);
|
|
29
31
|
const rootDir = src.indexOf('/') === -1 ? '.' : src.substring(0, src.lastIndexOf('/') + 1);
|
|
30
32
|
const outfilePath = utils_1.getOutfilePath(dist, outfileName);
|
|
31
|
-
const
|
|
33
|
+
const buildSnap = async (path, logMessage) => {
|
|
34
|
+
if (logMessage !== undefined) {
|
|
35
|
+
console.log(logMessage);
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
await bundle_1.bundle(src, outfilePath, argv, utils_1.loadConfig().bundlerCustomizer);
|
|
39
|
+
if (manifest) {
|
|
40
|
+
await manifestHandler_1.manifestHandler(argv);
|
|
41
|
+
}
|
|
42
|
+
if (shouldEval) {
|
|
43
|
+
await evalHandler_1.snapEval(Object.assign(Object.assign({}, argv), { bundle: outfilePath }));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
utils_1.logError(`Error ${path === undefined
|
|
48
|
+
? 'during initial build'
|
|
49
|
+
: `while processing "${path}"`}.`, error);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
chokidar_1.default
|
|
53
|
+
.watch(rootDir, {
|
|
32
54
|
ignoreInitial: true,
|
|
33
55
|
ignored: [
|
|
34
56
|
'**/node_modules/**',
|
|
@@ -40,24 +62,15 @@ async function watch(argv) {
|
|
|
40
62
|
/* istanbul ignore next */
|
|
41
63
|
(str) => str !== '.' && str.startsWith('.'),
|
|
42
64
|
],
|
|
43
|
-
});
|
|
44
|
-
watcher
|
|
45
|
-
.on('ready', () => {
|
|
46
|
-
bundle_1.bundle(src, outfilePath, argv);
|
|
47
|
-
})
|
|
48
|
-
.on('add', (path) => {
|
|
49
|
-
console.log(`File added: ${path}`);
|
|
50
|
-
bundle_1.bundle(src, outfilePath, argv);
|
|
51
|
-
})
|
|
52
|
-
.on('change', (path) => {
|
|
53
|
-
console.log(`File changed: ${path}`);
|
|
54
|
-
bundle_1.bundle(src, outfilePath, argv);
|
|
55
65
|
})
|
|
66
|
+
.on('ready', buildSnap)
|
|
67
|
+
.on('add', (path) => buildSnap(path, `File added: ${path}`))
|
|
68
|
+
.on('change', (path) => buildSnap(path, `File changed: ${path}`))
|
|
56
69
|
.on('unlink', (path) => console.log(`File removed: ${path}`))
|
|
57
|
-
.on('error', (
|
|
58
|
-
utils_1.logError(`Watcher error: ${
|
|
59
|
-
})
|
|
60
|
-
|
|
70
|
+
.on('error', (error) => {
|
|
71
|
+
utils_1.logError(`Watcher error: ${error.message}`, error);
|
|
72
|
+
})
|
|
73
|
+
.add(rootDir);
|
|
61
74
|
console.log(`Watching '${rootDir}' for changes...`);
|
|
62
75
|
}
|
|
63
76
|
exports.watch = watch;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watchHandler.js","sourceRoot":"","sources":["../../../src/cmds/watch/watchHandler.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAEhC,4CAAyC;AACzC,
|
|
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;AAE9D;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACpE,IAAI,WAAW,EAAE;QACf,2BAAmB,CAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,wBAAgB,C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,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC;SACpD;KACF,CAAC;SAED,EAAE,CAAC,OAAO,EAAE,SAAS,CAAC;SACtB,EAAE,CAAC,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,gBAAQ,CAAC,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;AAhED,sBAgEC","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';\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.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Arguments } from 'yargs';
|
|
2
2
|
export declare const deepClone: <T>(input: T) => T;
|
|
3
3
|
export declare const permRequestKeys: string[];
|
|
4
|
-
export declare const CONFIG_FILE = "snap.config.
|
|
4
|
+
export declare const CONFIG_FILE = "snap.config.js";
|
|
5
5
|
/**
|
|
6
6
|
* Sets global variable snaps which tracks user settings:
|
|
7
7
|
* watch mode activation, verbose errors messages, and whether to suppress warnings.
|
|
@@ -9,6 +9,15 @@ export declare const CONFIG_FILE = "snap.config.json";
|
|
|
9
9
|
* @param argv - arguments as an object generated by yargs
|
|
10
10
|
*/
|
|
11
11
|
export declare function setSnapGlobals(argv: Arguments): void;
|
|
12
|
+
/**
|
|
13
|
+
* Attempts to convert a string to a boolean and throws if the value is invalid.
|
|
14
|
+
*
|
|
15
|
+
* @param value - The value to convert to a boolean.
|
|
16
|
+
* @return `true` if the value is the string `"true"`, `false` if it is the
|
|
17
|
+
* string `"false"`, the value if it is already a boolean, or an error
|
|
18
|
+
* otherwise.
|
|
19
|
+
*/
|
|
20
|
+
export declare function booleanStringToBoolean(value: unknown): boolean;
|
|
12
21
|
/**
|
|
13
22
|
* Sanitizes inputs. Currently normalizes "./" paths to ".".
|
|
14
23
|
* Yargs handles other path normalization as specified in builders.
|
package/dist/utils/misc.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.trimPathString = exports.writeError = exports.logWarning = exports.logError = exports.sanitizeInputs = exports.setSnapGlobals = exports.CONFIG_FILE = exports.permRequestKeys = exports.deepClone = void 0;
|
|
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
9
|
const rfdc_1 = __importDefault(require("rfdc"));
|
|
@@ -17,7 +17,7 @@ exports.permRequestKeys = [
|
|
|
17
17
|
'caveats',
|
|
18
18
|
'proof',
|
|
19
19
|
];
|
|
20
|
-
exports.CONFIG_FILE = 'snap.config.
|
|
20
|
+
exports.CONFIG_FILE = 'snap.config.js';
|
|
21
21
|
// CLI arguments whose values are file paths
|
|
22
22
|
const pathArguments = new Set([
|
|
23
23
|
'src',
|
|
@@ -43,13 +43,34 @@ function setSnapGlobals(argv) {
|
|
|
43
43
|
global.snaps.isWatching = false;
|
|
44
44
|
}
|
|
45
45
|
if (Object.prototype.hasOwnProperty.call(argv, 'verboseErrors')) {
|
|
46
|
-
global.snaps.verboseErrors =
|
|
46
|
+
global.snaps.verboseErrors = booleanStringToBoolean(argv.verboseErrors);
|
|
47
47
|
}
|
|
48
48
|
if (Object.prototype.hasOwnProperty.call(argv, 'suppressWarnings')) {
|
|
49
|
-
global.snaps.suppressWarnings =
|
|
49
|
+
global.snaps.suppressWarnings = booleanStringToBoolean(argv.suppressWarnings);
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
exports.setSnapGlobals = setSnapGlobals;
|
|
53
|
+
/**
|
|
54
|
+
* Attempts to convert a string to a boolean and throws if the value is invalid.
|
|
55
|
+
*
|
|
56
|
+
* @param value - The value to convert to a boolean.
|
|
57
|
+
* @return `true` if the value is the string `"true"`, `false` if it is the
|
|
58
|
+
* string `"false"`, the value if it is already a boolean, or an error
|
|
59
|
+
* otherwise.
|
|
60
|
+
*/
|
|
61
|
+
function booleanStringToBoolean(value) {
|
|
62
|
+
if (typeof value === 'boolean') {
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
else if (value === 'true') {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
else if (value === 'false') {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
throw new Error(`Expected a boolean or the strings "true" or "false". Received: "${value}"`);
|
|
72
|
+
}
|
|
73
|
+
exports.booleanStringToBoolean = booleanStringToBoolean;
|
|
53
74
|
/**
|
|
54
75
|
* Sanitizes inputs. Currently normalizes "./" paths to ".".
|
|
55
76
|
* Yargs handles other path normalization as specified in builders.
|
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,gD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AAC,CAAC;AACnD,CAAC;AAFD,wCAEC","sourcesContent":["import { promises as filesystem } from 'fs';\nimport path from 'path';\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 (Object.prototype.hasOwnProperty.call(argv, 'verboseErrors')) {\n global.snaps.verboseErrors = booleanStringToBoolean(argv.verboseErrors);\n }\n\n if (Object.prototype.hasOwnProperty.call(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"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isSnapConfig = void 0;
|
|
4
|
+
function isSnapConfig(obj, _argumentName) {
|
|
5
|
+
return ((obj !== null &&
|
|
6
|
+
typeof obj === "object" ||
|
|
7
|
+
typeof obj === "function") &&
|
|
8
|
+
(typeof obj.cliOptions === "undefined" ||
|
|
9
|
+
(obj.cliOptions !== null &&
|
|
10
|
+
typeof obj.cliOptions === "object" ||
|
|
11
|
+
typeof obj.cliOptions === "function") &&
|
|
12
|
+
Object.entries(obj.cliOptions)
|
|
13
|
+
.every(([key, _value]) => (typeof key === "string"))) &&
|
|
14
|
+
(typeof obj.bundlerCustomizer === "undefined" ||
|
|
15
|
+
typeof obj.bundlerCustomizer === "function"));
|
|
16
|
+
}
|
|
17
|
+
exports.isSnapConfig = isSnapConfig;
|
|
18
|
+
//# sourceMappingURL=snap-config.__GENERATED__.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snap-config.__GENERATED__.js","sourceRoot":"","sources":["../../src/utils/snap-config.__GENERATED__.ts"],"names":[],"mappings":";;;AAMA,SAAgB,YAAY,CAAC,GAAQ,EAAE,aAAsB;IACzD,OAAO,CACH,CAAC,GAAG,KAAK,IAAI;QACT,OAAO,GAAG,KAAK,QAAQ;QACvB,OAAO,GAAG,KAAK,UAAU,CAAC;QAC9B,CAAC,OAAO,GAAG,CAAC,UAAU,KAAK,WAAW;YAClC,CAAC,GAAG,CAAC,UAAU,KAAK,IAAI;gBACpB,OAAO,GAAG,CAAC,UAAU,KAAK,QAAQ;gBAClC,OAAO,GAAG,CAAC,UAAU,KAAK,UAAU,CAAC;gBACzC,MAAM,CAAC,OAAO,CAAM,GAAG,CAAC,UAAU,CAAC;qBAC9B,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC;QAC7D,CAAC,OAAO,GAAG,CAAC,iBAAiB,KAAK,WAAW;YACzC,OAAO,GAAG,CAAC,iBAAiB,KAAK,UAAU,CAAC,CACnD,CAAA;AACL,CAAC;AAdD,oCAcC","sourcesContent":["/*\n * Generated type guards for \"snap-config.ts\".\n * WARNING: Do not manually change this file.\n */\nimport { SnapConfig } from \"./snap-config\";\n\nexport function isSnapConfig(obj: any, _argumentName?: string): obj is SnapConfig {\n return (\n (obj !== null &&\n typeof obj === \"object\" ||\n typeof obj === \"function\") &&\n (typeof obj.cliOptions === \"undefined\" ||\n (obj.cliOptions !== null &&\n typeof obj.cliOptions === \"object\" ||\n typeof obj.cliOptions === \"function\") &&\n Object.entries<any>(obj.cliOptions)\n .every(([key, _value]) => (typeof key === \"string\"))) &&\n (typeof obj.bundlerCustomizer === \"undefined\" ||\n typeof obj.bundlerCustomizer === \"function\")\n )\n}\n"]}
|
|
@@ -1,5 +1,12 @@
|
|
|
1
|
+
import type browserify from 'browserify';
|
|
1
2
|
import { Arguments } from 'yargs';
|
|
2
3
|
import yargs from 'yargs/yargs';
|
|
4
|
+
/** @see {isSnapConfig} ts-auto-guard:type-guard */
|
|
5
|
+
export declare type SnapConfig = {
|
|
6
|
+
cliOptions?: Record<string, unknown>;
|
|
7
|
+
bundlerCustomizer?: (bundler: browserify.BrowserifyObject) => void;
|
|
8
|
+
};
|
|
9
|
+
export declare function loadConfig(cached?: boolean): SnapConfig;
|
|
3
10
|
/**
|
|
4
11
|
* Attempts to read configuration options for package.json and the config file,
|
|
5
12
|
* and apply them to argv if they weren't already set.
|
|
@@ -7,4 +14,4 @@ import yargs from 'yargs/yargs';
|
|
|
7
14
|
* Arguments are only set per the snap-cli config file if they were not specified
|
|
8
15
|
* on the command line.
|
|
9
16
|
*/
|
|
10
|
-
export declare function applyConfig(processArgv: string[], yargsArgv: Arguments, yargsInstance: typeof yargs): void;
|
|
17
|
+
export declare function applyConfig(snapConfig: SnapConfig, processArgv: string[], yargsArgv: Arguments, yargsInstance: typeof yargs): void;
|