@metamask/snaps-cli 0.7.0 → 0.10.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 +43 -1
- package/README.md +67 -25
- package/dist/builders.d.ts +16 -8
- package/dist/builders.js +66 -41
- package/dist/builders.js.map +1 -1
- package/dist/cli.js +5 -4
- 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 +152 -0
- package/dist/cmds/build/utils.js.map +1 -0
- package/dist/cmds/eval/evalHandler.d.ts +1 -1
- package/dist/cmds/eval/evalHandler.js +1 -2
- package/dist/cmds/eval/evalHandler.js.map +1 -1
- package/dist/cmds/eval/index.d.ts +1 -1
- package/dist/cmds/index.d.ts +2 -7
- package/dist/cmds/init/init-template.json +2 -2
- package/dist/cmds/init/initHandler.d.ts +2 -0
- package/dist/cmds/init/initHandler.js +11 -6
- package/dist/cmds/init/initHandler.js.map +1 -1
- package/dist/cmds/init/initUtils.js +4 -4
- package/dist/cmds/init/initUtils.js.map +1 -1
- package/dist/cmds/manifest/index.js +1 -1
- package/dist/cmds/manifest/index.js.map +1 -1
- package/dist/cmds/serve/index.js +2 -2
- package/dist/cmds/serve/index.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/fs.js +1 -1
- package/dist/utils/fs.js.map +1 -1
- package/dist/utils/misc.d.ts +10 -1
- package/dist/utils/misc.js +27 -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 -7
- 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
package/dist/cmds/build/index.js
CHANGED
|
@@ -4,20 +4,26 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
const builders_1 = __importDefault(require("../../builders"));
|
|
6
6
|
const buildHandler_1 = require("./buildHandler");
|
|
7
|
+
const utils_1 = require("./utils");
|
|
7
8
|
module.exports = {
|
|
8
9
|
command: ['build', 'b'],
|
|
9
10
|
desc: 'Build Snap from source',
|
|
10
11
|
builder: (yarg) => {
|
|
11
12
|
yarg
|
|
12
|
-
.option('src', builders_1.default.src)
|
|
13
13
|
.option('dist', builders_1.default.dist)
|
|
14
|
+
.option('eval', builders_1.default.eval)
|
|
15
|
+
.option('manifest', builders_1.default.manifest)
|
|
14
16
|
.option('outfileName', builders_1.default.outfileName)
|
|
15
17
|
.option('sourceMaps', builders_1.default.sourceMaps)
|
|
18
|
+
.option('src', builders_1.default.src)
|
|
16
19
|
.option('stripComments', builders_1.default.stripComments)
|
|
17
|
-
.option('
|
|
18
|
-
.option('
|
|
20
|
+
.option('transpilationMode', builders_1.default.transpilationMode)
|
|
21
|
+
.option('depsToTranspile', builders_1.default.depsToTranspile)
|
|
22
|
+
.option('transformHtmlComments', builders_1.default.transformHtmlComments)
|
|
19
23
|
.option('writeManifest', builders_1.default.writeManifest)
|
|
20
|
-
.implies('writeManifest', 'manifest')
|
|
24
|
+
.implies('writeManifest', 'manifest')
|
|
25
|
+
.implies('depsToTranspile', 'transpilationMode')
|
|
26
|
+
.middleware((argv) => utils_1.processInvalidTranspilation(argv));
|
|
21
27
|
},
|
|
22
28
|
handler: (argv) => buildHandler_1.build(argv),
|
|
23
29
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/build/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,iDAAuC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/build/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,iDAAuC;AACvC,mCAAsD;AAEtD,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,wBAAwB;IAC9B,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI;aACD,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC;aAC7B,MAAM,CAAC,UAAU,EAAE,kBAAQ,CAAC,QAAQ,CAAC;aACrC,MAAM,CAAC,aAAa,EAAE,kBAAQ,CAAC,WAAW,CAAC;aAC3C,MAAM,CAAC,YAAY,EAAE,kBAAQ,CAAC,UAAU,CAAC;aACzC,MAAM,CAAC,KAAK,EAAE,kBAAQ,CAAC,GAAG,CAAC;aAC3B,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;aAC/C,MAAM,CAAC,mBAAmB,EAAE,kBAAQ,CAAC,iBAAiB,CAAC;aACvD,MAAM,CAAC,iBAAiB,EAAE,kBAAQ,CAAC,eAAe,CAAC;aACnD,MAAM,CAAC,uBAAuB,EAAE,kBAAQ,CAAC,qBAAqB,CAAC;aAC/D,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;aAC/C,OAAO,CAAC,eAAe,EAAE,UAAU,CAAC;aACpC,OAAO,CAAC,iBAAiB,EAAE,mBAAmB,CAAC;aAC/C,UAAU,CAAC,CAAC,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 { 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,152 @@
|
|
|
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
|
+
// TODO: Upstream a better fix to @nodefactory/strip-comments
|
|
65
|
+
// The strip-comments package has issues with block comments of the
|
|
66
|
+
// form "/**/", and so we remove them manually first:
|
|
67
|
+
processedString = processedString.replace(/\/\*\*\//gu, '');
|
|
68
|
+
processedString = strip_comments_1.default(processedString);
|
|
69
|
+
}
|
|
70
|
+
// Break up tokens that could be parsed as HTML comment terminators.
|
|
71
|
+
// The regular expressions below are written strangely so as to avoid the
|
|
72
|
+
// appearance of such tokens in our source code.
|
|
73
|
+
// Ref: https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
|
|
74
|
+
// This aggressive hack may change the behavior of programs that contain HTML
|
|
75
|
+
// comment terminators in string literals.
|
|
76
|
+
if (options.transformHtmlComments) {
|
|
77
|
+
processedString = processedString.replace(new RegExp(`<!${'--'}`, 'gu'), '< !--');
|
|
78
|
+
processedString = processedString.replace(new RegExp(`${'--'}>`, 'gu'), '-- >');
|
|
79
|
+
}
|
|
80
|
+
// stuff.eval(otherStuff) => (1, stuff.eval)(otherStuff)
|
|
81
|
+
processedString = processedString.replace(/((?:\b[\w\d]*[\])]?\.)+eval)(\([^)]*\))/gu, '(1, $1)$2');
|
|
82
|
+
// If we don't do the above, the below causes syntax errors if it encounters
|
|
83
|
+
// things of the form: "something.eval(stuff)"
|
|
84
|
+
// eval(stuff) => (1, eval)(stuff)
|
|
85
|
+
processedString = processedString.replace(/(\b)(eval)(\([^)]*\))/gu, '$1(1, $2)$3');
|
|
86
|
+
// Browserify provides the Buffer global as an argument to modules that use
|
|
87
|
+
// it, but this does not work in SES. Since we pass in Buffer as an endowment,
|
|
88
|
+
// we can simply remove the argument.
|
|
89
|
+
processedString = processedString.replace(/^\(function \(Buffer\)\{$/gmu, '(function (){');
|
|
90
|
+
if (processedString.length === 0) {
|
|
91
|
+
throw new Error(`Bundled code is empty after postprocessing.`);
|
|
92
|
+
}
|
|
93
|
+
// handle some cases by declaring missing globals
|
|
94
|
+
// Babel regeneratorRuntime
|
|
95
|
+
if (processedString.indexOf('regeneratorRuntime') !== -1) {
|
|
96
|
+
processedString = `var regeneratorRuntime;\n${processedString}`;
|
|
97
|
+
}
|
|
98
|
+
return processedString;
|
|
99
|
+
}
|
|
100
|
+
exports.postProcess = postProcess;
|
|
101
|
+
/**
|
|
102
|
+
* Processes dependencies and updates argv with an options object
|
|
103
|
+
* @param argv
|
|
104
|
+
*/
|
|
105
|
+
function processDependencies(argv) {
|
|
106
|
+
const { depsToTranspile, transpilationMode } = argv;
|
|
107
|
+
const babelifyOptions = {};
|
|
108
|
+
if (transpilationMode === builders_1.TranspilationModes.localAndDeps) {
|
|
109
|
+
const regexpStr = getDependencyRegExp(depsToTranspile);
|
|
110
|
+
if (regexpStr !== null) {
|
|
111
|
+
babelifyOptions.ignore = [regexpStr];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return babelifyOptions;
|
|
115
|
+
}
|
|
116
|
+
exports.processDependencies = processDependencies;
|
|
117
|
+
/**
|
|
118
|
+
* Processes a string of space delimited dependencies into one regex string
|
|
119
|
+
* @param dependencies
|
|
120
|
+
* @returns a regexp string
|
|
121
|
+
*/
|
|
122
|
+
function getDependencyRegExp(dependencies) {
|
|
123
|
+
let regexp = null;
|
|
124
|
+
if (!dependencies || dependencies.includes('.') || !dependencies.length) {
|
|
125
|
+
return regexp;
|
|
126
|
+
}
|
|
127
|
+
const paths = sanitizeDependencyPaths(dependencies);
|
|
128
|
+
regexp = `/node_modules/(?!${paths.shift()}`;
|
|
129
|
+
paths.forEach((path) => (regexp += `|${path}`));
|
|
130
|
+
regexp += '/)';
|
|
131
|
+
return RegExp(regexp, 'u');
|
|
132
|
+
}
|
|
133
|
+
exports.getDependencyRegExp = getDependencyRegExp;
|
|
134
|
+
/**
|
|
135
|
+
* Helper function remove any leading and trailing slashes from dependency list
|
|
136
|
+
* @param dependencies
|
|
137
|
+
* @returns an array of sanitized paths
|
|
138
|
+
*/
|
|
139
|
+
function sanitizeDependencyPaths(dependencies) {
|
|
140
|
+
return dependencies.map((dependency) => {
|
|
141
|
+
return dependency.replace(/^[/\\]+/u, '').replace(/[/\\]+$/u, '');
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
exports.sanitizeDependencyPaths = sanitizeDependencyPaths;
|
|
145
|
+
function processInvalidTranspilation(argv) {
|
|
146
|
+
if (argv.depsToTranspile &&
|
|
147
|
+
argv.transpilationMode !== builders_1.TranspilationModes.localAndDeps) {
|
|
148
|
+
throw new Error('"depsToTranspile" can only be specified if "transpilationMode" is set to "localAndDeps" .');
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
exports.processInvalidTranspilation = processInvalidTranspilation;
|
|
152
|
+
//# 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,WAAW,EAAE;QACf,MAAM,iBAAU,CAAC,cAAc,EAAE,WAAW,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;KACpE;IAED,IAAI;QACF,MAAM,aAAE,CAAC,SAAS,CAChB,IAAI,EACJ,WAAW,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE;YACzD,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;SAClD,CAAW,CACb,CAAC;QAEF,IAAI,YAAY,EAAE;YAChB,OAAO,CAAC,GAAG,CAAC,mBAAmB,GAAG,iBAAiB,IAAI,IAAI,CAAC,CAAC;SAC9D;QACD,OAAO,CAAC,IAAI,CAAC,CAAC;KACf;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,iBAAU,CAAC,cAAc,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;KAC9D;AACH,CAAC;AA5BD,0CA4BC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,WAAW,CACzB,YAA2B,EAC3B,UAA2B,EAAE;IAE7B,IAAI,OAAO,YAAY,KAAK,QAAQ,EAAE;QACpC,OAAO,IAAI,CAAC;KACb;IAED,IAAI,eAAe,GAAG,YAAY,CAAC,IAAI,EAAE,CAAC;IAE1C,IAAI,OAAO,CAAC,aAAa,EAAE;QACz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AAC,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 // TODO: Upstream a better fix to @nodefactory/strip-comments\n // The strip-comments package has issues with block comments of the\n // form \"/**/\", and so we remove them manually first:\n processedString = processedString.replace(/\\/\\*\\*\\//gu, '');\n\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"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { YargsArgs } from '../../types/yargs';
|
|
2
|
-
export declare function snapEval(argv: YargsArgs): Promise<
|
|
2
|
+
export declare function snapEval(argv: YargsArgs): Promise<void>;
|
|
@@ -9,11 +9,10 @@ async function snapEval(argv) {
|
|
|
9
9
|
try {
|
|
10
10
|
await workerEval_1.workerEval(bundlePath);
|
|
11
11
|
console.log(`Eval Success: evaluated '${bundlePath}' in SES!`);
|
|
12
|
-
return true;
|
|
13
12
|
}
|
|
14
13
|
catch (err) {
|
|
15
14
|
utils_1.logError(`Snap evaluation error: ${err.message}`, err);
|
|
16
|
-
|
|
15
|
+
throw err;
|
|
17
16
|
}
|
|
18
17
|
}
|
|
19
18
|
exports.snapEval = snapEval;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evalHandler.js","sourceRoot":"","sources":["../../../src/cmds/eval/evalHandler.ts"],"names":[],"mappings":";;;AACA,uCAAyD;AACzD,6CAA0C;AAEnC,KAAK,UAAU,QAAQ,CAAC,IAAe;IAC5C,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;IACpC,MAAM,wBAAgB,CAAC,UAAoB,CAAC,CAAC;IAC7C,IAAI;QACF,MAAM,uBAAU,CAAC,UAAoB,CAAC,CAAC;QACvC,OAAO,CAAC,GAAG,CAAC,4BAA4B,UAAU,WAAW,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"evalHandler.js","sourceRoot":"","sources":["../../../src/cmds/eval/evalHandler.ts"],"names":[],"mappings":";;;AACA,uCAAyD;AACzD,6CAA0C;AAEnC,KAAK,UAAU,QAAQ,CAAC,IAAe;IAC5C,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;IACpC,MAAM,wBAAgB,CAAC,UAAoB,CAAC,CAAC;IAC7C,IAAI;QACF,MAAM,uBAAU,CAAC,UAAoB,CAAC,CAAC;QACvC,OAAO,CAAC,GAAG,CAAC,4BAA4B,UAAU,WAAW,CAAC,CAAC;KAChE;IAAC,OAAO,GAAG,EAAE;QACZ,gBAAQ,CAAC,0BAA0B,GAAG,CAAC,OAAO,EAAE,EAAE,GAAG,CAAC,CAAC;QACvD,MAAM,GAAG,CAAC;KACX;AACH,CAAC;AAVD,4BAUC","sourcesContent":["import { YargsArgs } from '../../types/yargs';\nimport { logError, validateFilePath } from '../../utils';\nimport { workerEval } from './workerEval';\n\nexport async function snapEval(argv: YargsArgs): Promise<void> {\n const { bundle: bundlePath } = argv;\n await validateFilePath(bundlePath as string);\n try {\n await workerEval(bundlePath as string);\n console.log(`Eval Success: evaluated '${bundlePath}' in SES!`);\n } catch (err) {\n logError(`Snap evaluation error: ${err.message}`, err);\n throw err;\n }\n}\n"]}
|
package/dist/cmds/index.d.ts
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
declare const commands:
|
|
1
|
+
declare const commands: {
|
|
2
2
|
command: string[];
|
|
3
3
|
desc: string;
|
|
4
4
|
builder: (yarg: import("yargs").Argv<{}>) => void;
|
|
5
5
|
handler: (argv: import("../types/yargs").YargsArgs) => Promise<void>;
|
|
6
|
-
}
|
|
7
|
-
command: string[];
|
|
8
|
-
desc: string;
|
|
9
|
-
builder: (yarg: import("yargs").Argv<{}>) => void;
|
|
10
|
-
handler: (argv: import("../types/yargs").YargsArgs) => Promise<boolean>;
|
|
11
|
-
})[];
|
|
6
|
+
}[];
|
|
12
7
|
export default commands;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
{
|
|
2
|
-
"html": "<!doctype html>\n<html>\n </head>\n <title>Hello, Snaps!</title>\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 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
|
|
3
|
-
"source": "wallet.registerRpcMessageHandler(async (originString, requestObject) => {\n switch (requestObject.method) {\n case 'hello':\n return wallet.request({\n method: 'snap_confirm',\n params: [{
|
|
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 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": "wallet.registerRpcMessageHandler(async (originString, requestObject) => {\n switch (requestObject.method) {\n case 'hello':\n return wallet.request({\n method: 'snap_confirm',\n params: [\n {\n prompt: `Hello, ${originString}!`,\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
|
}
|
|
@@ -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;
|
|
@@ -6,8 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.updateManifestShasum = exports.initHandler = void 0;
|
|
7
7
|
const fs_1 = require("fs");
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
|
-
const mkdirp_1 = __importDefault(require("mkdirp"));
|
|
10
9
|
const snap_controllers_1 = require("@metamask/snap-controllers");
|
|
10
|
+
const mkdirp_1 = __importDefault(require("mkdirp"));
|
|
11
11
|
const utils_1 = require("../../utils");
|
|
12
12
|
const manifestHandler_1 = require("../manifest/manifestHandler");
|
|
13
13
|
const init_template_json_1 = __importDefault(require("./init-template.json"));
|
|
@@ -29,7 +29,7 @@ async function initHandler(argv) {
|
|
|
29
29
|
}
|
|
30
30
|
catch (err) {
|
|
31
31
|
utils_1.logError(`Init Error: Failed to write '${snap_controllers_1.NpmSnapFileNames.Manifest}'.`, err);
|
|
32
|
-
|
|
32
|
+
throw err;
|
|
33
33
|
}
|
|
34
34
|
console.log(`\nInit: Created '${snap_controllers_1.NpmSnapFileNames.Manifest}'.`);
|
|
35
35
|
// Write main .js entry file
|
|
@@ -43,7 +43,7 @@ async function initHandler(argv) {
|
|
|
43
43
|
}
|
|
44
44
|
catch (err) {
|
|
45
45
|
utils_1.logError(`Init Error: Failed to write '${src}'.`, err);
|
|
46
|
-
|
|
46
|
+
throw err;
|
|
47
47
|
}
|
|
48
48
|
// Write index.html
|
|
49
49
|
try {
|
|
@@ -52,16 +52,21 @@ async function initHandler(argv) {
|
|
|
52
52
|
}
|
|
53
53
|
catch (err) {
|
|
54
54
|
utils_1.logError(`Init Error: Failed to write 'index.html'.`, err);
|
|
55
|
-
|
|
55
|
+
throw err;
|
|
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) {
|
|
63
68
|
utils_1.logError(`Init Error: Failed to write '${utils_1.CONFIG_FILE}'.`, err);
|
|
64
|
-
|
|
69
|
+
throw err;
|
|
65
70
|
}
|
|
66
71
|
utils_1.closePrompt();
|
|
67
72
|
return Object.assign(Object.assign({}, argv), newArgs);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initHandler.js","sourceRoot":"","sources":["../../../src/cmds/init/initHandler.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAoC;AACpC,gDAA6B;AAC7B,
|
|
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,4BAAgB,EAAE,CAAC;IAE7C,MAAM,mCAAuB,EAAE,CAAC;IAEhC,OAAO,CAAC,GAAG,CAAC,qBAAqB,mCAAgB,CAAC,QAAQ,QAAQ,CAAC,CAAC;IAEpE,MAAM,CAAC,YAAY,EAAE,QAAQ,CAAC,GAAG,MAAM,6BAAiB,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAE5E,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CA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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"]}
|
|
@@ -34,13 +34,13 @@ async function asyncPackageInit() {
|
|
|
34
34
|
}
|
|
35
35
|
catch (error) {
|
|
36
36
|
utils_1.logError(`Init Error: Could not parse '${snaps_1.NpmSnapFileNames.PackageJson}'. Please verify that the file is correctly formatted and try again.`, error);
|
|
37
|
-
|
|
37
|
+
throw error;
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
40
|
// Exit if yarn.lock is found, or we'll be in trouble
|
|
41
41
|
if (fs_1.existsSync('yarn.lock')) {
|
|
42
42
|
utils_1.logError(`Init Error: Found a 'yarn.lock' file but no '${snaps_1.NpmSnapFileNames.PackageJson}'. Please run 'yarn init' and try again.`);
|
|
43
|
-
|
|
43
|
+
throw new Error('Already existing yarn.lock file found');
|
|
44
44
|
}
|
|
45
45
|
// Run 'npm init'
|
|
46
46
|
return new Promise((resolve, reject) => {
|
|
@@ -101,7 +101,7 @@ async function buildSnapManifest(argv, packageJson) {
|
|
|
101
101
|
}
|
|
102
102
|
catch (err) {
|
|
103
103
|
utils_1.logError(`Init Error: ${err.message}`, err);
|
|
104
|
-
|
|
104
|
+
throw err;
|
|
105
105
|
}
|
|
106
106
|
let invalidProposedName = true;
|
|
107
107
|
while (invalidProposedName) {
|
|
@@ -235,7 +235,7 @@ async function prepareWorkingDirectory() {
|
|
|
235
235
|
const shouldContinue = continueInput && isYes(continueInput);
|
|
236
236
|
if (!shouldContinue) {
|
|
237
237
|
console.log(`Init: Exiting...`);
|
|
238
|
-
|
|
238
|
+
throw new Error('User refused to continue');
|
|
239
239
|
}
|
|
240
240
|
}
|
|
241
241
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initUtils.js","sourceRoot":"","sources":["../../../src/cmds/init/initUtils.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAgD;AAChD,gDAA6B;AAC7B,iEAM+C;AAC/C,0EAAgD;AAChD,oDAA4B;AAC5B,kDAA0B;AAC1B,uCAQqB;AAGrB;;GAEG;AACH,MAAM,kBAAkB,GAAG,8CAA8C,CAAC;AAE1E,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AAE7D;;;;;;GAMG;AACI,KAAK,UAAU,gBAAgB;IAGpC,IAAI,eAAU,CAAC,wBAAgB,CAAC,WAAW,CAAC,EAAE;QAC5C,OAAO,CAAC,GAAG,CACT,qCAAqC,wBAAgB,CAAC,WAAW,MAAM,CACxE,CAAC;QAEF,IAAI;YACF,MAAM,WAAW,GAAG,MAAM,oBAAY,CAAC,wBAAgB,CAAC,WAAW,CAAC,CAAC;YACrE,4BAAoB,CAAC,wBAAgB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;YAEhE,OAAO,CAAC,GAAG,CACT,8BAA8B,wBAAgB,CAAC,WAAW,IAAI,CAC/D,CAAC;YACF,OAAO,WAAiC,CAAC;SAC1C;QAAC,OAAO,KAAK,EAAE;YACd,gBAAQ,CACN,gCAAgC,wBAAgB,CAAC,WAAW,sEAAsE,EAClI,KAAK,CACN,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACjB;KACF;IAED,qDAAqD;IACrD,IAAI,eAAU,CAAC,WAAW,CAAC,EAAE;QAC3B,gBAAQ,CACN,gDAAgD,wBAAgB,C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;AACI,KAAK,UAAU,uBAAuB;IAC3C,MAAM,aAAa,GAAG,CAAC,MAAM,aAAE,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CACtE,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CACrC,CAAC;IAEF,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5B,kBAAU,CACR,0EAA0E,aAAa,CAAC,MAAM,CAC5F,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE;YACvB,OAAO,GAAG,OAAO,KAAK,WAAW,IAAI,CAAC;QACxC,CAAC,EACD,EAAE,CACH,EAAE,CACJ,CAAC;QAEF,MAAM,aAAa,GAAG,MAAM,cAAM,CAAC;YACjC,QAAQ,EAAE,WAAW;YACrB,YAAY,EAAE,GAAG;SAClB,CAAC,CAAC;QACH,MAAM,cAAc,GAAG,aAAa,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAE7D,IAAI,CAAC,cAAc,EAAE;YACnB,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;YAChC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACjB;KACF;AACH,CAAC;AA1BD,0DA0BC","sourcesContent":["import { promises as fs, existsSync } from 'fs';\nimport pathUtils from 'path';\nimport {\n NpmSnapPackageJson,\n SnapManifest,\n NpmSnapFileNames,\n validateSnapJsonFile,\n PROPOSED_NAME_REGEX,\n} from '@metamask/snap-controllers/dist/snaps';\nimport initPackageJson from 'init-package-json';\nimport mkdirp from 'mkdirp';\nimport slash from 'slash';\nimport {\n CONFIG_FILE,\n deepClone,\n logError,\n logWarning,\n prompt,\n readJsonFile,\n trimPathString,\n} from '../../utils';\nimport { YargsArgs } from '../../types/yargs';\n\n/**\n * This is a placeholder shasum that will be replaced at the end of the init command.\n */\nconst PLACEHOLDER_SHASUM = '2QqUxo5joo4kKKr7yiCjdYsZOZcIFBnIBEdwU9Yx7+M=';\n\nconst NPM_PUBLIC_REGISTRY_URL = 'https://registry.npmjs.org';\n\n/**\n * Initializes a `package.json` file for a Snap project. Will attempt to read\n * and parse the existing file if it already exists, otherwise will intialize\n * a brand new one.\n *\n * @returns The contents of the `package.json` file.\n */\nexport async function asyncPackageInit(): Promise<\n Readonly<NpmSnapPackageJson>\n> {\n if (existsSync(NpmSnapFileNames.PackageJson)) {\n console.log(\n `Init: Attempting to use existing '${NpmSnapFileNames.PackageJson}'...`,\n );\n\n try {\n const packageJson = await readJsonFile(NpmSnapFileNames.PackageJson);\n validateSnapJsonFile(NpmSnapFileNames.PackageJson, packageJson);\n\n console.log(\n `Init: Successfully parsed '${NpmSnapFileNames.PackageJson}'!`,\n );\n return packageJson as NpmSnapPackageJson;\n } catch (error) {\n logError(\n `Init Error: Could not parse '${NpmSnapFileNames.PackageJson}'. Please verify that the file is correctly formatted and try again.`,\n error,\n );\n process.exit(1);\n }\n }\n\n // Exit if yarn.lock is found, or we'll be in trouble\n if (existsSync('yarn.lock')) {\n logError(\n `Init Error: Found a 'yarn.lock' file but no '${NpmSnapFileNames.PackageJson}'. Please run 'yarn init' and try again.`,\n );\n process.exit(1);\n }\n\n // Run 'npm init'\n return new Promise((resolve, reject) => {\n initPackageJson(process.cwd(), '', {}, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve(data);\n }\n });\n });\n}\n\nconst YES = 'yes';\nconst YES_VALUES = new Set([YES, 'y']);\n\nfunction isYes(userInput: string | undefined) {\n return userInput && YES_VALUES.has(userInput.toLowerCase());\n}\n\nconst DEFAULT_PERMISSION_KEY = 'snap_confirm';\nconst getDefaultPermissions = () => {\n return { [DEFAULT_PERMISSION_KEY]: {} };\n};\n\n/**\n * Interactively constructs a Snap manifest file by prompting the user.\n *\n * @param argv - The `yargs` `argv` object.\n * @param packageJson - The `package.json` object.\n * @param shasum - The shasum of the Snap source file.\n * @returns A tuple of the resulting Snap manifest object and a new `argv` object\n * with properties to match the manifest.\n */\nexport async function buildSnapManifest(\n argv: YargsArgs,\n packageJson: NpmSnapPackageJson,\n): Promise<[SnapManifest, { dist: string; outfileName: string; src: string }]> {\n const { outfileName } = argv;\n let { dist } = argv;\n let initialPermissions: Record<string, unknown> = getDefaultPermissions();\n let { description, name: proposedName } = packageJson;\n\n if (!description) {\n description = `The ${proposedName} Snap.`;\n }\n\n try {\n const userInput = await prompt({\n question: `Use default Snap manifest values?`,\n defaultValue: YES,\n shouldClose: false,\n });\n\n if (isYes(userInput)) {\n console.log('Using default values...');\n try {\n await mkdirp(dist);\n } catch (err) {\n logError(\n `Init Error: Could not write default 'dist' '${dist}'. Maybe check your local ${CONFIG_FILE} file?`,\n );\n throw err;\n }\n return endSnapManifest();\n }\n } catch (err) {\n logError(`Init Error: ${err.message}`, err);\n process.exit(1);\n }\n\n let invalidProposedName = true;\n while (invalidProposedName) {\n // eslint-disable-next-line require-atomic-updates\n proposedName = await prompt({\n question: `Proposed Snap name:`,\n defaultValue: proposedName,\n });\n\n if (\n proposedName.length > 0 &&\n proposedName.length <= 214 &&\n PROPOSED_NAME_REGEX.test(proposedName)\n ) {\n invalidProposedName = false;\n } else {\n logError(\n `The proposed name must adhere to npm package naming conventions, except that capital letters are allowed. For details, see: https://docs.npmjs.com/cli/v6/configuring-npm/package-json#name`,\n );\n }\n }\n\n let invalidDescription = true;\n while (invalidDescription) {\n // eslint-disable-next-line require-atomic-updates\n description = await prompt({\n question: `Description:`,\n defaultValue: description,\n });\n\n if (description.length === 0 || description.length <= 280) {\n invalidDescription = false;\n } else {\n logError(\n `The description must be a non-empty string less than or equal to 280 characters.`,\n );\n }\n }\n\n let invalidDist = true;\n while (invalidDist) {\n // eslint-disable-next-line require-atomic-updates\n dist = await prompt({ question: `Output directory:`, defaultValue: dist });\n try {\n dist = trimPathString(dist);\n await mkdirp(dist);\n invalidDist = false;\n } catch (distError) {\n logError(\n `Unable to create directory '${dist}'. Ensure that the path is valid and try again.`,\n distError,\n );\n }\n }\n\n let invalidPermissions = true;\n while (invalidPermissions) {\n const inputPermissions = await prompt({\n // We add the parenthetical default value ourselves\n question: `Initial permissions: [perm1 perm2 ...] ([snap_confirm])`,\n });\n\n if (\n !inputPermissions ||\n inputPermissions.trim() === DEFAULT_PERMISSION_KEY\n ) {\n break;\n }\n\n try {\n initialPermissions = inputPermissions\n .split(' ')\n .reduce((allPermissions, permission) => {\n if (\n typeof permission === 'string' &&\n permission.match(/^[\\w\\d_:]+$/iu)\n ) {\n allPermissions[permission] = {};\n } else {\n throw new Error(`Invalid permission: ${permission}`);\n }\n return allPermissions;\n }, {} as Record<string, unknown>);\n\n invalidPermissions = false;\n } catch (err) {\n logError(\n `Invalid permissions '${inputPermissions}'.\\nThe permissions must be specified as a space-separated list of strings with only characters, digits, underscores ('_'), and colons (':').`,\n err,\n );\n }\n }\n\n return endSnapManifest();\n\n function endSnapManifest(): [\n SnapManifest,\n {\n dist: string;\n outfileName: string;\n src: string;\n },\n ] {\n const manifest = {\n version: packageJson.version,\n description,\n proposedName,\n repository: packageJson.repository\n ? deepClone(packageJson.repository)\n : null,\n source: {\n shasum: PLACEHOLDER_SHASUM,\n location: {\n npm: {\n filePath: slash(pathUtils.join(dist, outfileName)),\n packageName: packageJson.name,\n registry: NPM_PUBLIC_REGISTRY_URL,\n } as const,\n },\n },\n initialPermissions,\n manifestVersion: '0.1' as const,\n };\n\n try {\n validateSnapJsonFile(NpmSnapFileNames.Manifest, manifest);\n } catch (error) {\n /* istanbul ignore next */\n throw new Error(\n `Internal Error: Validation of constructed manifest failed. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n return [\n manifest,\n { dist, outfileName, src: packageJson.main || 'src/index.js' },\n ];\n }\n}\n\nconst INIT_FILE_NAMES = new Set([\n 'src',\n 'index.html',\n CONFIG_FILE,\n 'dist',\n NpmSnapFileNames.Manifest,\n]);\n\n/**\n * Checks whether any files in the current working directory will be overwritten\n * by the initialization process, and asks the user whether to continue if so.\n */\nexport async function prepareWorkingDirectory(): Promise<void> {\n const existingFiles = (await fs.readdir(process.cwd())).filter((item) =>\n INIT_FILE_NAMES.has(item.toString()),\n );\n\n if (existingFiles.length > 0) {\n logWarning(\n `\\nInit Warning: Existing files and/or directories may be overwritten:\\n${existingFiles.reduce(\n (message, currentFile) => {\n return `${message}\\t${currentFile}\\n`;\n },\n '',\n )}`,\n );\n\n const continueInput = await prompt({\n question: `Continue?`,\n defaultValue: YES,\n });\n const shouldContinue = continueInput && isYes(continueInput);\n\n if (!shouldContinue) {\n console.log(`Init: Exiting...`);\n process.exit(1);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"initUtils.js","sourceRoot":"","sources":["../../../src/cmds/init/initUtils.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAgD;AAChD,gDAA6B;AAC7B,iEAM+C;AAC/C,0EAAgD;AAChD,oDAA4B;AAC5B,kDAA0B;AAE1B,uCAQqB;AAErB;;GAEG;AACH,MAAM,kBAAkB,GAAG,8CAA8C,CAAC;AAE1E,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AAE7D;;;;;;GAMG;AACI,KAAK,UAAU,gBAAgB;IAGpC,IAAI,eAAU,CAAC,wBAAgB,CAAC,WAAW,CAAC,EAAE;QAC5C,OAAO,CAAC,GAAG,CACT,qCAAqC,wBAAgB,CAAC,WAAW,MAAM,CACxE,CAAC;QAEF,IAAI;YACF,MAAM,WAAW,GAAG,MAAM,oBAAY,CAAC,wBAAgB,CAAC,WAAW,CAAC,CAAC;YACrE,4BAAoB,CAAC,wBAAgB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;YAEhE,OAAO,CAAC,GAAG,CACT,8BAA8B,wBAAgB,CAAC,WAAW,IAAI,CAC/D,CAAC;YACF,OAAO,WAAiC,CAAC;SAC1C;QAAC,OAAO,KAAK,EAAE;YACd,gBAAQ,CACN,gCAAgC,wBAAgB,CAAC,WAAW,sEAAsE,EAClI,KAAK,CACN,CAAC;YACF,MAAM,KAA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,YAAY;IACZ,mBAAW;IACX,MAAM;IACN,wBAAgB,CAAC,QAAQ;CAC1B,CAAC,CAAC;AAEH;;;GAGG;AACI,KAAK,UAAU,uBAAuB;IAC3C,MAAM,aAAa,GAAG,CAAC,MAAM,aAAE,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CACtE,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CACrC,CAAC;IAEF,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5B,kBAAU,CACR,0EAA0E,aAAa,CAAC,MAAM,CAC5F,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE;YACvB,OAAO,GAAG,OAAO,KAAK,WAAW,IAAI,CAAC;QACxC,CAAC,EACD,EAAE,CACH,EAAE,CACJ,CAAC;QAEF,MAAM,aAAa,GAAG,MAAM,cAAM,CAAC;YACjC,QAAQ,EAAE,WAAW;YACrB,YAAY,EAAE,GAAG;SAClB,CAAC,CAAC;QACH,MAAM,cAAc,GAAG,aAAa,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;QAE7D,IAAI,CAAC,cAAc,EAAE;YACnB,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;YAChC,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;SAC7C;KACF;AACH,CAAC;AA1BD,0DA0BC","sourcesContent":["import { existsSync, promises as fs } from 'fs';\nimport pathUtils from 'path';\nimport {\n NpmSnapFileNames,\n NpmSnapPackageJson,\n PROPOSED_NAME_REGEX,\n SnapManifest,\n validateSnapJsonFile,\n} from '@metamask/snap-controllers/dist/snaps';\nimport initPackageJson from 'init-package-json';\nimport mkdirp from 'mkdirp';\nimport slash from 'slash';\nimport { YargsArgs } from '../../types/yargs';\nimport {\n CONFIG_FILE,\n deepClone,\n logError,\n logWarning,\n prompt,\n readJsonFile,\n trimPathString,\n} from '../../utils';\n\n/**\n * This is a placeholder shasum that will be replaced at the end of the init command.\n */\nconst PLACEHOLDER_SHASUM = '2QqUxo5joo4kKKr7yiCjdYsZOZcIFBnIBEdwU9Yx7+M=';\n\nconst NPM_PUBLIC_REGISTRY_URL = 'https://registry.npmjs.org';\n\n/**\n * Initializes a `package.json` file for a Snap project. Will attempt to read\n * and parse the existing file if it already exists, otherwise will intialize\n * a brand new one.\n *\n * @returns The contents of the `package.json` file.\n */\nexport async function asyncPackageInit(): Promise<\n Readonly<NpmSnapPackageJson>\n> {\n if (existsSync(NpmSnapFileNames.PackageJson)) {\n console.log(\n `Init: Attempting to use existing '${NpmSnapFileNames.PackageJson}'...`,\n );\n\n try {\n const packageJson = await readJsonFile(NpmSnapFileNames.PackageJson);\n validateSnapJsonFile(NpmSnapFileNames.PackageJson, packageJson);\n\n console.log(\n `Init: Successfully parsed '${NpmSnapFileNames.PackageJson}'!`,\n );\n return packageJson as NpmSnapPackageJson;\n } catch (error) {\n logError(\n `Init Error: Could not parse '${NpmSnapFileNames.PackageJson}'. Please verify that the file is correctly formatted and try again.`,\n error,\n );\n throw error;\n }\n }\n\n // Exit if yarn.lock is found, or we'll be in trouble\n if (existsSync('yarn.lock')) {\n logError(\n `Init Error: Found a 'yarn.lock' file but no '${NpmSnapFileNames.PackageJson}'. Please run 'yarn init' and try again.`,\n );\n throw new Error('Already existing yarn.lock file found');\n }\n\n // Run 'npm init'\n return new Promise((resolve, reject) => {\n initPackageJson(process.cwd(), '', {}, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve(data);\n }\n });\n });\n}\n\nconst YES = 'yes';\nconst YES_VALUES = new Set([YES, 'y']);\n\nfunction isYes(userInput: string | undefined) {\n return userInput && YES_VALUES.has(userInput.toLowerCase());\n}\n\nconst DEFAULT_PERMISSION_KEY = 'snap_confirm';\nconst getDefaultPermissions = () => {\n return { [DEFAULT_PERMISSION_KEY]: {} };\n};\n\n/**\n * Interactively constructs a Snap manifest file by prompting the user.\n *\n * @param argv - The `yargs` `argv` object.\n * @param packageJson - The `package.json` object.\n * @param shasum - The shasum of the Snap source file.\n * @returns A tuple of the resulting Snap manifest object and a new `argv` object\n * with properties to match the manifest.\n */\nexport async function buildSnapManifest(\n argv: YargsArgs,\n packageJson: NpmSnapPackageJson,\n): Promise<[SnapManifest, { dist: string; outfileName: string; src: string }]> {\n const { outfileName } = argv;\n let { dist } = argv;\n let initialPermissions: Record<string, unknown> = getDefaultPermissions();\n let { description, name: proposedName } = packageJson;\n\n if (!description) {\n description = `The ${proposedName} Snap.`;\n }\n\n try {\n const userInput = await prompt({\n question: `Use default Snap manifest values?`,\n defaultValue: YES,\n shouldClose: false,\n });\n\n if (isYes(userInput)) {\n console.log('Using default values...');\n try {\n await mkdirp(dist);\n } catch (err) {\n logError(\n `Init Error: Could not write default 'dist' '${dist}'. Maybe check your local ${CONFIG_FILE} file?`,\n );\n throw err;\n }\n return endSnapManifest();\n }\n } catch (err) {\n logError(`Init Error: ${err.message}`, err);\n throw err;\n }\n\n let invalidProposedName = true;\n while (invalidProposedName) {\n // eslint-disable-next-line require-atomic-updates\n proposedName = await prompt({\n question: `Proposed Snap name:`,\n defaultValue: proposedName,\n });\n\n if (\n proposedName.length > 0 &&\n proposedName.length <= 214 &&\n PROPOSED_NAME_REGEX.test(proposedName)\n ) {\n invalidProposedName = false;\n } else {\n logError(\n `The proposed name must adhere to npm package naming conventions, except that capital letters are allowed. For details, see: https://docs.npmjs.com/cli/v6/configuring-npm/package-json#name`,\n );\n }\n }\n\n let invalidDescription = true;\n while (invalidDescription) {\n // eslint-disable-next-line require-atomic-updates\n description = await prompt({\n question: `Description:`,\n defaultValue: description,\n });\n\n if (description.length === 0 || description.length <= 280) {\n invalidDescription = false;\n } else {\n logError(\n `The description must be a non-empty string less than or equal to 280 characters.`,\n );\n }\n }\n\n let invalidDist = true;\n while (invalidDist) {\n // eslint-disable-next-line require-atomic-updates\n dist = await prompt({ question: `Output directory:`, defaultValue: dist });\n try {\n dist = trimPathString(dist);\n await mkdirp(dist);\n invalidDist = false;\n } catch (distError) {\n logError(\n `Unable to create directory '${dist}'. Ensure that the path is valid and try again.`,\n distError,\n );\n }\n }\n\n let invalidPermissions = true;\n while (invalidPermissions) {\n const inputPermissions = await prompt({\n // We add the parenthetical default value ourselves\n question: `Initial permissions: [perm1 perm2 ...] ([snap_confirm])`,\n });\n\n if (\n !inputPermissions ||\n inputPermissions.trim() === DEFAULT_PERMISSION_KEY\n ) {\n break;\n }\n\n try {\n initialPermissions = inputPermissions\n .split(' ')\n .reduce((allPermissions, permission) => {\n if (\n typeof permission === 'string' &&\n permission.match(/^[\\w\\d_:]+$/iu)\n ) {\n allPermissions[permission] = {};\n } else {\n throw new Error(`Invalid permission: ${permission}`);\n }\n return allPermissions;\n }, {} as Record<string, unknown>);\n\n invalidPermissions = false;\n } catch (err) {\n logError(\n `Invalid permissions '${inputPermissions}'.\\nThe permissions must be specified as a space-separated list of strings with only characters, digits, underscores ('_'), and colons (':').`,\n err,\n );\n }\n }\n\n return endSnapManifest();\n\n function endSnapManifest(): [\n SnapManifest,\n {\n dist: string;\n outfileName: string;\n src: string;\n },\n ] {\n const manifest = {\n version: packageJson.version,\n description,\n proposedName,\n repository: packageJson.repository\n ? deepClone(packageJson.repository)\n : null,\n source: {\n shasum: PLACEHOLDER_SHASUM,\n location: {\n npm: {\n filePath: slash(pathUtils.join(dist, outfileName)),\n packageName: packageJson.name,\n registry: NPM_PUBLIC_REGISTRY_URL,\n } as const,\n },\n },\n initialPermissions,\n manifestVersion: '0.1' as const,\n };\n\n try {\n validateSnapJsonFile(NpmSnapFileNames.Manifest, manifest);\n } catch (error) {\n /* istanbul ignore next */\n throw new Error(\n `Internal Error: Validation of constructed manifest failed. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n return [\n manifest,\n { dist, outfileName, src: packageJson.main || 'src/index.js' },\n ];\n }\n}\n\nconst INIT_FILE_NAMES = new Set([\n 'src',\n 'index.html',\n CONFIG_FILE,\n 'dist',\n NpmSnapFileNames.Manifest,\n]);\n\n/**\n * Checks whether any files in the current working directory will be overwritten\n * by the initialization process, and asks the user whether to continue if so.\n */\nexport async function prepareWorkingDirectory(): Promise<void> {\n const existingFiles = (await fs.readdir(process.cwd())).filter((item) =>\n INIT_FILE_NAMES.has(item.toString()),\n );\n\n if (existingFiles.length > 0) {\n logWarning(\n `\\nInit Warning: Existing files and/or directories may be overwritten:\\n${existingFiles.reduce(\n (message, currentFile) => {\n return `${message}\\t${currentFile}\\n`;\n },\n '',\n )}`,\n );\n\n const continueInput = await prompt({\n question: `Continue?`,\n defaultValue: YES,\n });\n const shouldContinue = continueInput && isYes(continueInput);\n\n if (!shouldContinue) {\n console.log(`Init: Exiting...`);\n throw new Error('User refused to continue');\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/manifest/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/manifest/index.ts"],"names":[],"mappings":";;;;AACA,8DAAsC;AAEtC,uCAAuC;AACvC,uDAAoD;AAEpD,iBAAS;IACP,OAAO,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC;IAC1B,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,eAAe,kCAAO,kBAAQ,CAAC,aAAa,KAAE,KAAK,EAAE,CAAC,KAAK,CAAC,IAAG,CAAC;IAC9E,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,IAAe,EAAE,EAAE;QACjC,IAAI;YACF,MAAM,iCAAe,CAAC,IAAI,CAAC,CAAC;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,gBAAQ,CAAC,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"]}
|
package/dist/cmds/serve/index.js
CHANGED
|
@@ -39,11 +39,11 @@ async function serve(argv) {
|
|
|
39
39
|
server.on('request', (request) => serveUtils_1.logRequest(request));
|
|
40
40
|
server.on('error', (error) => {
|
|
41
41
|
serveUtils_1.logServerError(error, argv.port);
|
|
42
|
-
process.
|
|
42
|
+
process.exitCode = 1;
|
|
43
43
|
});
|
|
44
44
|
server.on('close', () => {
|
|
45
45
|
console.log('Server closed');
|
|
46
|
-
process.
|
|
46
|
+
process.exitCode = 1;
|
|
47
47
|
});
|
|
48
48
|
}
|
|
49
49
|
module.exports = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cmds/serve/index.ts"],"names":[],"mappings":";;;;AAAA,gDAAwB;AACxB,kEAAyC;AAEzC,8DAAsC;AAEtC,uCAA8C;AAC9C,6CAA8E;AAW9E;;;;;;;GAOG;AACH,KAAK,UAAU,KAAK,CAAC,IAAe;IAClC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAErC,MAAM,uBAAe,CAAC,OAAiB,EAAE,IAAI,CAAC,CAAC;IAE/C,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAEpC,MAAM,MAAM,GAAG,cAAI,CAAC,YAAY,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;QAClD,MAAM,uBAAY,C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EAAE;wBACP;4BACE,GAAG,EAAE,eAAe;4BACpB,KAAK,EAAE,UAAU;yBAClB;qBACF;iBACF;aACF;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,CAAC,+BAAkB,CAAC,IAAI,CAAC,CAAC,CAAC;IAExD,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,uBAAU,CAAC,OAAO,CAAC,CAAC,CAAC;IAEvD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;QAC3B,2BAAc,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAC7B,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC;AAtDD,iBAAS;IACP,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;IACvB,IAAI,EAAE,wCAAwC;IAC9C,OAAO,EAAE,CAAC,IAAgB,EAAE,EAAE;QAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAQ,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,EAAE,CAAC,IAAe,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC;CAC1C,CAAC","sourcesContent":["import http from 'http';\nimport serveHandler from 'serve-handler';\nimport yargs from 'yargs';\nimport builders from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { validateDirPath } from '../../utils';\nimport { logRequest, logServerError, logServerListening } from './serveUtils';\n\nexport = {\n command: ['serve', 's'],\n desc: 'Locally serve Snap file(s) for testing',\n builder: (yarg: yargs.Argv) => {\n yarg.option('root', builders.root).option('port', builders.port);\n },\n handler: (argv: YargsArgs) => serve(argv),\n};\n\n/**\n * Starts a local, static HTTP server on the given port with the given root\n * directory.\n *\n * @param argv - arguments as an object generated by yargs\n * @param argv.root - The root directory path string\n * @param argv.port - The server port\n */\nasync function serve(argv: YargsArgs): Promise<void> {\n const { port, root: rootDir } = argv;\n\n await validateDirPath(rootDir as string, true);\n\n console.log(`\\nStarting server...`);\n\n const server = http.createServer(async (req, res) => {\n await serveHandler(req, res, {\n public: rootDir as string,\n headers: [\n {\n source: '**/*',\n headers: [\n {\n key: 'Cache-Control',\n value: 'no-cache',\n },\n ],\n },\n ],\n });\n });\n\n server.listen({ port }, () => logServerListening(port));\n\n server.on('request', (request) => logRequest(request));\n\n server.on('error', (error) => {\n logServerError(error, argv.port);\n process.exitCode = 1;\n });\n\n server.on('close', () => {\n console.log('Server closed');\n process.exitCode = 1;\n });\n}\n"]}
|