@metamask/snaps-cli 0.22.3 → 0.24.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.
Files changed (40) hide show
  1. package/README.md +6 -6
  2. package/dist/builders.d.ts +2 -6
  3. package/dist/builders.js +3 -12
  4. package/dist/builders.js.map +1 -1
  5. package/dist/cmds/build/buildHandler.js +5 -5
  6. package/dist/cmds/build/buildHandler.js.map +1 -1
  7. package/dist/cmds/eval/evalHandler.js +3 -5
  8. package/dist/cmds/eval/evalHandler.js.map +1 -1
  9. package/dist/cmds/init/index.js +3 -13
  10. package/dist/cmds/init/index.js.map +1 -1
  11. package/dist/cmds/init/initHandler.d.ts +5 -9
  12. package/dist/cmds/init/initHandler.js +37 -96
  13. package/dist/cmds/init/initHandler.js.map +1 -1
  14. package/dist/cmds/init/initUtils.d.ts +25 -32
  15. package/dist/cmds/init/initUtils.js +80 -250
  16. package/dist/cmds/init/initUtils.js.map +1 -1
  17. package/dist/cmds/manifest/manifestHandler.js +2 -2
  18. package/dist/cmds/manifest/manifestHandler.js.map +1 -1
  19. package/dist/cmds/serve/serveHandler.js +2 -2
  20. package/dist/cmds/serve/serveHandler.js.map +1 -1
  21. package/dist/cmds/watch/watchHandler.js +5 -5
  22. package/dist/cmds/watch/watchHandler.js.map +1 -1
  23. package/dist/utils/index.d.ts +0 -1
  24. package/dist/utils/index.js +0 -1
  25. package/dist/utils/index.js.map +1 -1
  26. package/dist/utils/misc.d.ts +1 -1
  27. package/dist/utils/misc.js +6 -1
  28. package/dist/utils/misc.js.map +1 -1
  29. package/dist/utils/snap-config.d.ts +21 -4
  30. package/dist/utils/snap-config.js +20 -3
  31. package/dist/utils/snap-config.js.map +1 -1
  32. package/package.json +13 -19
  33. package/dist/cmds/init/init-template.json +0 -8
  34. package/dist/tsconfig.json +0 -8
  35. package/dist/utils/readline.d.ts +0 -37
  36. package/dist/utils/readline.js +0 -75
  37. package/dist/utils/readline.js.map +0 -1
  38. package/dist/utils/snap-config.__GENERATED__.d.ts +0 -2
  39. package/dist/utils/snap-config.__GENERATED__.js +0 -18
  40. package/dist/utils/snap-config.__GENERATED__.js.map +0 -1
@@ -3,290 +3,120 @@ 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.isTemplateTypescript = exports.correctDefaultArgs = exports.prepareWorkingDirectory = exports.buildSnapManifest = exports.asyncPackageInit = void 0;
6
+ exports.yarnInstall = exports.gitInit = exports.isInGitRepository = exports.isGitInstalled = exports.cloneTemplate = exports.prepareWorkingDirectory = exports.SNAP_LOCATION = exports.TEMPLATE_GIT_URL = void 0;
7
7
  const fs_1 = require("fs");
8
+ const child_process_1 = require("child_process");
8
9
  const path_1 = __importDefault(require("path"));
9
- const snap_utils_1 = require("@metamask/snap-utils");
10
- const init_package_json_1 = __importDefault(require("init-package-json"));
11
- const mkdirp_1 = __importDefault(require("mkdirp"));
12
- const slash_1 = __importDefault(require("slash"));
13
- const utils_1 = require("../../utils");
14
- const builders_1 = require("../../builders");
10
+ exports.TEMPLATE_GIT_URL = 'https://github.com/MetaMask/template-snap-monorepo.git';
11
+ exports.SNAP_LOCATION = 'packages/snap/';
15
12
  /**
16
- * This is a placeholder shasum that will be replaced at the end of the init command.
17
- */
18
- const PLACEHOLDER_SHASUM = '2QqUxo5joo4kKKr7yiCjdYsZOZcIFBnIBEdwU9Yx7+M=';
19
- const NPM_PUBLIC_REGISTRY_URL = 'https://registry.npmjs.org';
20
- /**
21
- * Initializes a `package.json` file for a Snap project. Will attempt to read
22
- * and parse the existing file if it already exists, otherwise will intialize
23
- * a brand new one.
13
+ * Checks if the destination folder exists and if it's empty. Otherwise create it.
24
14
  *
25
- * @param argv - Yargs arguments object.
26
- * @returns The contents of the `package.json` file.
15
+ * @param directory - The desination folder.
27
16
  */
