@metamask/snaps-cli 0.16.0 → 0.17.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 (69) hide show
  1. package/README.md +2 -0
  2. package/dist/builders.d.ts +6 -0
  3. package/dist/builders.js +20 -1
  4. package/dist/builders.js.map +1 -1
  5. package/dist/cli.d.ts +7 -0
  6. package/dist/cli.js +8 -0
  7. package/dist/cli.js.map +1 -1
  8. package/dist/cmds/build/buildHandler.d.ts +4 -4
  9. package/dist/cmds/build/buildHandler.js +4 -4
  10. package/dist/cmds/build/buildHandler.js.map +1 -1
  11. package/dist/cmds/build/bundle.d.ts +3 -2
  12. package/dist/cmds/build/bundle.js +3 -2
  13. package/dist/cmds/build/bundle.js.map +1 -1
  14. package/dist/cmds/build/utils.d.ts +21 -8
  15. package/dist/cmds/build/utils.js +21 -8
  16. package/dist/cmds/build/utils.js.map +1 -1
  17. package/dist/cmds/eval/eval-worker.js +18 -16
  18. package/dist/cmds/eval/eval-worker.js.map +1 -1
  19. package/dist/cmds/eval/evalHandler.d.ts +7 -0
  20. package/dist/cmds/eval/evalHandler.js +7 -0
  21. package/dist/cmds/eval/evalHandler.js.map +1 -1
  22. package/dist/cmds/eval/mock.d.ts +11 -0
  23. package/dist/cmds/eval/mock.js +36 -0
  24. package/dist/cmds/eval/mock.js.map +1 -1
  25. package/dist/cmds/eval/workerEval.d.ts +7 -0
  26. package/dist/cmds/eval/workerEval.js +11 -6
  27. package/dist/cmds/eval/workerEval.js.map +1 -1
  28. package/dist/cmds/init/index.js +13 -1
  29. package/dist/cmds/init/index.js.map +1 -1
  30. package/dist/cmds/init/init-template.json +5 -1
  31. package/dist/cmds/init/initHandler.d.ts +11 -0
  32. package/dist/cmds/init/initHandler.js +38 -3
  33. package/dist/cmds/init/initHandler.js.map +1 -1
  34. package/dist/cmds/init/initUtils.d.ts +21 -4
  35. package/dist/cmds/init/initUtils.js +55 -7
  36. package/dist/cmds/init/initUtils.js.map +1 -1
  37. package/dist/cmds/manifest/manifestHandler.d.ts +1 -0
  38. package/dist/cmds/manifest/manifestHandler.js +6 -0
  39. package/dist/cmds/manifest/manifestHandler.js.map +1 -1
  40. package/dist/cmds/serve/index.js +2 -44
  41. package/dist/cmds/serve/index.js.map +1 -1
  42. package/dist/cmds/serve/serveHandler.d.ts +10 -0
  43. package/dist/cmds/serve/serveHandler.js +51 -0
  44. package/dist/cmds/serve/serveHandler.js.map +1 -0
  45. package/dist/cmds/serve/serveUtils.d.ts +17 -0
  46. package/dist/cmds/serve/serveUtils.js +17 -0
  47. package/dist/cmds/serve/serveUtils.js.map +1 -1
  48. package/dist/cmds/watch/index.js +3 -0
  49. package/dist/cmds/watch/index.js.map +1 -1
  50. package/dist/cmds/watch/watchHandler.d.ts +4 -4
  51. package/dist/cmds/watch/watchHandler.js +12 -6
  52. package/dist/cmds/watch/watchHandler.js.map +1 -1
  53. package/dist/utils/fs.d.ts +5 -5
  54. package/dist/utils/fs.js +5 -5
  55. package/dist/utils/fs.js.map +1 -1
  56. package/dist/utils/misc.d.ts +16 -13
  57. package/dist/utils/misc.js +16 -13
  58. package/dist/utils/misc.js.map +1 -1
  59. package/dist/utils/readline.d.ts +25 -0
  60. package/dist/utils/readline.js +25 -0
  61. package/dist/utils/readline.js.map +1 -1
  62. package/dist/utils/snap-config.d.ts +14 -0
  63. package/dist/utils/snap-config.js +15 -1
  64. package/dist/utils/snap-config.js.map +1 -1
  65. package/dist/utils/validate-fs.d.ts +19 -18
  66. package/dist/utils/validate-fs.js +21 -20
  67. package/dist/utils/validate-fs.js.map +1 -1
  68. package/package.json +11 -11
  69. package/CHANGELOG.md +0 -227
package/README.md CHANGED
@@ -34,6 +34,8 @@ Options:
34
34
  Examples:
35
35
  mm-snap init Initialize a snap project in the
36
36
  current directory
37
+ mm-snap init --template javascript Initialize a snap JavaScript project
38
+ in the current directory
37
39
  mm-snap build -s src/index.js -d out Build 'src/index.js' as
38
40
  './out/bundle.js'
39
41
  mm-snap build -s src/index.js -d out -n Build 'src/index.js' as
@@ -16,11 +16,17 @@ export declare type SnapsCliBuilders = {
16
16
  readonly depsToTranspile: Readonly<Options>;
17
17
  readonly verboseErrors: Readonly<Options>;
18
18
  readonly writeManifest: Readonly<Options>;
19
+ readonly serve: Readonly<Options>;
20
+ readonly template: Readonly<Options>;
19
21
  };
20
22
  export declare enum TranspilationModes {
21
23
  localAndDeps = "localAndDeps",
22
24
  localOnly = "localOnly",
23
25
  none = "none"
24
26
  }
27
+ export declare enum TemplateType {
28
+ TypeScript = "typescript",
29
+ JavaScript = "javascript"
30
+ }
25
31
  declare const builders: SnapsCliBuilders;
26
32
  export default builders;
package/dist/builders.js CHANGED
@@ -1,12 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TranspilationModes = void 0;
3
+ exports.TemplateType = exports.TranspilationModes = void 0;
4
4
  var TranspilationModes;
5
5
  (function (TranspilationModes) {
6
6
  TranspilationModes["localAndDeps"] = "localAndDeps";
7
7
  TranspilationModes["localOnly"] = "localOnly";
8
8
  TranspilationModes["none"] = "none";
9
9
  })(TranspilationModes = exports.TranspilationModes || (exports.TranspilationModes = {}));
10
+ var TemplateType;
11
+ (function (TemplateType) {
12
+ TemplateType["TypeScript"] = "typescript";
13
+ TemplateType["JavaScript"] = "javascript";
14
+ })(TemplateType = exports.TemplateType || (exports.TemplateType = {}));
10
15
  const builders = {
11
16
  bundle: {
12
17
  alias: 'b',
@@ -124,6 +129,20 @@ const builders = {
124
129
  demandOption: false,
125
130
  default: true,
126
131
  },
132
+ serve: {
133
+ describe: 'Serve Snap file(s) locally for testing',
134
+ type: 'boolean',
135
+ demandOption: false,
136
+ default: true,
137
+ },
138
+ template: {
139
+ alias: 't',
140
+ describe: 'Specify which template to use (TypeScript or JavaScript)',
141
+ type: 'string',
142
+ demandOption: false,
143
+ default: TemplateType.TypeScript,
144
+ choices: Object.values(TemplateType),
145
+ },
127
146
  };
128
147
  exports.default = builders;
129
148
  //# sourceMappingURL=builders.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"builders.js","sourceRoot":"","sources":["../src/builders.ts"],"names":[],"mappings":";;;AAqBA,IAAY,kBAIX;AAJD,WAAY,kBAAkB;IAC5B,mDAA6B,CAAA;IAC7B,6CAAuB,CAAA;IACvB,mCAAa,CAAA;AACf,CAAC,EAJW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAI7B;AAED,MAAM,QAAQ,GAAqB;IACjC,MAAM,EAAE;QACN,KAAK,EAAE,GAAG;QACV,QAAQ,EAAE,kBAAkB;QAC5B,IAAI,EAAE,QAAQ;QACd,YAAY,EAAE,IAAI;QAClB,SAAS,EAAE,IAAI;QACf,OAAO,EAAE,gBAAgB;KAC1B;IAED,IAAI,EAAE;QACJ,KAAK,EAAE,GAAG;QACV,QAAQ,EAAE,kBAAkB;QAC5B,IAAI,EAAE,QAAQ;QACd,YAAY,EAAE,IAAI;QAClB,SAAS,EAAE,IAAI;QACf,OAAO,EAAE,MAAM;KAChB;IAED,IAAI,EAAE;QACJ,KAAK,EAAE,GAAG;QACV,QAAQ,EAAE,wCAAwC;QAClD,IAAI,EAAE,SAAS;QACf,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,IAAI;KACd;IAED,QAAQ,EAAE;QACR,KAAK,EAAE,GAAG;QACV,QAAQ,EAAE,6BAA6B;QACvC,IAAI,EAAE,SAAS;QACf,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,IAAI;KACd;IAED,IAAI,EAAE;QACJ,KAAK,EAAE,GAAG;QACV,QAAQ,EAAE,+BAA+B;QACzC,IAAI,EAAE,QAAQ;QACd,YAAY,EAAE,IAAI;QAClB,OAAO,EAAE,IAAI;QACb,MAAM,EAAE,CAAC,GAAY,EAAE,EAAE;YACvB,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;YAC9C,IAAI,MAAM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AI,EAAE,SAAS;QACf,QAAQ,EACN,mFAAmF;QACrF,YAAY,EAAE,IAAI;QAClB,OAAO,EAAE,IAAI;KACd;IAED,eAAe,EAAE;QACf,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,yCAAyC;QACnD,YAAY,EAAE,KAAK;KACpB;IAED,aAAa,EAAE;QACb,IAAI,EAAE,SAAS;QACf,QAAQ,EAAE,yBAAyB;QACnC,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,IAAI;KACd;IAED,aAAa,EAAE;QACb,QAAQ,EAAE,kDAAkD;QAC5D,IAAI,EAAE,SAAS;QACf,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,IAAI;KACd;CACF,CAAC;AAEF,kBAAe,QAAQ,CAAC","sourcesContent":["import { Options } from 'yargs';\n\nexport type SnapsCliBuilders = {\n readonly bundle: Readonly<Options>;\n readonly dist: Readonly<Options>;\n readonly eval: Readonly<Options>;\n readonly manifest: Readonly<Options>;\n readonly outfileName: Readonly<Options>;\n readonly port: Readonly<Options>;\n readonly root: Readonly<Options>;\n readonly sourceMaps: Readonly<Options>;\n readonly src: Readonly<Options>;\n readonly stripComments: Readonly<Options>;\n readonly suppressWarnings: Readonly<Options>;\n readonly transpilationMode: Readonly<Options>;\n readonly transformHtmlComments: Readonly<Options>;\n readonly depsToTranspile: Readonly<Options>;\n readonly verboseErrors: Readonly<Options>;\n readonly writeManifest: Readonly<Options>;\n};\n\nexport enum TranspilationModes {\n localAndDeps = 'localAndDeps',\n localOnly = 'localOnly',\n none = 'none',\n}\n\nconst builders: SnapsCliBuilders = {\n bundle: {\n alias: 'b',\n describe: 'Snap bundle file',\n type: 'string',\n demandOption: true,\n normalize: true,\n default: 'dist/bundle.js',\n },\n\n dist: {\n alias: 'd',\n describe: 'Output directory',\n type: 'string',\n demandOption: true,\n normalize: true,\n default: 'dist',\n },\n\n eval: {\n alias: 'e',\n describe: 'Attempt to evaluate Snap bundle in SES',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n\n manifest: {\n alias: 'm',\n describe: 'Validate snap.manifest.json',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n\n port: {\n alias: 'p',\n describe: 'Local server port for testing',\n type: 'number',\n demandOption: true,\n default: 8081,\n coerce: (arg: unknown) => {\n const port = Number.parseInt(String(arg), 10);\n if (Number.isNaN(port)) {\n throw new Error(`Invalid port: ${arg}`);\n }\n return port;\n },\n },\n\n outfileName: {\n alias: 'n',\n describe: 'Output file name',\n type: 'string',\n demandOption: false,\n default: 'bundle.js',\n },\n\n root: {\n alias: 'r',\n describe: 'Server root directory',\n type: 'string',\n demandOption: true,\n normalize: true,\n default: '.',\n },\n\n sourceMaps: {\n describe: 'Whether builds include sourcemaps',\n type: 'boolean',\n demandOption: false,\n default: false,\n },\n\n src: {\n alias: 's',\n describe: 'Source file',\n type: 'string',\n demandOption: true,\n normalize: true,\n default: 'src/index.js',\n },\n\n stripComments: {\n alias: 'strip',\n describe: 'Whether to remove code comments from the build output',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n\n suppressWarnings: {\n type: 'boolean',\n describe: 'Whether to suppress warnings',\n demandOption: false,\n default: false,\n },\n\n transpilationMode: {\n type: 'string',\n describe:\n 'Whether to use Babel to transpile all source code (including dependencies), local source code only, or nothing.',\n demandOption: false,\n default: TranspilationModes.localOnly,\n choices: Object.values(TranspilationModes),\n },\n\n transformHtmlComments: {\n type: 'boolean',\n describe:\n 'Whether to break up HTML comment tokens wherever they appear in your source code.',\n demandOption: true,\n default: true,\n },\n\n depsToTranspile: {\n type: 'array',\n describe: 'Transpile only the listed dependencies.',\n demandOption: false,\n },\n\n verboseErrors: {\n type: 'boolean',\n describe: 'Display original errors',\n demandOption: false,\n default: true,\n },\n\n writeManifest: {\n describe: 'Make necessary changes to the Snap manifest file',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n};\n\nexport default builders;\n"]}
1
+ {"version":3,"file":"builders.js","sourceRoot":"","sources":["../src/builders.ts"],"names":[],"mappings":";;;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qBAAqB,EAAE;QACrB,IAAI,EAAE,SAAS;QACf,QAAQ,EACN,mFAAmF;QACrF,YAAY,EAAE,IAAI;QAClB,OAAO,EAAE,IAAI;KACd;IAED,eAAe,EAAE;QACf,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,yCAAyC;QACnD,YAAY,EAAE,KAAK;KACpB;IAED,aAAa,EAAE;QACb,IAAI,EAAE,SAAS;QACf,QAAQ,EAAE,yBAAyB;QACnC,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,IAAI;KACd;IAED,aAAa,EAAE;QACb,QAAQ,EAAE,kDAAkD;QAC5D,IAAI,EAAE,SAAS;QACf,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,IAAI;KACd;IAED,KAAK,EAAE;QACL,QAAQ,EAAE,wCAAwC;QAClD,IAAI,EAAE,SAAS;QACf,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,IAAI;KACd;IAED,QAAQ,EAAE;QACR,KAAK,EAAE,GAAG;QACV,QAAQ,EAAE,0DAA0D;QACpE,IAAI,EAAE,QAAQ;QACd,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,YAAY,CAAC,UAAU;QAChC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC;KACrC;CACF,CAAC;AAEF,kBAAe,QAAQ,CAAC","sourcesContent":["import { Options } from 'yargs';\n\nexport type SnapsCliBuilders = {\n readonly bundle: Readonly<Options>;\n readonly dist: Readonly<Options>;\n readonly eval: Readonly<Options>;\n readonly manifest: Readonly<Options>;\n readonly outfileName: Readonly<Options>;\n readonly port: Readonly<Options>;\n readonly root: Readonly<Options>;\n readonly sourceMaps: Readonly<Options>;\n readonly src: Readonly<Options>;\n readonly stripComments: Readonly<Options>;\n readonly suppressWarnings: Readonly<Options>;\n readonly transpilationMode: Readonly<Options>;\n readonly transformHtmlComments: Readonly<Options>;\n readonly depsToTranspile: Readonly<Options>;\n readonly verboseErrors: Readonly<Options>;\n readonly writeManifest: Readonly<Options>;\n readonly serve: Readonly<Options>;\n readonly template: Readonly<Options>;\n};\n\nexport enum TranspilationModes {\n localAndDeps = 'localAndDeps',\n localOnly = 'localOnly',\n none = 'none',\n}\n\nexport enum TemplateType {\n TypeScript = 'typescript',\n JavaScript = 'javascript',\n}\n\nconst builders: SnapsCliBuilders = {\n bundle: {\n alias: 'b',\n describe: 'Snap bundle file',\n type: 'string',\n demandOption: true,\n normalize: true,\n default: 'dist/bundle.js',\n },\n\n dist: {\n alias: 'd',\n describe: 'Output directory',\n type: 'string',\n demandOption: true,\n normalize: true,\n default: 'dist',\n },\n\n eval: {\n alias: 'e',\n describe: 'Attempt to evaluate Snap bundle in SES',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n\n manifest: {\n alias: 'm',\n describe: 'Validate snap.manifest.json',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n\n port: {\n alias: 'p',\n describe: 'Local server port for testing',\n type: 'number',\n demandOption: true,\n default: 8081,\n coerce: (arg: unknown) => {\n const port = Number.parseInt(String(arg), 10);\n if (Number.isNaN(port)) {\n throw new Error(`Invalid port: ${arg}`);\n }\n return port;\n },\n },\n\n outfileName: {\n alias: 'n',\n describe: 'Output file name',\n type: 'string',\n demandOption: false,\n default: 'bundle.js',\n },\n\n root: {\n alias: 'r',\n describe: 'Server root directory',\n type: 'string',\n demandOption: true,\n normalize: true,\n default: '.',\n },\n\n sourceMaps: {\n describe: 'Whether builds include sourcemaps',\n type: 'boolean',\n demandOption: false,\n default: false,\n },\n\n src: {\n alias: 's',\n describe: 'Source file',\n type: 'string',\n demandOption: true,\n normalize: true,\n default: 'src/index.js',\n },\n\n stripComments: {\n alias: 'strip',\n describe: 'Whether to remove code comments from the build output',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n\n suppressWarnings: {\n type: 'boolean',\n describe: 'Whether to suppress warnings',\n demandOption: false,\n default: false,\n },\n\n transpilationMode: {\n type: 'string',\n describe:\n 'Whether to use Babel to transpile all source code (including dependencies), local source code only, or nothing.',\n demandOption: false,\n default: TranspilationModes.localOnly,\n choices: Object.values(TranspilationModes),\n },\n\n transformHtmlComments: {\n type: 'boolean',\n describe:\n 'Whether to break up HTML comment tokens wherever they appear in your source code.',\n demandOption: true,\n default: true,\n },\n\n depsToTranspile: {\n type: 'array',\n describe: 'Transpile only the listed dependencies.',\n demandOption: false,\n },\n\n verboseErrors: {\n type: 'boolean',\n describe: 'Display original errors',\n demandOption: false,\n default: true,\n },\n\n writeManifest: {\n describe: 'Make necessary changes to the Snap manifest file',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n\n serve: {\n describe: 'Serve Snap file(s) locally for testing',\n type: 'boolean',\n demandOption: false,\n default: true,\n },\n\n template: {\n alias: 't',\n describe: 'Specify which template to use (TypeScript or JavaScript)',\n type: 'string',\n demandOption: false,\n default: TemplateType.TypeScript,\n choices: Object.values(TemplateType),\n },\n};\n\nexport default builders;\n"]}
package/dist/cli.d.ts CHANGED
@@ -1 +1,8 @@
1
+ /**
2
+ * The main CLI entry point function. This processes the command line args, and
3
+ * runs the appropriate function.
4
+ *
5
+ * @param argv - The raw command line arguments, i.e., `process.argv`.
6
+ * @param commands - The list of commands to use.
7
+ */
1
8
  export declare function cli(argv: string[], commands: any): void;
package/dist/cli.js CHANGED
@@ -7,6 +7,13 @@ exports.cli = void 0;
7
7
  const yargs_1 = __importDefault(require("yargs"));
8
8
  const builders_1 = __importDefault(require("./builders"));
9
9
  const utils_1 = require("./utils");
10
+ /**
11
+ * The main CLI entry point function. This processes the command line args, and
12
+ * runs the appropriate function.
13
+ *
14
+ * @param argv - The raw command line arguments, i.e., `process.argv`.
15
+ * @param commands - The list of commands to use.
16
+ */
10
17
  function cli(argv, commands) {
11
18
  const rawArgv = argv.slice(2);
12
19
  // eslint-disable-next-line @typescript-eslint/no-unused-expressions
@@ -14,6 +21,7 @@ function cli(argv, commands) {
14
21
  .scriptName('mm-snap')
15
22
  .usage('Usage: $0 <command> [options]')
16
23
  .example('$0 init', `\tInitialize a snap project in the current directory`)
24
+ .example('$0 init --template javascript', `\tInitialize a snap JavaScript project in the current directory`)
17
25
  .example('$0 build -s src/index.js -d out', `\tBuild 'src/index.js' as './out/bundle.js'`)
18
26
  .example('$0 build -s src/index.js -d out -n snap.js', `\tBuild 'src/index.js' as './out/snap.js'`)
19
27
  .example('$0 serve -r out', `\tServe files in './out' on port 8080`)
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;AAAA,kDAAyC;AAEzC,0DAAkC;AAClC,mCAMiB;AAEjB,SAAgB,GAAG,CAAC,IAAc,EAAE,QAAa;IAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,oEAAoE;IACpE,IAAA,eAAK,EAAC,OAAO,CAAC;SACX,UAAU,CAAC,SAAS,CAAC;SACrB,KAAK,CAAC,+BAA+B,CAAC;SAEtC,OAAO,CAAC,SAAS,EAAE,sDAAsD,CAAC;SAC1E,OAAO,CACN,iCAAiC,EACjC,6CAA6C,CAC9C;SACA,OAAO,CACN,4CAA4C,EAC5C,2CAA2C,CAC5C;SACA,OAAO,CAAC,iBAAiB,EAAE,uCAAuC,CAAC;SACnE,OAAO,CAAC,yBAAyB,EAAE,uCAAuC,CAAC;SAC3E,OAAO,CACN,iCAAiC,EACjC,gGAAgG,CACjG;SAEA,OAAO,CAAC,QAAQ,CAAC;SAEjB,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;SAE/C,MAAM,CAAC,kBAAkB,EAAE,kBAAQ,CAAC,gBAAgB,CAAC;SAErD,MAAM,EAAE;QAET,gEAAgE;QAChE,+EAA+E;QAC/E,0FAA0F;SACzF,UAAU,CACT,CAAC,CAAC,SAAoB,EAAE,aAA+B,EAAE,EAAE;QACzD,IAAA,mBAAW,EAAC,IAAA,kBAAU,GAAE,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;QAC7D,IAAA,sBAAc,EAAC,SAAS,CAAC,CAAC;QAC1B,IAAA,sBAAc,EAAC,SAAS,CAAC,CAAC;IAC5B,CAAC,CAAQ,EACT,IAAI,CACL;SAEA,IAAI,CAAC,CAAC,GAAW,EAAE,GAAU,EAAE,MAAM,EAAE,EAAE;QACxC,IAAA,gBAAQ,EAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QACnB,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC;SAED,aAAa,CAAC,CAAC,EAAE,wCAAwC,CAAC;SAE1D,IAAI,EAAE;SACN,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC;AAC7B,CAAC;AApDD,kBAoDC","sourcesContent":["import yargs, { Arguments } from 'yargs';\nimport yargsType from 'yargs/yargs';\nimport builders from './builders';\nimport {\n applyConfig,\n loadConfig,\n sanitizeInputs,\n setSnapGlobals,\n logError,\n} from './utils';\n\nexport function cli(argv: string[], commands: any): void {\n const rawArgv = argv.slice(2);\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n yargs(rawArgv)\n .scriptName('mm-snap')\n .usage('Usage: $0 <command> [options]')\n\n .example('$0 init', `\\tInitialize a snap project in the current directory`)\n .example(\n '$0 build -s src/index.js -d out',\n `\\tBuild 'src/index.js' as './out/bundle.js'`,\n )\n .example(\n '$0 build -s src/index.js -d out -n snap.js',\n `\\tBuild 'src/index.js' as './out/snap.js'`,\n )\n .example('$0 serve -r out', `\\tServe files in './out' on port 8080`)\n .example('$0 serve -r out -p 9000', `\\tServe files in './out' on port 9000`)\n .example(\n '$0 watch -s src/index.js -d out',\n `\\tRebuild './out/bundle.js' on changes to files in 'src/index.js' parent and child directories`,\n )\n\n .command(commands)\n\n .option('verboseErrors', builders.verboseErrors)\n\n .option('suppressWarnings', builders.suppressWarnings)\n\n .strict()\n\n // Typecast: The @types/yargs type for .middleware is incorrect.\n // yargs middleware functions receive the yargs instance as a second parameter.\n // ref: https://yargs.js.org/docs/#api-reference-middlewarecallbacks-applybeforevalidation\n .middleware(\n ((yargsArgv: Arguments, yargsInstance: typeof yargsType) => {\n applyConfig(loadConfig(), rawArgv, yargsArgv, yargsInstance);\n setSnapGlobals(yargsArgv);\n sanitizeInputs(yargsArgv);\n }) as any,\n true,\n )\n\n .fail((msg: string, err: Error, _yargs) => {\n logError(msg, err);\n process.exitCode = 1;\n })\n\n .demandCommand(1, 'You must specify at least one command.')\n\n .help()\n .alias('help', 'h').argv;\n}\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;AAAA,kDAAyC;AAEzC,0DAAkC;AAClC,mCAMiB;AAEjB;;;;;;GAMG;AACH,SAAgB,GAAG,CAAC,IAAc,EAAE,QAAa;IAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,oEAAoE;IACpE,IAAA,eAAK,EAAC,OAAO,CAAC;SACX,UAAU,CAAC,SAAS,CAAC;SACrB,KAAK,CAAC,+BAA+B,CAAC;SAEtC,OAAO,CAAC,SAAS,EAAE,sDAAsD,CAAC;SAC1E,OAAO,CACN,+BAA+B,EAC/B,iEAAiE,CAClE;SACA,OAAO,CACN,iCAAiC,EACjC,6CAA6C,CAC9C;SACA,OAAO,CACN,4CAA4C,EAC5C,2CAA2C,CAC5C;SACA,OAAO,CAAC,iBAAiB,EAAE,uCAAuC,CAAC;SACnE,OAAO,CAAC,yBAAyB,EAAE,uCAAuC,CAAC;SAC3E,OAAO,CACN,iCAAiC,EACjC,gGAAgG,CACjG;SAEA,OAAO,CAAC,QAAQ,CAAC;SAEjB,MAAM,CAAC,eAAe,EAAE,kBAAQ,CAAC,aAAa,CAAC;SAE/C,MAAM,CAAC,kBAAkB,EAAE,kBAAQ,CAAC,gBAAgB,CAAC;SAErD,MAAM,EAAE;QAET,gEAAgE;QAChE,+EAA+E;QAC/E,0FAA0F;SACzF,UAAU,CACT,CAAC,CAAC,SAAoB,EAAE,aAA+B,EAAE,EAAE;QACzD,IAAA,mBAAW,EAAC,IAAA,kBAAU,GAAE,EAAE,OAAO,EAAE,SAAS,EAAE,aAAa,CAAC,CAAC;QAC7D,IAAA,sBAAc,EAAC,SAAS,CAAC,CAAC;QAC1B,IAAA,sBAAc,EAAC,SAAS,CAAC,CAAC;IAC5B,CAAC,CAAQ,EACT,IAAI,CACL;SAEA,IAAI,CAAC,CAAC,GAAW,EAAE,GAAU,EAAE,MAAM,EAAE,EAAE;QACxC,IAAA,gBAAQ,EAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QACnB,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC;SAED,aAAa,CAAC,CAAC,EAAE,wCAAwC,CAAC;SAE1D,IAAI,EAAE;SACN,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC;AAC7B,CAAC;AAxDD,kBAwDC","sourcesContent":["import yargs, { Arguments } from 'yargs';\nimport yargsType from 'yargs/yargs';\nimport builders from './builders';\nimport {\n applyConfig,\n loadConfig,\n sanitizeInputs,\n setSnapGlobals,\n logError,\n} from './utils';\n\n/**\n * The main CLI entry point function. This processes the command line args, and\n * runs the appropriate function.\n *\n * @param argv - The raw command line arguments, i.e., `process.argv`.\n * @param commands - The list of commands to use.\n */\nexport function cli(argv: string[], commands: any): void {\n const rawArgv = argv.slice(2);\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n yargs(rawArgv)\n .scriptName('mm-snap')\n .usage('Usage: $0 <command> [options]')\n\n .example('$0 init', `\\tInitialize a snap project in the current directory`)\n .example(\n '$0 init --template javascript',\n `\\tInitialize a snap JavaScript project in the current directory`,\n )\n .example(\n '$0 build -s src/index.js -d out',\n `\\tBuild 'src/index.js' as './out/bundle.js'`,\n )\n .example(\n '$0 build -s src/index.js -d out -n snap.js',\n `\\tBuild 'src/index.js' as './out/snap.js'`,\n )\n .example('$0 serve -r out', `\\tServe files in './out' on port 8080`)\n .example('$0 serve -r out -p 9000', `\\tServe files in './out' on port 9000`)\n .example(\n '$0 watch -s src/index.js -d out',\n `\\tRebuild './out/bundle.js' on changes to files in 'src/index.js' parent and child directories`,\n )\n\n .command(commands)\n\n .option('verboseErrors', builders.verboseErrors)\n\n .option('suppressWarnings', builders.suppressWarnings)\n\n .strict()\n\n // Typecast: The @types/yargs type for .middleware is incorrect.\n // yargs middleware functions receive the yargs instance as a second parameter.\n // ref: https://yargs.js.org/docs/#api-reference-middlewarecallbacks-applybeforevalidation\n .middleware(\n ((yargsArgv: Arguments, yargsInstance: typeof yargsType) => {\n applyConfig(loadConfig(), rawArgv, yargsArgv, yargsInstance);\n setSnapGlobals(yargsArgv);\n sanitizeInputs(yargsArgv);\n }) as any,\n true,\n )\n\n .fail((msg: string, err: Error, _yargs) => {\n logError(msg, err);\n process.exitCode = 1;\n })\n\n .demandCommand(1, 'You must specify at least one command.')\n\n .help()\n .alias('help', 'h').argv;\n}\n"]}
@@ -5,9 +5,9 @@ import { YargsArgs } from '../../types/yargs';
5
5
  *
6
6
  * Creates destination directory if it doesn't exist.
7
7
  *
8
- * @param argv - argv from Yargs
9
- * @param argv.src - The source file path
10
- * @param argv.dist - The output directory path
11
- * @param argv.outfileName - The output file name
8
+ * @param argv - Argv from Yargs.
9
+ * @param argv.src - The source file path.
10
+ * @param argv.dist - The output directory path.
11
+ * @param argv.outfileName - The output file name.
12
12
  */
13
13
  export declare function build(argv: YargsArgs): Promise<void>;
@@ -11,10 +11,10 @@ const bundle_1 = require("./bundle");
11
11
  *
12
12
  * Creates destination directory if it doesn't exist.
13
13
  *
14
- * @param argv - argv from Yargs
15
- * @param argv.src - The source file path
16
- * @param argv.dist - The output directory path
17
- * @param argv.outfileName - The output file name
14
+ * @param argv - Argv from Yargs.
15
+ * @param argv.src - The source file path.
16
+ * @param argv.dist - The output directory path.
17
+ * @param argv.outfileName - The output file name.
18
18
  */
19
19
  async function build(argv) {
20
20
  const { src, dist, outfileName } = argv;
@@ -1 +1 @@
1
- {"version":3,"file":"buildHandler.js","sourceRoot":"","sources":["../../../src/cmds/build/buildHandler.ts"],"names":[],"mappings":";;;AACA,uCAMqB;AACrB,qDAA+C;AAC/C,iEAA8D;AAC9D,qCAAkC;AAElC;;;;;;;;;;GAUG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACxC,IAAI,WAAW,EAAE;QACf,IAAA,2BAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,wBAAgB,EAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAA,uBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAElC,MAAM,WAAW,GAAG,IAAA,sBAAc,EAAC,IAAI,EAAE,WAAqB,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,IAAA,eAAM,EACzB,GAAG,EACH,WAAW,EACX,IAAI,EACJ,IAAA,kBAAU,GAAE,CAAC,iBAAiB,CAC/B,CAAC;IACF,IAAI,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE;QACvB,MAAM,IAAA,sBAAQ,EAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;KAClD;IAED,IAAI,IAAI,CAAC,QAAQ,EAAE;QACjB,MAAM,IAAA,iCAAe,EAAC,IAAI,CAAC,CAAC;KAC7B;AACH,CAAC;AAtBD,sBAsBC","sourcesContent":["import { YargsArgs } from '../../types/yargs';\nimport {\n getOutfilePath,\n loadConfig,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '../../utils';\nimport { snapEval } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\nimport { bundle } from './bundle';\n\n/**\n * Builds all files in the given source directory to the given destination\n * directory.\n *\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - argv from Yargs\n * @param argv.src - The source file path\n * @param argv.dist - The output directory path\n * @param argv.outfileName - The output file name\n */\nexport async function build(argv: YargsArgs): Promise<void> {\n const { src, dist, outfileName } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n\n const outfilePath = getOutfilePath(dist, outfileName as string);\n const result = await bundle(\n src,\n outfilePath,\n argv,\n loadConfig().bundlerCustomizer,\n );\n if (result && argv.eval) {\n await snapEval({ ...argv, bundle: outfilePath });\n }\n\n if (argv.manifest) {\n await manifestHandler(argv);\n }\n}\n"]}
1
+ {"version":3,"file":"buildHandler.js","sourceRoot":"","sources":["../../../src/cmds/build/buildHandler.ts"],"names":[],"mappings":";;;AACA,uCAMqB;AACrB,qDAA+C;AAC/C,iEAA8D;AAC9D,qCAAkC;AAElC;;;;;;;;;;GAUG;AACI,KAAK,UAAU,KAAK,CAAC,IAAe;IACzC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;IACxC,IAAI,WAAW,EAAE;QACf,IAAA,2BAAmB,EAAC,WAAqB,CAAC,CAAC;KAC5C;IACD,MAAM,IAAA,wBAAgB,EAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAA,uBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAElC,MAAM,WAAW,GAAG,IAAA,sBAAc,EAAC,IAAI,EAAE,WAAqB,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,IAAA,eAAM,EACzB,GAAG,EACH,WAAW,EACX,IAAI,EACJ,IAAA,kBAAU,GAAE,CAAC,iBAAiB,CAC/B,CAAC;IACF,IAAI,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE;QACvB,MAAM,IAAA,sBAAQ,EAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;KAClD;IAED,IAAI,IAAI,CAAC,QAAQ,EAAE;QACjB,MAAM,IAAA,iCAAe,EAAC,IAAI,CAAC,CAAC;KAC7B;AACH,CAAC;AAtBD,sBAsBC","sourcesContent":["import { YargsArgs } from '../../types/yargs';\nimport {\n getOutfilePath,\n loadConfig,\n validateDirPath,\n validateFilePath,\n validateOutfileName,\n} from '../../utils';\nimport { snapEval } from '../eval/evalHandler';\nimport { manifestHandler } from '../manifest/manifestHandler';\nimport { bundle } from './bundle';\n\n/**\n * Builds all files in the given source directory to the given destination\n * directory.\n *\n * Creates destination directory if it doesn't exist.\n *\n * @param argv - Argv from Yargs.\n * @param argv.src - The source file path.\n * @param argv.dist - The output directory path.\n * @param argv.outfileName - The output file name.\n */\nexport async function build(argv: YargsArgs): Promise<void> {\n const { src, dist, outfileName } = argv;\n if (outfileName) {\n validateOutfileName(outfileName as string);\n }\n await validateFilePath(src);\n await validateDirPath(dist, true);\n\n const outfilePath = getOutfilePath(dist, outfileName as string);\n const result = await bundle(\n src,\n outfilePath,\n argv,\n loadConfig().bundlerCustomizer,\n );\n if (result && argv.eval) {\n await snapEval({ ...argv, bundle: outfilePath });\n }\n\n if (argv.manifest) {\n await manifestHandler(argv);\n }\n}\n"]}
@@ -6,10 +6,11 @@ import { YargsArgs } from '../../types/yargs';
6
6
  *
7
7
  * @param src - The source file path.
8
8
  * @param dest - The destination file path.
9
- * @param argv - arguments as an object generated by yargs.
9
+ * @param argv - Arguments as an object generated by `yargs`.
10
10
  * @param argv.sourceMaps - Whether to output sourcemaps.
11
11
  * @param argv.stripComments - Whether to remove comments from code.
12
12
  * @param argv.transpilationMode - The Babel transpilation mode.
13
- * @param bundlerTransform
13
+ * @param bundlerTransform - An optional function which can be used to transform
14
+ * the Browserify instance, e.g., adding a custom transform or plugin.
14
15
  */
15
16
  export declare function bundle(src: string, dest: string, argv: YargsArgs, bundlerTransform?: (bundler: BrowserifyObject) => void): Promise<boolean>;
@@ -16,11 +16,12 @@ const utils_1 = require("./utils");
16
16
  *
17
17
  * @param src - The source file path.
18
18
  * @param dest - The destination file path.
19
- * @param argv - arguments as an object generated by yargs.
19
+ * @param argv - Arguments as an object generated by `yargs`.
20
20
  * @param argv.sourceMaps - Whether to output sourcemaps.
21
21
  * @param argv.stripComments - Whether to remove comments from code.
22
22
  * @param argv.transpilationMode - The Babel transpilation mode.
23
- * @param bundlerTransform
23
+ * @param bundlerTransform - An optional function which can be used to transform
24
+ * the Browserify instance, e.g., adding a custom transform or plugin.
24
25
  */
25
26
  function bundle(src, dest, argv, bundlerTransform) {
26
27
  const { sourceMaps: debug, transpilationMode } = argv;
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../../src/cmds/build/bundle.ts"],"names":[],"mappings":";;;;;;AAAA,4DAA0D;AAC1D,gGAAuD;AACvD,6CAAoD;AAEpD,mCAA+D;AAE/D,+EAA+E;AAC/E,mEAAmE;AACnE,mHAAmH;AAEnH;;;;;;;;;;GAUG;AACH,SAAgB,MAAM,CACpB,GAAW,EACX,IAAY,EACZ,IAAe,EACf,gBAAsD;IAEtD,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IACtD,MAAM,eAAe,GAAG,IAAA,2BAAmB,EAAC,IAAW,CAAC,CAAC;IACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;QACtC,MAAM,OAAO,GAAG,IAAA,oBAAU,EAAC,GAAG,EAAE;YAC9B,KAAK;YACL,UAAU,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC;YAC1B,wEAAwE;YACxE,UAAU,EAAE,QAAQ;SACrB,CAAC,CAAC;QAEH,IAAI,iBAAiB,KAAK,6BAAkB,CAAC,IAAI,EAAE;YACjD,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE;gBACrC,MAAM,EAAE,iBAAiB,KAAK,6BAAkB,CAAC,YAAY;gBAC7D,UAAU,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC;gBAC1B,OAAO,EAAE;oBACP,OAAO,CAAC,0BAA0B,CAAC;oBACnC;wBACE,OAAO,CAAC,mBAAmB,CAAC;wBAC5B;4BACE,OAAO,EAAE;gCACP,QAAQ,EAAE,CAAC,cAAc,EAAE,eAAe,CAAC;6BAC5C;yBACF;qBACF;iBACF;gBACD,OAAO,EAAE;oBACP,OAAO,CAAC,iCAAiC,CAAC;oBAC1C,OAAO,CAAC,yCAAyC,CAAC;oBAClD,OAAO,CAAC,2CAA2C,CAAC;oBACpD,OAAO,CAAC,0CAA0C,CAAC;oBACnD,OAAO,CAAC,oDAAoD,CAAC;iBAC9D;gBACD,GAAI,eAAuB;aAC5B,CAAC,CAAC;SACJ;QAED,gBAAgB,EAAE,CAAC,OAAO,CAAC,CAAC;QAE5B,OAAO,CAAC,MAAM,CAAC,iCAAM,EAAE;YACrB,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;SAClD,CAAC,CAAC;QAEH,OAAO,CAAC,MAAM,CACZ,KAAK,EAAE,WAAW,EAAE,YAAoB,EAAE,EAAE,CAC1C,MAAM,IAAA,uBAAe,EAAC;YACpB,WAAW;YACX,YAAY;YACZ,GAAG;YACH,IAAI;YACJ,OAAO;SACR,CAAC,CACL,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AA5DD,wBA4DC","sourcesContent":["import browserify, { BrowserifyObject } from 'browserify';\nimport plugin from '@metamask/snaps-browserify-plugin';\nimport { TranspilationModes } from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { processDependencies, writeBundleFile } from './utils';\n\n// We need to statically import all Browserify transforms and all Babel presets\n// and plugins, and calling `require` is the sanest way to do that.\n/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n\n/**\n * Builds a Snap bundle JS file from its JavaScript source.\n *\n * @param src - The source file path.\n * @param dest - The destination file path.\n * @param argv - arguments as an object generated by yargs.\n * @param argv.sourceMaps - Whether to output sourcemaps.\n * @param argv.stripComments - Whether to remove comments from code.\n * @param argv.transpilationMode - The Babel transpilation mode.\n * @param bundlerTransform\n */\nexport function bundle(\n src: string,\n dest: string,\n argv: YargsArgs,\n bundlerTransform?: (bundler: BrowserifyObject) => void,\n): Promise<boolean> {\n const { sourceMaps: debug, transpilationMode } = argv;\n const babelifyOptions = processDependencies(argv as any);\n return new Promise((resolve, _reject) => {\n const bundler = browserify(src, {\n debug,\n extensions: ['.js', '.ts'],\n // Standalone is required to properly support Snaps using module.exports\n standalone: '<snap>',\n });\n\n if (transpilationMode !== TranspilationModes.none) {\n bundler.transform(require('babelify'), {\n global: transpilationMode === TranspilationModes.localAndDeps,\n extensions: ['.js', '.ts'],\n presets: [\n require('@babel/preset-typescript'),\n [\n require('@babel/preset-env'),\n {\n targets: {\n browsers: ['chrome >= 66', 'firefox >= 68'],\n },\n },\n ],\n ],\n plugins: [\n require('@babel/plugin-transform-runtime'),\n require('@babel/plugin-proposal-class-properties'),\n require('@babel/plugin-proposal-object-rest-spread'),\n require('@babel/plugin-proposal-optional-chaining'),\n require('@babel/plugin-proposal-nullish-coalescing-operator'),\n ],\n ...(babelifyOptions as any),\n });\n }\n\n bundlerTransform?.(bundler);\n\n bundler.plugin(plugin, {\n stripComments: argv.stripComments,\n transformHtmlComments: argv.transformHtmlComments,\n });\n\n bundler.bundle(\n async (bundleError, bundleBuffer: Buffer) =>\n await writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n }),\n );\n });\n}\n"]}
1
+ {"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../../src/cmds/build/bundle.ts"],"names":[],"mappings":";;;;;;AAAA,4DAA0D;AAC1D,gGAAuD;AACvD,6CAAoD;AAEpD,mCAA+D;AAE/D,+EAA+E;AAC/E,mEAAmE;AACnE,mHAAmH;AAEnH;;;;;;;;;;;GAWG;AACH,SAAgB,MAAM,CACpB,GAAW,EACX,IAAY,EACZ,IAAe,EACf,gBAAsD;IAEtD,MAAM,EAA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,EAAE,WAAW,EAAE,YAAoB,EAAE,EAAE,CAC1C,MAAM,IAAA,uBAAe,EAAC;YACpB,WAAW;YACX,YAAY;YACZ,GAAG;YACH,IAAI;YACJ,OAAO;SACR,CAAC,CACL,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AA5DD,wBA4DC","sourcesContent":["import browserify, { BrowserifyObject } from 'browserify';\nimport plugin from '@metamask/snaps-browserify-plugin';\nimport { TranspilationModes } from '../../builders';\nimport { YargsArgs } from '../../types/yargs';\nimport { processDependencies, writeBundleFile } from './utils';\n\n// We need to statically import all Browserify transforms and all Babel presets\n// and plugins, and calling `require` is the sanest way to do that.\n/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n\n/**\n * Builds a Snap bundle JS file from its JavaScript source.\n *\n * @param src - The source file path.\n * @param dest - The destination file path.\n * @param argv - Arguments as an object generated by `yargs`.\n * @param argv.sourceMaps - Whether to output sourcemaps.\n * @param argv.stripComments - Whether to remove comments from code.\n * @param argv.transpilationMode - The Babel transpilation mode.\n * @param bundlerTransform - An optional function which can be used to transform\n * the Browserify instance, e.g., adding a custom transform or plugin.\n */\nexport function bundle(\n src: string,\n dest: string,\n argv: YargsArgs,\n bundlerTransform?: (bundler: BrowserifyObject) => void,\n): Promise<boolean> {\n const { sourceMaps: debug, transpilationMode } = argv;\n const babelifyOptions = processDependencies(argv as any);\n return new Promise((resolve, _reject) => {\n const bundler = browserify(src, {\n debug,\n extensions: ['.js', '.ts'],\n // Standalone is required to properly support Snaps using module.exports\n standalone: '<snap>',\n });\n\n if (transpilationMode !== TranspilationModes.none) {\n bundler.transform(require('babelify'), {\n global: transpilationMode === TranspilationModes.localAndDeps,\n extensions: ['.js', '.ts'],\n presets: [\n require('@babel/preset-typescript'),\n [\n require('@babel/preset-env'),\n {\n targets: {\n browsers: ['chrome >= 66', 'firefox >= 68'],\n },\n },\n ],\n ],\n plugins: [\n require('@babel/plugin-transform-runtime'),\n require('@babel/plugin-proposal-class-properties'),\n require('@babel/plugin-proposal-object-rest-spread'),\n require('@babel/plugin-proposal-optional-chaining'),\n require('@babel/plugin-proposal-nullish-coalescing-operator'),\n ],\n ...(babelifyOptions as any),\n });\n }\n\n bundlerTransform?.(bundler);\n\n bundler.plugin(plugin, {\n stripComments: argv.stripComments,\n transformHtmlComments: argv.transformHtmlComments,\n });\n\n bundler.bundle(\n async (bundleError, bundleBuffer: Buffer) =>\n await writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n }),\n );\n });\n}\n"]}
@@ -23,21 +23,34 @@ declare type WriteBundleFileArgs = {
23
23
  */
24
24
  export declare function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve, }: WriteBundleFileArgs): Promise<void>;
25
25
  /**
26
- * Processes dependencies and updates argv with an options object
27
- * @param argv
26
+ * Processes dependencies and updates `argv` with an options object.
27
+ *
28
+ * @param argv - The Yargs arguments object.
29
+ * @returns An object with options that can be passed to Babelify.
28
30
  */
29
31
  export declare function processDependencies(argv: YargsArgs): Record<string, any>;
30
32
  /**
31
- * Processes a string of space delimited dependencies into one regex string
32
- * @param dependencies
33
- * @returns a regexp string
33
+ * Processes a string of space delimited dependencies into one RegExp string.
34
+ *
35
+ * @param dependencies - An array of dependencies to add to the RegExp.
36
+ * @returns A RegExp object.
34
37
  */
35
38
  export declare function getDependencyRegExp(dependencies: string[]): RegExp | null;
36
39
  /**
37
- * Helper function remove any leading and trailing slashes from dependency list
38
- * @param dependencies
39
- * @returns an array of sanitized paths
40
+ * Helper function remove any leading and trailing slashes from dependency list.
41
+ *
42
+ * @param dependencies - An array of dependencies to sanitize.
43
+ * @returns An array of sanitized paths.
40
44
  */
41
45
  export declare function sanitizeDependencyPaths(dependencies: string[]): string[];
46
+ /**
47
+ * Check the Yargs argv object, to see if the provided options are valid. The
48
+ * options are invalid if both `depsToTranspile` are provided, and
49
+ * `transpilationMode` is not set to `localAndDeps`.
50
+ *
51
+ * @param argv - The Yargs arguments object.
52
+ * @throws If the `depsToTranspile` is set, and `transpilationMode` is not set
53
+ * to `localAndDeps`.
54
+ */
42
55
  export declare function processInvalidTranspilation(argv: YargsArgs): void;
43
56
  export {};
@@ -33,8 +33,10 @@ async function writeBundleFile({ bundleError, bundleBuffer, src, dest, resolve,
33
33
  }
34
34
  exports.writeBundleFile = writeBundleFile;
35
35
  /**
36
- * Processes dependencies and updates argv with an options object
37
- * @param argv
36
+ * Processes dependencies and updates `argv` with an options object.
37
+ *
38
+ * @param argv - The Yargs arguments object.
39
+ * @returns An object with options that can be passed to Babelify.
38
40
  */
39
41
  function processDependencies(argv) {
40
42
  const { depsToTranspile, transpilationMode } = argv;
@@ -49,9 +51,10 @@ function processDependencies(argv) {
49
51
  }
50
52
  exports.processDependencies = processDependencies;
51
53
  /**
52
- * Processes a string of space delimited dependencies into one regex string
53
- * @param dependencies
54
- * @returns a regexp string
54
+ * Processes a string of space delimited dependencies into one RegExp string.
55
+ *
56
+ * @param dependencies - An array of dependencies to add to the RegExp.
57
+ * @returns A RegExp object.
55
58
  */
56
59
  function getDependencyRegExp(dependencies) {
57
60
  let regexp = null;
@@ -66,9 +69,10 @@ function getDependencyRegExp(dependencies) {
66
69
  }
67
70
  exports.getDependencyRegExp = getDependencyRegExp;
68
71
  /**
69
- * Helper function remove any leading and trailing slashes from dependency list
70
- * @param dependencies
71
- * @returns an array of sanitized paths
72
+ * Helper function remove any leading and trailing slashes from dependency list.
73
+ *
74
+ * @param dependencies - An array of dependencies to sanitize.
75
+ * @returns An array of sanitized paths.
72
76
  */
73
77
  function sanitizeDependencyPaths(dependencies) {
74
78
  return dependencies.map((dependency) => {
@@ -76,6 +80,15 @@ function sanitizeDependencyPaths(dependencies) {
76
80
  });
77
81
  }
78
82
  exports.sanitizeDependencyPaths = sanitizeDependencyPaths;
83
+ /**
84
+ * Check the Yargs argv object, to see if the provided options are valid. The
85
+ * options are invalid if both `depsToTranspile` are provided, and
86
+ * `transpilationMode` is not set to `localAndDeps`.
87
+ *
88
+ * @param argv - The Yargs arguments object.
89
+ * @throws If the `depsToTranspile` is set, and `transpilationMode` is not set
90
+ * to `localAndDeps`.
91
+ */
79
92
  function processInvalidTranspilation(argv) {
80
93
  if (argv.depsToTranspile &&
81
94
  argv.transpilationMode !== builders_1.TranspilationModes.localAndDeps) {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/cmds/build/utils.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AACpC,2CAA8C;AAE9C,6CAAoD;AAUpD;;;;;;;;;;;;;GAaG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,WAAW,EACX,YAAY,EACZ,GAAG,EACH,IAAI,EACJ,OAAO,GACa;IACpB,IAAI,WAAW,EAAE;QACf,MAAM,IAAA,iBAAU,EAAC,cAAc,EAAE,WAAW,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;KACpE;IAED,IAAI;QACF,MAAM,aAAE,CAAC,SAAS,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnD,OAAO,CAAC,GAAG,CAAC,mBAAmB,GAAG,iBAAiB,IAAI,IAAI,CAAC,CAAC;QAC7D,OAAO,CAAC,IAAI,CAAC,CAAC;KACf;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAA,iBAAU,EAAC,cAAc,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;KAC9D;AACH,CAAC;AAlBD,0CAkBC;AAED;;;GAGG;AACH,SAAgB,mBAAmB,CAAC,IAAe;IACjD,MAAM,EAAE,eAAe,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IACpD,MAAM,eAAe,GAAwB,EAAE,CAAC;IAChD,IAAI,iBAAiB,KAAK,6BAAkB,CAAC,YAAY,EAAE;QACzD,MAAM,SAAS,GAAG,mBAAmB,CAAC,eAA2B,CAAC,CAAC;QACnE,IAAI,SAAS,KAAK,IAAI,EAAE;YACtB,eAAe,CAAC,MAAM,GAAG,CAAC,SAAS,CAAC,CAAC;SACtC;KACF;IACD,OAAO,eAAe,CAAC;AACzB,CAAC;AAVD,kDAUC;AAED;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,YAAsB;IACxD,IAAI,MAAM,GAAkB,IAAI,CAAC;IACjC,IAAI,CAAC,YAAY,IAAI,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE;QACvE,OAAO,MAAM,CAAC;KACf;IACD,MAAM,KAAK,GAAa,uBAAuB,CAAC,YAAY,CAAC,CAAC;IAC9D,MAAM,GAAG,oBAAoB,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;IAC7C,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;IAChD,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC;AAVD,kDAUC;AAED;;;;GAIG;AACH,SAAgB,uBAAuB,CAAC,YAAsB;IAC5D,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;QACrC,OAAO,UAAU,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;AAJD,0DAIC;AAED,SAAgB,2BAA2B,CAAC,IAAe;IACzD,IACE,IAAI,CAAC,eAAe;QACpB,IAAI,CAAC,iBAAiB,KAAK,6BAAkB,CAAC,YAAY,EAC1D;QACA,MAAM,IAAI,KAAK,CACb,2FAA2F,CAC5F,CAAC;KACH;AACH,CAAC;AATD,kEASC","sourcesContent":["import { promises as fs } from 'fs';\nimport { writeError } from '../../utils/misc';\nimport { YargsArgs } from '../../types/yargs';\nimport { TranspilationModes } from '../../builders';\n\ntype WriteBundleFileArgs = {\n bundleError: Error;\n bundleBuffer: Buffer;\n src: string;\n dest: string;\n resolve: (value: boolean) => void;\n};\n\n/**\n * Performs postprocessing on the bundle contents and writes them to disk.\n * Intended to be used in the callback passed to the Browserify `.bundle()`\n * call.\n *\n * @param options - Options bag.\n * @param options.bundleError - Any error received from Browserify.\n * @param options.bundleBuffer - The {@link Buffer} with the bundle contents\n * from Browserify.\n * @param options.src - The source file path.\n * @param options.dest - The destination file path.\n * @param options.resolve - A {@link Promise} resolution function, so that we\n * can use promises and `async`/`await` even though Browserify uses callbacks.\n */\nexport async function writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n}: WriteBundleFileArgs) {\n if (bundleError) {\n await writeError('Build error:', bundleError.message, bundleError);\n }\n\n try {\n await fs.writeFile(dest, bundleBuffer?.toString());\n console.log(`Build success: '${src}' bundled as '${dest}'!`);\n resolve(true);\n } catch (error) {\n await writeError('Write error:', error.message, error, dest);\n }\n}\n\n/**\n * Processes dependencies and updates argv with an options object\n * @param argv\n */\nexport function processDependencies(argv: YargsArgs) {\n const { depsToTranspile, transpilationMode } = argv;\n const babelifyOptions: Record<string, any> = {};\n if (transpilationMode === TranspilationModes.localAndDeps) {\n const regexpStr = getDependencyRegExp(depsToTranspile as string[]);\n if (regexpStr !== null) {\n babelifyOptions.ignore = [regexpStr];\n }\n }\n return babelifyOptions;\n}\n\n/**\n * Processes a string of space delimited dependencies into one regex string\n * @param dependencies\n * @returns a regexp string\n */\nexport function getDependencyRegExp(dependencies: string[]): RegExp | null {\n let regexp: string | null = null;\n if (!dependencies || dependencies.includes('.') || !dependencies.length) {\n return regexp;\n }\n const paths: string[] = sanitizeDependencyPaths(dependencies);\n regexp = `/node_modules/(?!${paths.shift()}`;\n paths.forEach((path) => (regexp += `|${path}`));\n regexp += '/)';\n return RegExp(regexp, 'u');\n}\n\n/**\n * Helper function remove any leading and trailing slashes from dependency list\n * @param dependencies\n * @returns an array of sanitized paths\n */\nexport function sanitizeDependencyPaths(dependencies: string[]): string[] {\n return dependencies.map((dependency) => {\n return dependency.replace(/^[/\\\\]+/u, '').replace(/[/\\\\]+$/u, '');\n });\n}\n\nexport function processInvalidTranspilation(argv: YargsArgs) {\n if (\n argv.depsToTranspile &&\n argv.transpilationMode !== TranspilationModes.localAndDeps\n ) {\n throw new Error(\n '\"depsToTranspile\" can only be specified if \"transpilationMode\" is set to \"localAndDeps\" .',\n );\n }\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/cmds/build/utils.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AACpC,2CAA8C;AAE9C,6CAAoD;AAUpD;;;;;;;;;;;;;GAaG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,WAAW,EACX,YAAY,EACZ,GAAG,EACH,IAAI,EACJ,OAAO,GACa;IACpB,IAAI,WAAW,EAAE;QACf,MAAM,IAAA,iBAAU,EAAC,cAAc,EAAE,WAAW,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;KACpE;IAED,IAAI;QACF,MAAM,aAAE,CAAC,SAAS,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnD,OAAO,CAAC,GAAG,CAAC,mBAAmB,GAAG,iBAAiB,IAAI,IAAI,CAAC,CAAC;QAC7D,OAAO,CAAC,IAAI,CAAC,CAAC;KACf;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAA,iBAAU,EAAC,cAAc,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;KAC9D;AACH,CAAC;AAlBD,0CAkBC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CAAC,IAAe;IACjD,MAAM,EAAE,eAAe,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IACpD,MAAM,eAAe,GAAwB,EAAE,CAAC;IAChD,IAAI,iBAAiB,KAAK,6BAAkB,CAAC,YAAY,EAAE;QACzD,MAAM,SAAS,GAA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sourcesContent":["import { promises as fs } from 'fs';\nimport { writeError } from '../../utils/misc';\nimport { YargsArgs } from '../../types/yargs';\nimport { TranspilationModes } from '../../builders';\n\ntype WriteBundleFileArgs = {\n bundleError: Error;\n bundleBuffer: Buffer;\n src: string;\n dest: string;\n resolve: (value: boolean) => void;\n};\n\n/**\n * Performs postprocessing on the bundle contents and writes them to disk.\n * Intended to be used in the callback passed to the Browserify `.bundle()`\n * call.\n *\n * @param options - Options bag.\n * @param options.bundleError - Any error received from Browserify.\n * @param options.bundleBuffer - The {@link Buffer} with the bundle contents\n * from Browserify.\n * @param options.src - The source file path.\n * @param options.dest - The destination file path.\n * @param options.resolve - A {@link Promise} resolution function, so that we\n * can use promises and `async`/`await` even though Browserify uses callbacks.\n */\nexport async function writeBundleFile({\n bundleError,\n bundleBuffer,\n src,\n dest,\n resolve,\n}: WriteBundleFileArgs) {\n if (bundleError) {\n await writeError('Build error:', bundleError.message, bundleError);\n }\n\n try {\n await fs.writeFile(dest, bundleBuffer?.toString());\n console.log(`Build success: '${src}' bundled as '${dest}'!`);\n resolve(true);\n } catch (error) {\n await writeError('Write error:', error.message, error, dest);\n }\n}\n\n/**\n * Processes dependencies and updates `argv` with an options object.\n *\n * @param argv - The Yargs arguments object.\n * @returns An object with options that can be passed to Babelify.\n */\nexport function processDependencies(argv: YargsArgs) {\n const { depsToTranspile, transpilationMode } = argv;\n const babelifyOptions: Record<string, any> = {};\n if (transpilationMode === TranspilationModes.localAndDeps) {\n const regexpStr = getDependencyRegExp(depsToTranspile as string[]);\n if (regexpStr !== null) {\n babelifyOptions.ignore = [regexpStr];\n }\n }\n return babelifyOptions;\n}\n\n/**\n * Processes a string of space delimited dependencies into one RegExp string.\n *\n * @param dependencies - An array of dependencies to add to the RegExp.\n * @returns A RegExp object.\n */\nexport function getDependencyRegExp(dependencies: string[]): RegExp | null {\n let regexp: string | null = null;\n if (!dependencies || dependencies.includes('.') || !dependencies.length) {\n return regexp;\n }\n const paths: string[] = sanitizeDependencyPaths(dependencies);\n regexp = `/node_modules/(?!${paths.shift()}`;\n paths.forEach((path) => (regexp += `|${path}`));\n regexp += '/)';\n return RegExp(regexp, 'u');\n}\n\n/**\n * Helper function remove any leading and trailing slashes from dependency list.\n *\n * @param dependencies - An array of dependencies to sanitize.\n * @returns An array of sanitized paths.\n */\nexport function sanitizeDependencyPaths(dependencies: string[]): string[] {\n return dependencies.map((dependency) => {\n return dependency.replace(/^[/\\\\]+/u, '').replace(/[/\\\\]+$/u, '');\n });\n}\n\n/**\n * Check the Yargs argv object, to see if the provided options are valid. The\n * options are invalid if both `depsToTranspile` are provided, and\n * `transpilationMode` is not set to `localAndDeps`.\n *\n * @param argv - The Yargs arguments object.\n * @throws If the `depsToTranspile` is set, and `transpilationMode` is not set\n * to `localAndDeps`.\n */\nexport function processInvalidTranspilation(argv: YargsArgs) {\n if (\n argv.depsToTranspile &&\n argv.transpilationMode !== TranspilationModes.localAndDeps\n ) {\n throw new Error(\n '\"depsToTranspile\" can only be specified if \"transpilationMode\" is set to \"localAndDeps\" .',\n );\n }\n}\n"]}
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const fs_1 = require("fs");
4
4
  // eslint-disable-next-line import/no-unassigned-import
5
5
  require("ses/lockdown");
6
- const worker_threads_1 = require("worker_threads");
7
6
  const mock_1 = require("./mock");
8
7
  lockdown({
9
8
  consoleTaming: 'unsafe',
@@ -12,21 +11,13 @@ lockdown({
12
11
  dateTaming: 'unsafe',
13
12
  overrideTaming: 'severe',
14
13
  });
15
- if (worker_threads_1.parentPort !== null) {
16
- worker_threads_1.parentPort.on('message', (message) => {
17
- const { snapFilePath } = message;
18
- const snapModule = { exports: {} };
19
- new Compartment({
20
- ...getMockEndowments(),
21
- module: snapModule,
22
- exports: snapModule.exports,
23
- }).evaluate((0, fs_1.readFileSync)(snapFilePath, 'utf8'));
24
- if (!snapModule.exports?.onRpcRequest) {
25
- console.warn("The Snap doesn't have onRpcRequest export defined");
26
- }
27
- setTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits
28
- });
29
- }
14
+ /**
15
+ * Get mock endowments that don't do anything. This is useful for running the
16
+ * eval, for snaps that try to communicate with the extension on initialisation,
17
+ * for example.
18
+ *
19
+ * @returns The mock endowments.
20
+ */
30
21
  function getMockEndowments() {
31
22
  const endowments = (0, mock_1.generateMockEndowments)();
32
23
  return {
@@ -35,4 +26,15 @@ function getMockEndowments() {
35
26
  self: endowments,
36
27
  };
37
28
  }
29
+ const snapFilePath = process.argv[2];
30
+ const snapModule = { exports: {} };
31
+ new Compartment({
32
+ ...getMockEndowments(),
33
+ module: snapModule,
34
+ exports: snapModule.exports,
35
+ }).evaluate((0, fs_1.readFileSync)(snapFilePath, 'utf8'));
36
+ if (!snapModule.exports?.onRpcRequest) {
37
+ console.warn(`The Snap doesn't have an "onRpcRequest" export defined.`);
38
+ }
39
+ setTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits
38
40
  //# sourceMappingURL=eval-worker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../../../src/cmds/eval/eval-worker.ts"],"names":[],"mappings":";;AAAA,2BAAkC;AAClC,uDAAuD;AACvD,wBAAsB;AACtB,mDAA4C;AAC5C,iCAAgD;AAIhD,QAAQ,CAAC;IACP,aAAa,EAAE,QAAQ;IACvB,WAAW,EAAE,QAAQ;IACrB,UAAU,EAAE,QAAQ;IACpB,UAAU,EAAE,QAAQ;IACpB,cAAc,EAAE,QAAQ;CACzB,CAAC,CAAC;AAEH,IAAI,2BAAU,KAAK,IAAI,EAAE;IACvB,2BAAU,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAiC,EAAE,EAAE;QAC7D,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;QAEjC,MAAM,UAAU,GAAsB,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;QAEtD,IAAI,WAAW,CAAC;YACd,GAAG,iBAAiB,EAAE;YACtB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,UAAU,CAAC,OAAO;SAC5B,CAAC,CAAC,QAAQ,CAAC,IAAA,iBAAY,EAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC;QAEhD,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,YAAY,EAAE;YACrC,OAAO,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAC;SACnE;QAED,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,8BAA8B;IACzE,CAAC,CAAC,CAAC;CACJ;AAED,SAAS,iBAAiB;IACxB,MAAM,UAAU,GAAG,IAAA,6BAAsB,GAAE,CAAC;IAC5C,OAAO;QACL,GAAG,UAAU;QACb,MAAM,EAAE,UAAU;QAClB,IAAI,EAAE,UAAU;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import { readFileSync } from 'fs';\n// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\nimport { parentPort } from 'worker_threads';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n});\n\nif (parentPort !== null) {\n parentPort.on('message', (message: { snapFilePath: string }) => {\n const { snapFilePath } = message;\n\n const snapModule: { exports?: any } = { exports: {} };\n\n new Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n }).evaluate(readFileSync(snapFilePath, 'utf8'));\n\n if (!snapModule.exports?.onRpcRequest) {\n console.warn(\"The Snap doesn't have onRpcRequest export defined\");\n }\n\n setTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n });\n}\n\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n"]}
1
+ {"version":3,"file":"eval-worker.js","sourceRoot":"","sources":["../../../src/cmds/eval/eval-worker.ts"],"names":[],"mappings":";;AAAA,2BAAkC;AAClC,uDAAuD;AACvD,wBAAsB;AACtB,iCAAgD;AAIhD,QAAQ,CAAC;IACP,aAAa,EAAE,QAAQ;IACvB,WAAW,EAAE,QAAQ;IACrB,UAAU,EAAE,QAAQ;IACpB,UAAU,EAAE,QAAQ;IACpB,cAAc,EAAE,QAAQ;CACzB,CAAC,CAAC;AAEH;;;;;;GAMG;AACH,SAAS,iBAAiB;IACxB,MAAM,UAAU,GAAG,IAAA,6BAAsB,GAAE,CAAC;IAC5C,OAAO;QACL,GAAG,UAAU;QACb,MAAM,EAAE,UAAU;QAClB,IAAI,EAAE,UAAU;KACjB,CAAC;AACJ,CAAC;AAED,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAErC,MAAM,UAAU,GAAsB,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;AAEtD,IAAI,WAAW,CAAC;IACd,GAAG,iBAAiB,EAAE;IACtB,MAAM,EAAE,UAAU;IAClB,OAAO,EAAE,UAAU,CAAC,OAAO;CAC5B,CAAC,CAAC,QAAQ,CAAC,IAAA,iBAAY,EAAC,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC;AAEhD,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,YAAY,EAAE;IACrC,OAAO,CAAC,IAAI,CAAC,yDAAyD,CAAC,CAAC;CACzE;AAED,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,8BAA8B","sourcesContent":["import { readFileSync } from 'fs';\n// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nif (!snapModule.exports?.onRpcRequest) {\n console.warn(`The Snap doesn't have an \"onRpcRequest\" export defined.`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"]}
@@ -1,2 +1,9 @@
1
1
  import { YargsArgs } from '../../types/yargs';
2
+ /**
3
+ * Runs the snap in a worker, to ensure SES compatibility.
4
+ *
5
+ * @param argv - The Yargs arguments object.
6
+ * @returns A promise that resolves once the eval has finished.
7
+ * @throws If the eval failed.
8
+ */
2
9
  export declare function snapEval(argv: YargsArgs): Promise<void>;
@@ -3,6 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.snapEval = void 0;
4
4
  const utils_1 = require("../../utils");
5
5
  const workerEval_1 = require("./workerEval");
6
+ /**
7
+ * Runs the snap in a worker, to ensure SES compatibility.
8
+ *
9
+ * @param argv - The Yargs arguments object.
10
+ * @returns A promise that resolves once the eval has finished.
11
+ * @throws If the eval failed.
12
+ */
6
13
  async function snapEval(argv) {
7
14
  const { bundle: bundlePath } = argv;
8
15
  await (0, utils_1.validateFilePath)(bundlePath);
@@ -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,IAAA,wBAAgB,EAAC,UAAoB,CAAC,CAAC;IAC7C,IAAI;QACF,MAAM,IAAA,uBAAU,EAAC,UAAoB,CAAC,CAAC;QACvC,OAAO,CAAC,GAAG,CAAC,4BAA4B,UAAU,WAAW,CAAC,CAAC;KAChE;IAAC,OAAO,GAAG,EAAE;QACZ,IAAA,gBAAQ,EAAC,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"]}
1
+ {"version":3,"file":"evalHandler.js","sourceRoot":"","sources":["../../../src/cmds/eval/evalHandler.ts"],"names":[],"mappings":";;;AACA,uCAAyD;AACzD,6CAA0C;AAE1C;;;;;;GAMG;AACI,KAAK,UAAU,QAAQ,CAAC,IAAe;IAC5C,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;IACpC,MAAM,IAAA,wBAAgB,EAAC,UAAoB,CAAC,CAAC;IAC7C,IAAI;QACF,MAAM,IAAA,uBAAU,EAAC,UAAoB,CAAC,CAAC;QACvC,OAAO,CAAC,GAAG,CAAC,4BAA4B,UAAU,WAAW,CAAC,CAAC;KAChE;IAAC,OAAO,GAAG,EAAE;QACZ,IAAA,gBAAQ,EAAC,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\n/**\n * Runs the snap in a worker, to ensure SES compatibility.\n *\n * @param argv - The Yargs arguments object.\n * @returns A promise that resolves once the eval has finished.\n * @throws If the eval failed.\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"]}
@@ -1,3 +1,14 @@
1
1
  export declare const ALL_APIS: string[];
2
+ /**
3
+ * Check if a value is a constructor.
4
+ *
5
+ * @param value - The value to check.
6
+ * @returns `true` if the value is a constructor, or `false` otherwise.
7
+ */
2
8
  export declare const isConstructor: (value: any) => boolean;
9
+ /**
10
+ * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.
11
+ *
12
+ * @returns A map of endowments.
13
+ */
3
14
  export declare const generateMockEndowments: () => Record<string, any>;
@@ -9,13 +9,29 @@ const crypto_1 = __importDefault(require("crypto"));
9
9
  const snap_controllers_1 = require("@metamask/snap-controllers");
10
10
  const NETWORK_APIS = ['fetch', 'WebSocket'];
11
11
  exports.ALL_APIS = [...snap_controllers_1.DEFAULT_ENDOWMENTS, ...NETWORK_APIS];
12
+ /**
13
+ * Get a mock snap provider, that always returns `true` for requests.
14
+ *
15
+ * @returns A mocked snap provider.
16
+ */
12
17
  function getMockSnapProvider() {
13
18
  const mockProvider = new events_1.default();
14
19
  mockProvider.request = async () => true;
15
20
  return mockProvider;
16
21
  }
22
+ /**
23
+ * Check if a value is a constructor.
24
+ *
25
+ * @param value - The value to check.
26
+ * @returns `true` if the value is a constructor, or `false` otherwise.
27
+ */
17
28
  const isConstructor = (value) => Boolean(typeof value?.prototype?.constructor?.name === 'string');
18
29
  exports.isConstructor = isConstructor;
30
+ /**
31
+ * A function that always returns `true`.
32
+ *
33
+ * @returns `true`.
34
+ */
19
35
  const mockFunction = () => true;
20
36
  class MockClass {
21
37
  }
@@ -27,6 +43,13 @@ const handler = {
27
43
  return mockFunction;
28
44
  },
29
45
  };
46
+ /**
47
+ * Generate a mock class for a given value. The value is wrapped in a Proxy, and
48
+ * all methods are replaced with a mock function.
49
+ *
50
+ * @param value - The value to mock.
51
+ * @returns A mock class.
52
+ */
30
53
  const generateMockClass = (value) => {
31
54
  return new Proxy(value, handler);
32
55
  };
@@ -36,6 +59,14 @@ const mockWindow = {
36
59
  crypto: crypto_1.default,
37
60
  SubtleCrypto: MockClass,
38
61
  };
62
+ /**
63
+ * Generate a mock endowment for a certain class or function on the `globalThis`
64
+ * object.
65
+ *
66
+ * @param key - The key to generate the mock endowment for.
67
+ * @returns A mocked class or function. If the key is part of the default
68
+ * endowments, the original value is returned.
69
+ */
39
70
  const generateMockEndowment = (key) => {
40
71
  const globalValue = globalThis[key];
41
72
  // Default exposed APIs don't need to be mocked
@@ -55,6 +86,11 @@ const generateMockEndowment = (key) => {
55
86
  }
56
87
  return globalOrMocked;
57
88
  };
89
+ /**
90
+ * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.
91
+ *
92
+ * @returns A map of endowments.
93
+ */
58
94
  const generateMockEndowments = () => {
59
95
  return exports.ALL_APIS.reduce((acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }), { wallet: getMockSnapProvider() });
60
96
  };
@@ -1 +1 @@
1
- {"version":3,"file":"mock.js","sourceRoot":"","sources":["../../../src/cmds/eval/mock.ts"],"names":[],"mappings":";;;;;;AAAA,oDAAkC;AAClC,oDAA4B;AAC5B,iEAAgE;AAEhE,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AAE/B,QAAA,QAAQ,GAAa,CAAC,GAAG,qCAAkB,EAAE,GAAG,YAAY,CAAC,CAAC;AAO3E,SAAS,mBAAmB;IAC1B,MAAM,YAAY,GAAG,IAAI,gBAAY,EAA+B,CAAC;IACrE,YAAY,CAAC,O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AAI,UAAU,IAAI,IAAA,qBAAa,EAAC,cAAc,CAAC,EAAE;QAC/C,OAAO,iBAAiB,CAAC,cAAc,CAAC,CAAC;KAC1C;SAAM,IAAI,UAAU,IAAI,CAAC,cAAc,EAAE;QACxC,qCAAqC;QACrC,OAAO,YAAY,CAAC;KACrB;IACD,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAEK,MAAM,sBAAsB,GAAG,GAAG,EAAE;IACzC,OAAO,gBAAQ,CAAC,MAAM,CACpB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,EAC7D,EAAE,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAClC,CAAC;AACJ,CAAC,CAAC;AALW,QAAA,sBAAsB,0BAKjC","sourcesContent":["import EventEmitter from 'events';\nimport crypto from 'crypto';\nimport { DEFAULT_ENDOWMENTS } from '@metamask/snap-controllers';\n\nconst NETWORK_APIS = ['fetch', 'WebSocket'];\n\nexport const ALL_APIS: string[] = [...DEFAULT_ENDOWMENTS, ...NETWORK_APIS];\n\ntype MockSnapProvider = EventEmitter & {\n registerRpcMessageHandler: () => any;\n request: () => Promise<any>;\n};\n\nfunction getMockSnapProvider(): MockSnapProvider {\n const mockProvider = new EventEmitter() as Partial<MockSnapProvider>;\n mockProvider.request = async () => true;\n return mockProvider as MockSnapProvider;\n}\n\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we have types for them and can use that to generate mocks if needed\nconst mockWindow = {\n WebSocket: MockClass,\n crypto,\n SubtleCrypto: MockClass,\n};\n\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? (mockWindow as any)[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { wallet: getMockSnapProvider() },\n );\n};\n"]}
1
+ {"version":3,"file":"mock.js","sourceRoot":"","sources":["../../../src/cmds/eval/mock.ts"],"names":[],"mappings":";;;;;;AAAA,oDAAkC;AAClC,oDAA4B;AAC5B,iEAAgE;AAEhE,MAAM,YAAY,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AAE/B,QAAA,QAAQ,GAAa,CAAC,GAAG,qCAAkB,EAAE,GAAG,YAAY,CAAC,CAAC;AAM3E;;;;GAIG;AACH,SAAS,mBAAmB;IAC1B,MAAM,YAAY,GAAG,IAAI,gBAAY,EAA+B,CAAC;IACrE,YAAY,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC;IACxC,OAAO,YAAgC,CAAC;AAC1C,CAAC;AAED;;;;;GAKG;AACI,MAAM,aAAa,GAAG,CAAC,KAAU,EAAE,EAAE,CAC1C,OAAO,CAAC,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC;AADtD,QAAA,aAAa,iBACyC;AAEnE;;;;GAIG;AACH,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,IAAI,CAA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GAAG,GAAG,EAAE;IACzC,OAAO,gBAAQ,CAAC,MAAM,CACpB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,EAC7D,EAAE,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAClC,CAAC;AACJ,CAAC,CAAC;AALW,QAAA,sBAAsB,0BAKjC","sourcesContent":["import EventEmitter from 'events';\nimport crypto from 'crypto';\nimport { DEFAULT_ENDOWMENTS } from '@metamask/snap-controllers';\n\nconst NETWORK_APIS = ['fetch', 'WebSocket'];\n\nexport const ALL_APIS: string[] = [...DEFAULT_ENDOWMENTS, ...NETWORK_APIS];\n\ntype MockSnapProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap provider, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapProvider(): MockSnapProvider {\n const mockProvider = new EventEmitter() as Partial<MockSnapProvider>;\n mockProvider.request = async () => true;\n return mockProvider as MockSnapProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\n */\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\n */\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we have types for them and can use that to generate mocks if needed\nconst mockWindow = {\n WebSocket: MockClass,\n crypto,\n SubtleCrypto: MockClass,\n};\n\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\n */\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? (mockWindow as any)[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\n */\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { wallet: getMockSnapProvider() },\n );\n};\n"]}
@@ -1 +1,8 @@
1
+ /**
2
+ * Spawn a new worker thread to run the provided bundle in.
3
+ *
4
+ * @param bundlePath - The path to the bundle to run.
5
+ * @returns `null` if the worker ran successfully.
6
+ * @throws If the worker failed to run successfully.
7
+ */
1
8
  export declare function workerEval(bundlePath: string): Promise<null>;