28
- async function asyncPackageInit(argv) {
29
- if ((0, fs_1.existsSync)(snap_utils_1.NpmSnapFileNames.PackageJson)) {
30
- console.log(`Init: Attempting to use existing '${snap_utils_1.NpmSnapFileNames.PackageJson}'...`);
31
- try {
32
- const packageJson = await (0, snap_utils_1.readJsonFile)(snap_utils_1.NpmSnapFileNames.PackageJson);
33
- (0, snap_utils_1.validateSnapJsonFile)(snap_utils_1.NpmSnapFileNames.PackageJson, packageJson);
34
- console.log(`Init: Successfully parsed '${snap_utils_1.NpmSnapFileNames.PackageJson}'!`);
35
- return packageJson;
17
+ async function prepareWorkingDirectory(directory) {
18
+ try {
19
+ const isCurrentDirectory = directory === process.cwd();
20
+ if (!isCurrentDirectory) {
21
+ try {
22
+ await fs_1.promises.mkdir(directory, { recursive: true });
23
+ }
24
+ catch (err) {
25
+ throw new Error('Init Error: Failed to create new directory.');
26
+ }
36
27
  }
37
- catch (error) {
38
- (0, utils_1.logError)(`Init Error: Could not parse '${snap_utils_1.NpmSnapFileNames.PackageJson}'. Please verify that the file is correctly formatted and try again.`, error);
39
- throw error;
28
+ const existingFiles = await fs_1.promises.readdir(directory);
29
+ if (existingFiles.length > 0) {
30
+ throw new Error(`Directory ${directory} not empty.`);
40
31
  }
41
32
  }
42
- // Exit if yarn.lock is found, or we'll be in trouble
43
- if ((0, fs_1.existsSync)('yarn.lock')) {
44
- (0, utils_1.logError)(`Init Error: Found a 'yarn.lock' file but no '${snap_utils_1.NpmSnapFileNames.PackageJson}'. Please run 'yarn init' and try again.`);
45
- throw new Error('Already existing yarn.lock file found');
33
+ catch (err) {
34
+ throw new Error(`Init Error: Failed to prepare working directory with message: ${err.message}`);
46
35
  }
47
- // Run 'npm init'
48
- return new Promise((resolve, reject) => {
49
- (0, init_package_json_1.default)(process.cwd(), '', {
50
- 'init.main': argv.src,
51
- }, (err, data) => {
52
- if (err) {
53
- reject(err);
54
- }
55
- else {
56
- resolve(data);
57
- }
58
- });
59
- });
60
36
  }
61
- exports.asyncPackageInit = asyncPackageInit;
62
- const YES = 'yes';
63
- const YES_VALUES = new Set([YES, 'y']);
37
+ exports.prepareWorkingDirectory = prepareWorkingDirectory;
64
38
  /**
65
- * Checks if user input provided over a prompt is "yes", i.e., if the value is
66
- * truthy and in the {@link YES_VALUES} set.
39
+ * Clones the template in a directory.
67
40
  *
68
- * @param userInput - The user input to check.
69
- * @returns `true` if the user input is "yes", `false` otherwise.
41
+ * @param directory - The directory to clone the template in.
70
42
  */
71
- function isYes(userInput) {
72
- return userInput && YES_VALUES.has(userInput.toLowerCase());
43
+ async function cloneTemplate(directory) {
44
+ try {
45
+ (0, child_process_1.execSync)(`git clone --depth=1 ${exports.TEMPLATE_GIT_URL} ${directory}`, {
46
+ stdio: [2],
47
+ });
48
+ }
49
+ catch (err) {
50
+ throw new Error('Init Error: Failed to clone the template.');
51
+ }
73
52
  }
74
- const DEFAULT_PERMISSION_KEY = 'snap_confirm';
53
+ exports.cloneTemplate = cloneTemplate;
75
54
  /**
76
- * Get the default permissions to write to the snap manifest.
55
+ * Check if git is installed.
77
56
  *
78
- * @returns An object containing the default permissions.
57
+ * @returns True if git is installed, or false otherwise.
79
58
  */
80
- const getDefaultPermissions = () => {
81
- return { [DEFAULT_PERMISSION_KEY]: {} };
82
- };
59
+ function isGitInstalled() {
60
+ try {
61
+ (0, child_process_1.execSync)('git --version', { stdio: 'ignore' });
62
+ return true;
63
+ }
64
+ catch (e) {
65
+ return false;
66
+ }
67
+ }
68
+ exports.isGitInstalled = isGitInstalled;
83
69
  /**
84
- * Interactively constructs a Snap manifest file by prompting the user.
70
+ * Check if the actual working dir is a git repository.
85
71
  *
86
- * @param argv - The `yargs` `argv` object.
87
- * @param packageJson - The `package.json` object.
88
- * @returns A tuple of the resulting Snap manifest object and a new `argv`
89
- * object with properties to match the manifest.
72
+ * @param directory - The directory to check.
73
+ * @returns True if it's a git repository otherwise false.
90
74
  */
91
- async function buildSnapManifest(argv, packageJson) {
92
- const { outfileName } = argv;
93
- let { dist } = argv;
94
- let initialPermissions = getDefaultPermissions();
95
- let { description, name: proposedName } = packageJson;
96
- if (!description) {
97
- description = `The ${proposedName} Snap.`;
98
- }
75
+ function isInGitRepository(directory) {
99
76
  try {
100
- const userInput = await (0, utils_1.prompt)({
101
- question: `Use default Snap manifest values?`,
102
- defaultValue: YES,
103
- shouldClose: false,
77
+ (0, child_process_1.execSync)('git rev-parse --is-inside-work-tree', {
78
+ stdio: 'ignore',
79
+ cwd: path_1.default.resolve(__dirname, directory),
104
80
  });
105
- if (isYes(userInput)) {
106
- console.log('Using default values...');
107
- try {
108
- await (0, mkdirp_1.default)(dist);
109
- }
110
- catch (err) {
111
- (0, utils_1.logError)(`Init Error: Could not write default 'dist' '${dist}'. Maybe check your local ${utils_1.CONFIG_FILE} file?`);
112
- throw err;
113
- }
114
- return endSnapManifest();
115
- }
81
+ return true;
116
82
  }
117
83
  catch (err) {
118
- (0, utils_1.logError)(`Init Error: ${err.message}`, err);
119
- throw err;
120
- }
121
- let invalidProposedName = true;
122
- while (invalidProposedName) {
123
- // eslint-disable-next-line require-atomic-updates
124
- proposedName = await (0, utils_1.prompt)({
125
- question: `Proposed Snap name:`,
126
- defaultValue: proposedName,
127
- });
128
- if (proposedName.length > 0 &&
129
- proposedName.length <= 214 &&
130
- snap_utils_1.PROPOSED_NAME_REGEX.test(proposedName)) {
131
- invalidProposedName = false;
132
- }
133
- else {
134
- (0, utils_1.logError)(`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`);
135
- }
136
- }
137
- let invalidDescription = true;
138
- while (invalidDescription) {
139
- // eslint-disable-next-line require-atomic-updates
140
- description = await (0, utils_1.prompt)({
141
- question: `Description:`,
142
- defaultValue: description,
143
- });
144
- if (description.length === 0 || description.length <= 280) {
145
- invalidDescription = false;
146
- }
147
- else {
148
- (0, utils_1.logError)(`The description must be a non-empty string less than or equal to 280 characters.`);
149
- }
150
- }
151
- let invalidDist = true;
152
- while (invalidDist) {
153
- // eslint-disable-next-line require-atomic-updates
154
- dist = await (0, utils_1.prompt)({ question: `Output directory:`, defaultValue: dist });
155
- try {
156
- dist = (0, utils_1.trimPathString)(dist);
157
- await (0, mkdirp_1.default)(dist);
158
- invalidDist = false;
159
- }
160
- catch (distError) {
161
- (0, utils_1.logError)(`Unable to create directory '${dist}'. Ensure that the path is valid and try again.`, distError);
162
- }
163
- }
164
- let invalidPermissions = true;
165
- while (invalidPermissions) {
166
- const inputPermissions = await (0, utils_1.prompt)({
167
- // We add the parenthetical default value ourselves
168
- question: `Initial permissions: [perm1 perm2 ...] ([snap_confirm])`,
169
- });
170
- if (!inputPermissions ||
171
- inputPermissions.trim() === DEFAULT_PERMISSION_KEY) {
172
- break;
173
- }
174
- try {
175
- initialPermissions = inputPermissions
176
- .split(' ')
177
- .reduce((allPermissions, permission) => {
178
- if (typeof permission === 'string' &&
179
- permission.match(/^[\w\d_:]+$/iu)) {
180
- allPermissions[permission] = {};
181
- }
182
- else {
183
- throw new Error(`Invalid permission: ${permission}`);
184
- }
185
- return allPermissions;
186
- }, {});
187
- invalidPermissions = false;
188
- }
189
- catch (err) {
190
- (0, utils_1.logError)(`Invalid permissions '${inputPermissions}'.\nThe permissions must be specified as a space-separated list of strings with only characters, digits, underscores ('_'), and colons (':').`, err);
191
- }
192
- }
193
- return endSnapManifest();
194
- /**
195
- * Get the final snap manifest object and return it, along with the dist and
196
- * file names.
197
- *
198
- * @returns A tuple of the resulting snap manifest object and an object
199
- * containing the dist and file names.
200
- */
201
- function endSnapManifest() {
202
- const manifest = {
203
- version: packageJson.version,
204
- description,
205
- proposedName,
206
- repository: packageJson.repository
207
- ? (0, snap_utils_1.deepClone)(packageJson.repository)
208
- : null,
209
- source: {
210
- shasum: PLACEHOLDER_SHASUM,
211
- location: {
212
- npm: {
213
- filePath: (0, slash_1.default)(path_1.default.join(dist, outfileName)),
214
- packageName: packageJson.name,
215
- registry: NPM_PUBLIC_REGISTRY_URL,
216
- iconPath: 'images/icon.svg',
217
- },
218
- },
219
- },
220
- initialPermissions,
221
- manifestVersion: '0.1',
222
- };
223
- try {
224
- (0, snap_utils_1.validateSnapJsonFile)(snap_utils_1.NpmSnapFileNames.Manifest, manifest);
225
- }
226
- catch (error) {
227
- /* istanbul ignore next */
228
- throw new Error(`Internal Error: Validation of constructed manifest failed. This is a bug, please report it. Reason:\n${error.message}`);
229
- }
230
- return [
231
- manifest,
232
- { dist, outfileName, src: packageJson.main || 'src/index.js' },
233
- ];
84
+ return false;
234
85
  }
235
86
  }
236
- exports.buildSnapManifest = buildSnapManifest;
237
- const INIT_FILE_NAMES = new Set([
238
- 'src',
239
- 'index.html',
240
- utils_1.CONFIG_FILE,
241
- 'dist',
242
- snap_utils_1.NpmSnapFileNames.Manifest,
243
- ]);
87
+ exports.isInGitRepository = isInGitRepository;
244
88
  /**
245
- * Checks whether any files in the current working directory will be overwritten
246
- * by the initialization process, and asks the user whether to continue if so.
89
+ * Init a git repository.
90
+ *
91
+ * @param directory - The directory to init.
247
92
  */
248
- async function prepareWorkingDirectory() {
249
- const existingFiles = (await fs_1.promises.readdir(process.cwd())).filter((item) => INIT_FILE_NAMES.has(item.toString()));
250
- if (existingFiles.length > 0) {
251
- (0, utils_1.logWarning)(`\nInit Warning: Existing files and/or directories may be overwritten:\n${existingFiles.reduce((message, currentFile) => {
252
- return `${message}\t${currentFile}\n`;
253
- }, '')}`);
254
- const continueInput = await (0, utils_1.prompt)({
255
- question: `Continue?`,
256
- defaultValue: YES,
93
+ async function gitInit(directory) {
94
+ try {
95
+ (0, child_process_1.execSync)('git init', {
96
+ stdio: 'ignore',
97
+ cwd: path_1.default.resolve(__dirname, directory),
257
98
  });
258
- const shouldContinue = continueInput && isYes(continueInput);
259
- if (!shouldContinue) {
260
- console.log(`Init: Exiting...`);
261
- throw new Error('User refused to continue');
262
- }
263
99
  }
264
- }
265
- exports.prepareWorkingDirectory = prepareWorkingDirectory;
266
- /**
267
- * In case when TypeScript version is used, default source file
268
- * will be updated if previous was not correct.
269
- *
270
- * @param yargsArgv - The Yargs arguments object.
271
- * @returns Modified Yargs arguments object.
272
- */
273
- function correctDefaultArgs(yargsArgv) {
274
- if (yargsArgv.template === builders_1.TemplateType.TypeScript &&
275
- yargsArgv.src === 'src/index.js') {
276
- yargsArgv.src = 'src/index.ts';
277
- yargsArgv.s = 'src/index.ts';
100
+ catch (err) {
101
+ throw new Error('Init Error: Failed to init a new git repository.');
278
102
  }
279
- return yargsArgv;
280
103
  }
281
- exports.correctDefaultArgs = correctDefaultArgs;
104
+ exports.gitInit = gitInit;
282
105
  /**
283
- * Check if template argument is TemplateType.TypeScript.
106
+ * Install dependencies in a yarn project.
284
107
  *
285
- * @param templateType - TemplateType value of the template argument passed from CLI.
286
- * @returns True or false.
108
+ * @param directory - The directory containing the project.
287
109
  */
288
- function isTemplateTypescript(templateType) {
289
- return templateType === builders_1.TemplateType.TypeScript;
110
+ async function yarnInstall(directory) {
111
+ try {
112
+ (0, child_process_1.execSync)('yarn install', {
113
+ stdio: [0, 1, 2],
114
+ cwd: path_1.default.resolve(__dirname, directory),
115
+ });
116
+ }
117
+ catch (err) {
118
+ throw new Error('Init Error: Failed to install dependencies.');
119
+ }
290
120
  }
291
- exports.isTemplateTypescript = isTemplateTypescript;
121
+ exports.yarnInstall = yarnInstall;
292
122
  //# sourceMappingURL=initUtils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"initUtils.js","sourceRoot":"","sources":["../../../src/cmds/init/initUtils.ts"],"names":[],"mappings":";;;;;;AAAA,2BAAgD;AAChD,gDAA6B;AAC7B,qDAQ8B;AAC9B,0EAAgD;AAChD,oDAA4B;AAC5B,kDAA0B;AAG1B,uCAMqB;AACrB,6CAA8C;AAE9C;;GAEG;AACH,MAAM,kBAAkB,GAAG,8CAA8C,CAAC;AAE1E,MAAM,uBAAuB,GAAG,4BAA4B,CAAC;AAE7D;;;;;;;GAOG;AACI,KAAK,UAAU,gBAAgB,CACpC,IAAe;IAEf,IAAI,IAAA,eAAU,EAAC,6BAAgB,CAAC,WAAW,CAAC,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CAAC,EACD,EAAE,CACH,EAAE,CACJ,CAAC;QAEF,MAAM,aAAa,GAAG,MAAM,IAAA,cAAM,EAAC;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;AAED;;;;;;GAMG;AACH,SAAgB,kBAAkB,CAAC,SAAoB;IACrD,IACE,SAAS,CAAC,QAAQ,KAAK,uBAAY,CAAC,UAAU;QAC9C,SAAS,CAAC,GAAG,KAAK,cAAc,EAChC;QACA,SAAS,CAAC,GAAG,GAAG,cAAc,CAAC;QAC/B,SAAS,CAAC,CAAC,GAAG,cAAc,CAAC;KAC9B;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAVD,gDAUC;AAED;;;;;GAKG;AACH,SAAgB,oBAAoB,CAAC,YAA0B;IAC7D,OAAO,YAAY,KAAK,uBAAY,CAAC,UAAU,CAAC;AAClD,CAAC;AAFD,oDAEC","sourcesContent":["import { existsSync, promises as fs } from 'fs';\nimport pathUtils from 'path';\nimport {\n PROPOSED_NAME_REGEX,\n NpmSnapFileNames,\n SnapManifest,\n NpmSnapPackageJson,\n validateSnapJsonFile,\n readJsonFile,\n deepClone,\n} from '@metamask/snap-utils';\nimport initPackageJson from 'init-package-json';\nimport mkdirp from 'mkdirp';\nimport slash from 'slash';\nimport { Arguments } from 'yargs';\nimport { YargsArgs } from '../../types/yargs';\nimport {\n CONFIG_FILE,\n logError,\n logWarning,\n prompt,\n trimPathString,\n} from '../../utils';\nimport { TemplateType } from '../../builders';\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 * @param argv - Yargs arguments object.\n * @returns The contents of the `package.json` file.\n */\nexport async function asyncPackageInit(\n argv: YargsArgs,\n): Promise<Readonly<NpmSnapPackageJson>> {\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(\n process.cwd(),\n '',\n {\n 'init.main': argv.src,\n },\n (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve(data);\n }\n },\n );\n });\n}\n\nconst YES = 'yes';\nconst YES_VALUES = new Set([YES, 'y']);\n\n/**\n * Checks if user input provided over a prompt is \"yes\", i.e., if the value is\n * truthy and in the {@link YES_VALUES} set.\n *\n * @param userInput - The user input to check.\n * @returns `true` if the user input is \"yes\", `false` otherwise.\n */\nfunction isYes(userInput: string | undefined) {\n return userInput && YES_VALUES.has(userInput.toLowerCase());\n}\n\nconst DEFAULT_PERMISSION_KEY = 'snap_confirm';\n\n/**\n * Get the default permissions to write to the snap manifest.\n *\n * @returns An object containing the default permissions.\n */\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 * @returns A tuple of the resulting Snap manifest object and a new `argv`\n * object 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 /**\n * Get the final snap manifest object and return it, along with the dist and\n * file names.\n *\n * @returns A tuple of the resulting snap manifest object and an object\n * containing the dist and file names.\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 iconPath: 'images/icon.svg',\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\n/**\n * In case when TypeScript version is used, default source file\n * will be updated if previous was not correct.\n *\n * @param yargsArgv - The Yargs arguments object.\n * @returns Modified Yargs arguments object.\n */\nexport function correctDefaultArgs(yargsArgv: Arguments): Arguments {\n if (\n yargsArgv.template === TemplateType.TypeScript &&\n yargsArgv.src === 'src/index.js'\n ) {\n yargsArgv.src = 'src/index.ts';\n yargsArgv.s = 'src/index.ts';\n }\n\n return yargsArgv;\n}\n\n/**\n * Check if template argument is TemplateType.TypeScript.\n *\n * @param templateType - TemplateType value of the template argument passed from CLI.\n * @returns True or false.\n */\nexport function isTemplateTypescript(templateType: TemplateType): boolean {\n return templateType === TemplateType.TypeScript;\n}\n"]}
1
+ {"version":3,"file":"initUtils.js","sourceRoot":"","sources":["../../../src/cmds/init/initU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AE,QAAQ,EAAE,CAAC,CAAC;QAC/C,OAAO,IAAI,CAAC;KACb;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAPD,wCAOC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,SAAiB;IACjD,IAAI;QACF,IAAA,wBAAQ,EAAC,qCAAqC,EAAE;YAC9C,KAAK,EAAE,QAAQ;YACf,GAAG,EAAE,cAAS,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7C,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;KACb;IAAC,OAAO,GAAG,EAAE;QACZ,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAVD,8CAUC;AAED;;;;GAIG;AACI,KAAK,UAAU,OAAO,CAAC,SAAiB;IAC7C,IAAI;QACF,IAAA,wBAAQ,EAAC,UAAU,EAAE;YACnB,KAAK,EAAE,QAAQ;YACf,GAAG,EAAE,cAAS,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7C,CAAC,CAAC;KACJ;IAAC,OAAO,GAAG,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;KACrE;AACH,CAAC;AATD,0BASC;AAED;;;;GAIG;AACI,KAAK,UAAU,WAAW,CAAC,SAAiB;IACjD,IAAI;QACF,IAAA,wBAAQ,EAAC,cAAc,EAAE;YACvB,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;YAChB,GAAG,EAAE,cAAS,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7C,CAAC,CAAC;KACJ;IAAC,OAAO,GAAG,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;KAChE;AACH,CAAC;AATD,kCASC","sourcesContent":["import { promises as fs } from 'fs';\nimport { execSync } from 'child_process';\nimport pathUtils from 'path';\n\nexport const TEMPLATE_GIT_URL =\n 'https://github.com/MetaMask/template-snap-monorepo.git';\n\nexport const SNAP_LOCATION = 'packages/snap/';\n\n/**\n * Checks if the destination folder exists and if it's empty. Otherwise create it.\n *\n * @param directory - The desination folder.\n */\nexport async function prepareWorkingDirectory(\n directory: string,\n): Promise<void> {\n try {\n const isCurrentDirectory = directory === process.cwd();\n\n if (!isCurrentDirectory) {\n try {\n await fs.mkdir(directory, { recursive: true });\n } catch (err) {\n throw new Error('Init Error: Failed to create new directory.');\n }\n }\n\n const existingFiles = await fs.readdir(directory);\n\n if (existingFiles.length > 0) {\n throw new Error(`Directory ${directory} not empty.`);\n }\n } catch (err) {\n throw new Error(\n `Init Error: Failed to prepare working directory with message: ${err.message}`,\n );\n }\n}\n\n/**\n * Clones the template in a directory.\n *\n * @param directory - The directory to clone the template in.\n */\nexport async function cloneTemplate(directory: string) {\n try {\n execSync(`git clone --depth=1 ${TEMPLATE_GIT_URL} ${directory}`, {\n stdio: [2],\n });\n } catch (err) {\n throw new Error('Init Error: Failed to clone the template.');\n }\n}\n\n/**\n * Check if git is installed.\n *\n * @returns True if git is installed, or false otherwise.\n */\nexport function isGitInstalled() {\n try {\n execSync('git --version', { stdio: 'ignore' });\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Check if the actual working dir is a git repository.\n *\n * @param directory - The directory to check.\n * @returns True if it's a git repository otherwise false.\n */\nexport function isInGitRepository(directory: string) {\n try {\n execSync('git rev-parse --is-inside-work-tree', {\n stdio: 'ignore',\n cwd: pathUtils.resolve(__dirname, directory),\n });\n return true;\n } catch (err) {\n return false;\n }\n}\n\n/**\n * Init a git repository.\n *\n * @param directory - The directory to init.\n */\nexport async function gitInit(directory: string) {\n try {\n execSync('git init', {\n stdio: 'ignore',\n cwd: pathUtils.resolve(__dirname, directory),\n });\n } catch (err) {\n throw new Error('Init Error: Failed to init a new git repository.');\n }\n}\n\n/**\n * Install dependencies in a yarn project.\n *\n * @param directory - The directory containing the project.\n */\nexport async function yarnInstall(directory: string) {\n try {\n execSync('yarn install', {\n stdio: [0, 1, 2],\n cwd: pathUtils.resolve(__dirname, directory),\n });\n } catch (err) {\n throw new Error('Init Error: Failed to install dependencies.');\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.manifestHandler = void 0;
4
- const snap_utils_1 = require("@metamask/snap-utils");
4
+ const snaps_utils_1 = require("@metamask/snaps-utils");
5
5
  const ERROR_PREFIX = 'Manifest Error: ';
6
6
  /**
7
7
  * Validates a snap.manifest.json file. Attempts to fix the manifest and write
@@ -13,7 +13,7 @@ const ERROR_PREFIX = 'Manifest Error: ';
13
13
  */
14
14
  async function manifestHandler({ writeManifest }) {
15
15
  try {
16
- const { warnings, errors } = await (0, snap_utils_1.checkManifest)(process.cwd(), Boolean(writeManifest));
16
+ const { warnings, errors } = await (0, snaps_utils_1.checkManifest)(process.cwd(), Boolean(writeManifest));
17
17
  if (!writeManifest && errors.length > 0) {
18
18
  console.error(`${ERROR_PREFIX}The manifest is invalid.`);
19
19
  errors.forEach(logManifestError);
@@ -1 +1 @@
1
- {"version":3,"file":"manifestHandler.js","sourceRoot":"","sources":["../../../src/cmds/manifest/manifestHandler.ts"],"names":[],"mappings":";;;AAAA,qDAAqD;AAGrD,MAAM,YAAY,GAAG,kBAAkB,CAAC;AAExC;;;;;;;GAOG;AACI,KAAK,UAAU,eAAe,CAAC,EAAE,aAAa,EAAa;IAChE,IAAI;QACF,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,IAAA,0BAAa,EAC9C,OAAO,CAAC,GAAG,EAAE,EACb,OAAO,CAAC,aAAa,CAAC,CACvB,CAAC;QAEF,IAAI,CAAC,aAAa,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,OAAO,CAAC,KAAK,CAAC,GAAG,YAAY,0BAA0B,CAAC,CAAC;YACzD,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;YAEjC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACjB;QAED,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YACvB,OAAO,CAAC,GAAG,CACT,6EAA6E,CAC9E,CAAC;YACF,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;SACtC;KACF;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,GAAG,YAAY,GAAG,KAAK,EAAE,CAAC,CAAC;KAC5C;AACH,CAAC;AAvBD,0CAuBC;AAED;;;;GAIG;AACH,SAAS,kBAAkB,CAAC,OAAe;IACzC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE;QAClC,OAAO,CAAC,GAAG,CAAC,qBAAqB,OAAO,EAAE,CAAC,CAAC;KAC7C;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,gBAAgB,CAAC,OAAe;IACvC,OAAO,CAAC,KAAK,CAAC,GAAG,YAAY,GAAG,OAAO,EAAE,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import { checkManifest } from '@metamask/snap-utils';\nimport { YargsArgs } from '../../types/yargs';\n\nconst ERROR_PREFIX = 'Manifest Error: ';\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param argv - The Yargs `argv` object.\n * @param argv.writeManifest - Whether to write the fixed manifest to disk.\n */\nexport async function manifestHandler({ writeManifest }: YargsArgs) {\n try {\n const { warnings, errors } = await checkManifest(\n process.cwd(),\n Boolean(writeManifest),\n );\n\n if (!writeManifest && errors.length > 0) {\n console.error(`${ERROR_PREFIX}The manifest is invalid.`);\n errors.forEach(logManifestError);\n\n process.exit(1);\n }\n\n if (warnings.length > 0) {\n console.log(\n 'Manifest Warning: Validation of snap.manifest.json completed with warnings.',\n );\n warnings.forEach(logManifestWarning);\n }\n } catch (error) {\n throw new Error(`${ERROR_PREFIX}${error}`);\n }\n}\n\n/**\n * Logs a manifest warning, if `suppressWarnings` is not enabled.\n *\n * @param message - The message to log.\n */\nfunction logManifestWarning(message: string) {\n if (!global.snaps.suppressWarnings) {\n console.log(`Manifest Warning: ${message}`);\n }\n}\n\n/**\n * Logs a manifest error.\n *\n * @param message - The message to log.\n */\nfunction logManifestError(message: string) {\n console.error(`${ERROR_PREFIX}${message}`);\n}\n"]}
1
+ {"version":3,"file":"manifestHandler.js","sourceRoot":"","sources":["../../../src/cmds/manifest/manifestHandler.ts"],"names":[],"mappings":";;;AAAA,uDAAsD;AAGtD,MAAM,YAAY,GAAG,kBAAkB,CAAC;AAExC;;;;;;;GAOG;AACI,KAAK,UAAU,eAAe,CAAC,EAAE,aAAa,EAAa;IAChE,IAAI;QACF,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,IAAA,2BAAa,EAC9C,OAAO,CAAC,GAAG,EAAE,EACb,OAAO,CAAC,aAAa,CAAC,CACvB,CAAC;QAEF,IAAI,CAAC,aAAa,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,OAAO,CAAC,KAAK,CAAC,GAAG,YAAY,0BAA0B,CAAC,CAAC;YACzD,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;YAEjC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACjB;QAED,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YACvB,OAAO,CAAC,GAAG,CACT,6EAA6E,CAC9E,CAAC;YACF,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;SACtC;KACF;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CAAC,GAAG,YAAY,GAAG,KAAK,EAAE,CAAC,CAAC;KAC5C;AACH,CAAC;AAvBD,0CAuBC;AAED;;;;GAIG;AACH,SAAS,kBAAkB,CAAC,OAAe;IACzC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE;QAClC,OAAO,CAAC,GAAG,CAAC,qBAAqB,OAAO,EAAE,CAAC,CAAC;KAC7C;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,gBAAgB,CAAC,OAAe;IACvC,OAAO,CAAC,KAAK,CAAC,GAAG,YAAY,GAAG,OAAO,EAAE,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import { checkManifest } from '@metamask/snaps-utils';\nimport { YargsArgs } from '../../types/yargs';\n\nconst ERROR_PREFIX = 'Manifest Error: ';\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param argv - The Yargs `argv` object.\n * @param argv.writeManifest - Whether to write the fixed manifest to disk.\n */\nexport async function manifestHandler({ writeManifest }: YargsArgs) {\n try {\n const { warnings, errors } = await checkManifest(\n process.cwd(),\n Boolean(writeManifest),\n );\n\n if (!writeManifest && errors.length > 0) {\n console.error(`${ERROR_PREFIX}The manifest is invalid.`);\n errors.forEach(logManifestError);\n\n process.exit(1);\n }\n\n if (warnings.length > 0) {\n console.log(\n 'Manifest Warning: Validation of snap.manifest.json completed with warnings.',\n );\n warnings.forEach(logManifestWarning);\n }\n } catch (error) {\n throw new Error(`${ERROR_PREFIX}${error}`);\n }\n}\n\n/**\n * Logs a manifest warning, if `suppressWarnings` is not enabled.\n *\n * @param message - The message to log.\n */\nfunction logManifestWarning(message: string) {\n if (!global.snaps.suppressWarnings) {\n console.log(`Manifest Warning: ${message}`);\n }\n}\n\n/**\n * Logs a manifest error.\n *\n * @param message - The message to log.\n */\nfunction logManifestError(message: string) {\n console.error(`${ERROR_PREFIX}${message}`);\n}\n"]}
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.serve = void 0;
7
7
  const http_1 = __importDefault(require("http"));
8
8
  const serve_handler_1 = __importDefault(require("serve-handler"));
9
- const snap_utils_1 = require("@metamask/snap-utils");
9
+ const snaps_utils_1 = require("@metamask/snaps-utils");
10
10
  const serveUtils_1 = require("./serveUtils");
11
11
  /**
12
12
  * Starts a local, static HTTP server on the given port with the given root
@@ -18,7 +18,7 @@ const serveUtils_1 = require("./serveUtils");
18
18
  */
19
19
  async function serve(argv) {
20
20
  const { port, root: rootDir } = argv;
21
- await (0, snap_utils_1.validateDirPath)(rootDir, true);
21
+ await (0, snaps_utils_1.validateDirPath)(rootDir, true);
22
22
  console.log(`\nStarting server...`);
23
23
  const server = http_1.default.createServer(async (req, res) => {
24
24
  await (0, serve_handler_1.default)(req, res, {
@@ -1 +1 @@
1
- {"version":3,"file":"serveHandler.js","sourceRoot":"","sources":["../../../src/cmds/serve/serveHandler.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AACxB,kEAAyC;AACzC,qDAAuD;AAEvD,6CAA8E;AAE9E;;;;;;;GAOG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAErC,MAAM,IAAA,4BAAe,EAAC,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,IAAA,uBAAY,EAAC,GAAG,EAAE,GAAG,EAAE;YAC3B,MAAM,EAAE,OAAiB;YACzB,OAAO,EAAE;gBACP;oBACE,MAAM,EAAE,MAAM;oBACd,OAAO,EAAE;wBACP;4BACE,GAAG,EAAE,eAAe;4BACpB,KAAK,EAAE,UAAU;yBAClB;wBACD;4BACE,GAAG,EAAE,6BAA6B;4BAClC,KAAK,EAAE,GAAG;yBACX;qBACF;iBACF;aACF;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,CAAC,IAAA,+BAAkB,EAAC,IAAI,CAAC,CAAC,CAAC;IAExD,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,IAAA,uBAAU,EAAC,OAAO,CAAC,CAAC,CAAC;IAEvD,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;QAC3B,IAAA,2BAAc,EAAC,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;AAzCD,sBAyCC","sourcesContent":["import http from 'http';\nimport serveHandler from 'serve-handler';\nimport { validateDirPath } from '@metamask/snap-utils';\nimport { YargsArgs } from '../../types/yargs';\nimport { logRequest, logServerError, logServerListening } from './serveUtils';\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 */\nexport async 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 key: 'Access-Control-Allow-Origin',\n value: '*',\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"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AAC,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;AAzCD,sBAyCC","sourcesContent":["import http from 'http';\nimport serveHandler from 'serve-handler';\nimport { validateDirPath } from '@metamask/snaps-utils';\nimport { YargsArgs } from '../../types/yargs';\nimport { logRequest, logServerError, logServerListening } from './serveUtils';\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 */\nexport async 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 key: 'Access-Control-Allow-Origin',\n value: '*',\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"]}
@@ -5,7 +5,7 @@ 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 snap_utils_1 = require("@metamask/snap-utils");
8
+ const snaps_utils_1 = require("@metamask/snaps-utils");
9
9
  const utils_1 = require("../../utils");
10
10
  const bundle_1 = require("../build/bundle");
11
11
  const evalHandler_1 = require("../eval/evalHandler");
@@ -26,12 +26,12 @@ const serveHandler_1 = require("../serve/serveHandler");
26
26
  async function watch(argv) {
27
27
  const { dist, eval: shouldEval, manifest, outfileName, src, serve: shouldServe, } = argv;
28
28
  if (outfileName) {
29
- (0, snap_utils_1.validateOutfileName)(outfileName);
29
+ (0, snaps_utils_1.validateOutfileName)(outfileName);
30
30
  }
31
- await (0, snap_utils_1.validateFilePath)(src);
32
- await (0, snap_utils_1.validateDirPath)(dist, true);
31
+ await (0, snaps_utils_1.validateFilePath)(src);
32
+ await (0, snaps_utils_1.validateDirPath)(dist, true);
33
33
  const rootDir = src.indexOf('/') === -1 ? '.' : src.substring(0, src.lastIndexOf('/') + 1);
34
- const outfilePath = (0, snap_utils_1.getOutfilePath)(dist, outfileName);
34
+ const outfilePath = (0, snaps_utils_1.getOutfilePath)(dist, outfileName);
35
35
  const buildSnap = async (path, logMessage) => {
36
36
  if (logMessage !== undefined) {
37
37
  console.log(logMessage);
@@ -1 +1 @@
1
- {"version":3,"file":"watchHandler.js","sourceRoot":"","sources":["../../../src/cmds/watch/watchHandler.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAChC,qDAK8B;AAE9B,uCAAmD;AACnD,4CAAyC;AACzC,qDAAkD;AAClD,iEAA8D;AAC9D,wDAA8C;AAE9C;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EACJ,IAAI,EACJ,IAAI,EAAE,UAAU,EAChB,QAAQ,EACR,WAAW,EACX,GAAG,EACH,KAAK,EAAE,WAAW,GACnB,GAAG,IAAI,CAAC;IACT,IAAI,WAAW,EAAE;QACf,IAAA,gCAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,6BAAgB,EAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAA,4BAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,MAAM,OAAO,GACX,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG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AAI,WAAW,EAAE;YACf,MAAM,IAAA,oBAAK,EAAC,IAAI,CAAC,CAAC;SACnB;IACH,CAAC,CAAC;SACD,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,IAAA,gBAAQ,EAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC,CAAC;SAED,GAAG,CAAC,OAAO,CAAC,CAAC;IAEhB,OAAO,CAAC,GAAG,CAAC,aAAa,OAAO,kBAAkB,CAAC,CAAC;AACtD,CAAC;AA5ED,sBA4EC","sourcesContent":["import chokidar from 'chokidar';\nimport {\n getOutfilePath,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '@metamask/snap-utils';\nimport { YargsArgs } from '../../types/yargs';\nimport { loadConfig, logError } from '../../utils';\nimport { bundle } from '../build/bundle';\nimport { evalHandler } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\nimport { serve } from '../serve/serveHandler';\n\n/**\n * Watch a directory and its subdirectories for changes, and build when files\n * are added or changed.\n *\n * Ignores 'node_modules' and dotfiles.\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - Arguments as an object generated by Yargs.\n * @param argv.src - The source file path.\n * @param argv.dist - The output directory path.\n * @param argv.'outfileName' - The output file name.\n */\nexport async function watch(argv: YargsArgs): Promise<void> {\n const {\n dist,\n eval: shouldEval,\n manifest,\n outfileName,\n src,\n serve: shouldServe,\n } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n const rootDir =\n src.indexOf('/') === -1 ? '.' : src.substring(0, src.lastIndexOf('/') + 1);\n const outfilePath = getOutfilePath(dist, outfileName as string);\n\n const buildSnap = async (path?: string, logMessage?: string) => {\n if (logMessage !== undefined) {\n console.log(logMessage);\n }\n\n try {\n await bundle(src, outfilePath, argv, loadConfig().bundlerCustomizer);\n\n if (manifest) {\n await manifestHandler(argv);\n }\n\n if (shouldEval) {\n await evalHandler({ ...argv, bundle: outfilePath });\n }\n } catch (error) {\n logError(\n `Error ${\n path === undefined\n ? 'during initial build'\n : `while processing \"${path}\"`\n }.`,\n error,\n );\n }\n };\n\n chokidar\n .watch(rootDir, {\n ignoreInitial: true,\n ignored: [\n '**/node_modules/**',\n `**/${dist}/**`,\n `**/test/**`,\n `**/tests/**`,\n `**/*.test.js`,\n `**/*.test.ts`,\n /* istanbul ignore next */\n (str: string) => str !== '.' && str.startsWith('.'),\n ],\n })\n\n .on('ready', async () => {\n await buildSnap();\n if (shouldServe) {\n await serve(argv);\n }\n })\n .on('add', (path) => buildSnap(path, `File added: ${path}`))\n .on('change', (path) => buildSnap(path, `File changed: ${path}`))\n .on('unlink', (path) => console.log(`File removed: ${path}`))\n .on('error', (error: Error) => {\n logError(`Watcher error: ${error.message}`, error);\n })\n\n .add(rootDir);\n\n console.log(`Watching '${rootDir}' for changes...`);\n}\n"]}
1
+ {"version":3,"file":"watchHandler.js","sourceRoot":"","sources":["../../../src/cmds/watch/watchHandler.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAgC;AAChC,uDAK+B;AAE/B,uCAAmD;AACnD,4CAAyC;AACzC,qDAAkD;AAClD,iEAA8D;AAC9D,wDAA8C;AAE9C;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EACJ,IAAI,EACJ,IAAI,EAA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AEF,kBAAQ;SACL,KAAK,CAAC,OAAO,EAAE;QACd,aAAa,EAAE,IAAI;QACnB,OAAO,EAAE;YACP,oBAAoB;YACpB,MAAM,IAAI,KAAK;YACf,YAAY;YACZ,aAAa;YACb,cAAc;YACd,cAAc;YACd,0BAA0B;YAC1B,CAAC,GAAW,EAAE,EAAE,CAAC,GAAG,KAAK,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC;SACpD;KACF,CAAC;SAED,EAAE,CAAC,OAAO,EAAE,KAAK,IAAI,EAAE;QACtB,MAAM,SAAS,EAAE,CAAC;QAClB,IAAI,WAAW,EAAE;YACf,MAAM,IAAA,oBAAK,EAAC,IAAI,CAAC,CAAC;SACnB;IACH,CAAC,CAAC;SACD,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,IAAA,gBAAQ,EAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC,CAAC;SAED,GAAG,CAAC,OAAO,CAAC,CAAC;IAEhB,OAAO,CAAC,GAAG,CAAC,aAAa,OAAO,kBAAkB,CAAC,CAAC;AACtD,CAAC;AA5ED,sBA4EC","sourcesContent":["import chokidar from 'chokidar';\nimport {\n getOutfilePath,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '@metamask/snaps-utils';\nimport { YargsArgs } from '../../types/yargs';\nimport { loadConfig, logError } from '../../utils';\nimport { bundle } from '../build/bundle';\nimport { evalHandler } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\nimport { serve } from '../serve/serveHandler';\n\n/**\n * Watch a directory and its subdirectories for changes, and build when files\n * are added or changed.\n *\n * Ignores 'node_modules' and dotfiles.\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - Arguments as an object generated by Yargs.\n * @param argv.src - The source file path.\n * @param argv.dist - The output directory path.\n * @param argv.'outfileName' - The output file name.\n */\nexport async function watch(argv: YargsArgs): Promise<void> {\n const {\n dist,\n eval: shouldEval,\n manifest,\n outfileName,\n src,\n serve: shouldServe,\n } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n const rootDir =\n src.indexOf('/') === -1 ? '.' : src.substring(0, src.lastIndexOf('/') + 1);\n const outfilePath = getOutfilePath(dist, outfileName as string);\n\n const buildSnap = async (path?: string, logMessage?: string) => {\n if (logMessage !== undefined) {\n console.log(logMessage);\n }\n\n try {\n await bundle(src, outfilePath, argv, loadConfig().bundlerCustomizer);\n\n if (manifest) {\n await manifestHandler(argv);\n }\n\n if (shouldEval) {\n await evalHandler({ ...argv, bundle: outfilePath });\n }\n } catch (error) {\n logError(\n `Error ${\n path === undefined\n ? 'during initial build'\n : `while processing \"${path}\"`\n }.`,\n error,\n );\n }\n };\n\n chokidar\n .watch(rootDir, {\n ignoreInitial: true,\n ignored: [\n '**/node_modules/**',\n `**/${dist}/**`,\n `**/test/**`,\n `**/tests/**`,\n `**/*.test.js`,\n `**/*.test.ts`,\n /* istanbul ignore next */\n (str: string) => str !== '.' && str.startsWith('.'),\n ],\n })\n\n .on('ready', async () => {\n await buildSnap();\n if (shouldServe) {\n await serve(argv);\n }\n })\n .on('add', (path) => buildSnap(path, `File added: ${path}`))\n .on('change', (path) => buildSnap(path, `File changed: ${path}`))\n .on('unlink', (path) => console.log(`File removed: ${path}`))\n .on('error', (error: Error) => {\n logError(`Watcher error: ${error.message}`, error);\n })\n\n .add(rootDir);\n\n console.log(`Watching '${rootDir}' for changes...`);\n}\n"]}
@@ -1,3 +1,2 @@
1
1
  export * from './misc';
2
- export * from './readline';
3
2
  export * from './snap-config';
@@ -15,6 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./misc"), exports);
18
- __exportStar(require("./readline"), exports);
19
18
  __exportStar(require("./snap-config"), exports);
20
19
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,yCAAuB;AACvB,6CAA2B;AAC3B,gDAA8B","sourcesContent":["export * from './misc';\nexport * from './readline';\nexport * from './snap-config';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,yCAAuB;AACvB,gDAA8B","sourcesContent":["export * from './misc';\nexport * from './snap-config';\n"]}
@@ -32,7 +32,7 @@ export declare function sanitizeInputs(argv: Arguments): void;
32
32
  * @param msg - The error message.
33
33
  * @param err - The original error.
34
34
  */
35
- export declare function logError(msg: string, err?: Error): void;
35
+ export declare function logError(msg: string | null, err?: Error): void;
36
36
  /**
37
37
  * Logs a warning message to console.
38
38
  *
@@ -99,10 +99,15 @@ exports.sanitizeInputs = sanitizeInputs;
99
99
  * @param err - The original error.
100
100
  */
101
101
  function logError(msg, err) {
102
- console.error(msg);
102
+ if (msg !== null) {
103
+ console.error(msg);
104
+ }
103
105
  if (err && global.snaps.verboseErrors) {
104
106
  console.error(err);
105
107
  }
108
+ if (msg === null && (!err || (err && !global.snaps.verboseErrors))) {
109
+ console.error('Unknown error.');
110
+ }
106
111
  }
107
112
  exports.logError = logError;
108
113
  /**