@metamask/snaps-cli 8.3.0 → 8.4.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 (88) hide show
  1. package/CHANGELOG.md +38 -1
  2. package/dist/builders.cjs +11 -0
  3. package/dist/builders.cjs.map +1 -1
  4. package/dist/builders.d.cts +11 -0
  5. package/dist/builders.d.cts.map +1 -1
  6. package/dist/builders.d.mts +11 -0
  7. package/dist/builders.d.mts.map +1 -1
  8. package/dist/builders.mjs +11 -0
  9. package/dist/builders.mjs.map +1 -1
  10. package/dist/commands/build/build.cjs +15 -7
  11. package/dist/commands/build/build.cjs.map +1 -1
  12. package/dist/commands/build/build.d.cts +19 -3
  13. package/dist/commands/build/build.d.cts.map +1 -1
  14. package/dist/commands/build/build.d.mts +19 -3
  15. package/dist/commands/build/build.d.mts.map +1 -1
  16. package/dist/commands/build/build.mjs +15 -7
  17. package/dist/commands/build/build.mjs.map +1 -1
  18. package/dist/commands/build/index.cjs +15 -2
  19. package/dist/commands/build/index.cjs.map +1 -1
  20. package/dist/commands/build/index.d.cts.map +1 -1
  21. package/dist/commands/build/index.d.mts.map +1 -1
  22. package/dist/commands/build/index.mjs +15 -2
  23. package/dist/commands/build/index.mjs.map +1 -1
  24. package/dist/commands/manifest/implementation.cjs +1 -2
  25. package/dist/commands/manifest/implementation.cjs.map +1 -1
  26. package/dist/commands/manifest/implementation.d.cts.map +1 -1
  27. package/dist/commands/manifest/implementation.d.mts.map +1 -1
  28. package/dist/commands/manifest/implementation.mjs +1 -2
  29. package/dist/commands/manifest/implementation.mjs.map +1 -1
  30. package/dist/commands/sandbox/sandbox.cjs +4 -1
  31. package/dist/commands/sandbox/sandbox.cjs.map +1 -1
  32. package/dist/commands/sandbox/sandbox.d.cts.map +1 -1
  33. package/dist/commands/sandbox/sandbox.d.mts.map +1 -1
  34. package/dist/commands/sandbox/sandbox.mjs +4 -1
  35. package/dist/commands/sandbox/sandbox.mjs.map +1 -1
  36. package/dist/commands/watch/index.cjs +7 -4
  37. package/dist/commands/watch/index.cjs.map +1 -1
  38. package/dist/commands/watch/index.d.cts.map +1 -1
  39. package/dist/commands/watch/index.d.mts.map +1 -1
  40. package/dist/commands/watch/index.mjs +7 -4
  41. package/dist/commands/watch/index.mjs.map +1 -1
  42. package/dist/config.cjs +5 -0
  43. package/dist/config.cjs.map +1 -1
  44. package/dist/config.d.cts +71 -22
  45. package/dist/config.d.cts.map +1 -1
  46. package/dist/config.d.mts +71 -22
  47. package/dist/config.d.mts.map +1 -1
  48. package/dist/config.mjs +5 -0
  49. package/dist/config.mjs.map +1 -1
  50. package/dist/utils/cli.cjs +44 -4
  51. package/dist/utils/cli.cjs.map +1 -1
  52. package/dist/utils/cli.d.cts +9 -0
  53. package/dist/utils/cli.d.cts.map +1 -1
  54. package/dist/utils/cli.d.mts +9 -0
  55. package/dist/utils/cli.d.mts.map +1 -1
  56. package/dist/utils/cli.mjs +20 -1
  57. package/dist/utils/cli.mjs.map +1 -1
  58. package/dist/webpack/config.cjs +7 -1
  59. package/dist/webpack/config.cjs.map +1 -1
  60. package/dist/webpack/config.d.cts +16 -4
  61. package/dist/webpack/config.d.cts.map +1 -1
  62. package/dist/webpack/config.d.mts +16 -4
  63. package/dist/webpack/config.d.mts.map +1 -1
  64. package/dist/webpack/config.mjs +8 -2
  65. package/dist/webpack/config.mjs.map +1 -1
  66. package/dist/webpack/plugins.cjs +90 -2
  67. package/dist/webpack/plugins.cjs.map +1 -1
  68. package/dist/webpack/plugins.d.cts +36 -2
  69. package/dist/webpack/plugins.d.cts.map +1 -1
  70. package/dist/webpack/plugins.d.mts +36 -2
  71. package/dist/webpack/plugins.d.mts.map +1 -1
  72. package/dist/webpack/plugins.mjs +90 -3
  73. package/dist/webpack/plugins.mjs.map +1 -1
  74. package/dist/webpack/server.cjs +14 -3
  75. package/dist/webpack/server.cjs.map +1 -1
  76. package/dist/webpack/server.d.cts.map +1 -1
  77. package/dist/webpack/server.d.mts.map +1 -1
  78. package/dist/webpack/server.mjs +16 -5
  79. package/dist/webpack/server.mjs.map +1 -1
  80. package/dist/webpack/utils.cjs +29 -1
  81. package/dist/webpack/utils.cjs.map +1 -1
  82. package/dist/webpack/utils.d.cts +9 -1
  83. package/dist/webpack/utils.d.cts.map +1 -1
  84. package/dist/webpack/utils.d.mts +9 -1
  85. package/dist/webpack/utils.d.mts.map +1 -1
  86. package/dist/webpack/utils.mjs +27 -0
  87. package/dist/webpack/utils.mjs.map +1 -1
  88. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"config.cjs","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":";;;;;;AAAA,0FAAgE;AAChE,oGAAwE;AAExE,kFAAiD;AAEjD,qCAAsE;AACtE,qEAA+D;AAE/D,iDAAoD;AACpD,2CAKmB;AACnB,uCAQiB;AA0BjB;;;;;;;;;;;;;;;;;GAiBG;AACI,KAAK,UAAU,uBAAuB,CAC3C,MAAuB,EACvB,UAA0B;IACxB,QAAQ,EAAE,MAAM,CAAC,QAAQ;CAC1B;IAED,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC;IAC1C,MAAM,eAAe,GACnB,MAAM,CAAC,KAAK,CAAC,QAAQ,IAAI,IAAI,8BAAoB,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAE3E,OAAO;QACL;;;;;;;WAOG;QACH,MAAM,EAAE,gBAAgB,yBAAiB,EAAE;QAE3C;;;;;WAKG;QACH,IAAI,EAAE,YAAY;QAElB;;;;WAIG;QACH,KAAK,EAAE,MAAM,CAAC,KAAK;QAEnB;;;;;WAKG;QACH,OAAO,EAAE,IAAA,kBAAU,EAAC,MAAM,CAAC,SAAS,CAAC;QAErC;;;;;;WAMG;QACH,KAAK,EAAE,MAAM;QAEb;;;;WAIG;QACH,MAAM,EAAE;YACN;;;;;;eAMG;YACH,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,KAAK;YAE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C,QAAQ,CAAC;gBACxC,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM;aAC5B,CAAC;YAEF;;;;eAIG;YACH,OAAO,CAAC,KAAK;gBACX,IAAI,0BAAgB,CAClB;oBACE,KAAK,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;iBAC9B,EACD,OAAO,CAAC,OAAO,CAChB;YAEH,OAAO,CAAC,OAAO;gBACb,IAAI,8CAAoB,CAAC;oBACvB,YAAY,EAAE,CAAC;oBACf,QAAQ,EAAE,QAAQ;oBAClB,YAAY,EAAE,KAAK;iBACpB,CAAC;YAEJ;;;eAGG;YACH,CAAC,MAAM,CAAC,SAAS,KAAK,IAAI;gBACxB,CAAC,MAAM,CAAC,SAAS,KAAK,KAAK,IAAI,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;gBACxD,IAAI,uBAAa,CAAC;oBAChB,MAAM,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC;iBAC7B,CAAC;SACL,CAAC,MAAM,CAAC,OAAO,CAAC;QAEjB;;;;WAIG;QACH,YAAY,EAAE;YACZ,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,QAAQ;YAEhC;;;eAGG;YACH,OAAO,EAAE,KAAK;YAEd;;eAEG;YACH,SAAS,EAAE;gBACT,IAAI,+BAAY,CAAC;oBACf,QAAQ,EAAE,IAAI;iBACf,CAAC;aACH;SACF;QAED;;;;;WAKG;QACH,WAAW,EAAE;YACX;;;;;eAKG;YACH,KAAK,EAAE,KAAK;SACb;QAED;;;;;WAKG;QACH,qBAAqB,EAAE;YACrB;;;eAGG;YACH,KAAK,EAAE,MAAM;SACd;KACF,CAAC;AACJ,CAAC;AA9WD,0DA8WC","sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-webpack-plugin';\nimport ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';\nimport type { Ora } from 'ora';\nimport TerserPlugin from 'terser-webpack-plugin';\nimport type { Configuration } from 'webpack';\nimport { DefinePlugin, ProgressPlugin, ProvidePlugin } from 'webpack';\nimport { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';\n\nimport { getFunctionLoader, wasm } from './loaders';\nimport {\n SnapsBuiltInResolver,\n SnapsBundleWarningsPlugin,\n SnapsStatsPlugin,\n SnapsWatchPlugin,\n} from './plugins';\nimport {\n BROWSERSLIST_FILE,\n getDefaultLoader,\n getDevTool,\n getEnvironmentVariables,\n getFallbacks,\n getImageSVG,\n getProgressHandler,\n} from './utils';\nimport type { ProcessedConfig } from '../config';\n\nexport type WebpackOptions = {\n /**\n * Whether to analyze the bundle.\n */\n analyze?: boolean;\n\n /**\n * Whether to watch for changes.\n */\n watch?: boolean;\n\n /**\n * Whether to evaluate the bundle. If this is set, it will override the\n * `evaluate` option in the config object.\n */\n evaluate?: boolean;\n\n /**\n * The spinner to use for logging.\n */\n spinner?: Ora;\n};\n\n/**\n * Get the default Webpack configuration. This is the configuration that will\n * be used if the user doesn't provide a custom Webpack configuration. The\n * configuration is based on the snap config.\n *\n * The default configuration includes:\n *\n * - `SWC` to transpile TypeScript and JavaScript files.\n * - `TerserPlugin` to minify the bundle.\n * - `SnapsWebpackPlugin` to validate the bundle and update the manifest.\n *\n * It can be customized through the `customizeWebpackConfig` function in the\n * snap config, but in most cases, you shouldn't need to do that.\n *\n * @param config - The processed snap Webpack config.\n * @param options - The Webpack options.\n * @returns The default Webpack configuration.\n */\nexport async function getDefaultConfiguration(\n config: ProcessedConfig,\n options: WebpackOptions = {\n evaluate: config.evaluate,\n },\n): Promise<Configuration> {\n const spinnerText = options.spinner?.text;\n const builtInResolver =\n config.stats.builtIns && new SnapsBuiltInResolver(config.stats.builtIns);\n\n return {\n /**\n * The target is set to `browserslist` so that Webpack will compile the\n * bundle to support the browsers specified in the `.browserslistrc` file.\n * This Browserslist file contains the browsers that are supported by\n * MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/target/\n */\n target: `browserslist:${BROWSERSLIST_FILE}`,\n\n /**\n * The mode is set to `production` by default, so that Webpack will minify\n * and optimize the bundle.\n *\n * @see https://webpack.js.org/configuration/mode/\n */\n mode: 'production',\n\n /**\n * The entry point is set to the `input` value from the config object.\n *\n * @see https://webpack.js.org/configuration/entry-context/\n */\n entry: config.input,\n\n /**\n * The devtool option controls how source maps are generated. We set it to\n * the `sourceMap` value from the config object.\n *\n * @see https://webpack.js.org/configuration/devtool/\n */\n devtool: getDevTool(config.sourceMap),\n\n /**\n * The stats option controls how much information is printed to the console\n * when Webpack is running. We set it to `none` so that we can control the\n * output ourselves.\n *\n * @see https://webpack.js.org/configuration/stats/\n */\n stats: 'none',\n\n /**\n * The output options.\n *\n * @see https://webpack.js.org/configuration/output/\n */\n output: {\n /**\n * This indicates whether Webpack should clear the output directory\n * before building. We set it to the `clean` value from the config\n * object.\n *\n * @see https://webpack.js.org/configuration/output/#outputclean\n */\n clean: config.output.clean,\n\n /**\n * The filename of the bundle. We set it to the `filename` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputfilename\n */\n filename: config.output.filename,\n\n /**\n * The path to the output directory. We set it to the `path` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputpath\n */\n path: config.output.path,\n\n /**\n * The public path of the bundle. We set it to `/` by default, so that\n * the bundle can be loaded from the root of the server.\n *\n * @see https://webpack.js.org/configuration/output/#outputpublicpath\n */\n publicPath: '/',\n\n /**\n * The library configuration. This tells Webpack how to export the\n * bundle.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrary\n */\n library: {\n /**\n * This tells Webpack to export the bundle via assignment to module.exports.\n * We do this to mimic CommonJS, but still allow for usage of async initialization logic\n * via top level await.\n *\n * CommonJS is currently the only supported format for MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrarytarget\n */\n type: 'assign',\n name: 'module.exports',\n },\n\n /**\n * The chunk format. This tells Webpack how to export chunks. This is\n * required because we use browserslist to target browsers, but Snaps are\n * not fully compatible with browser APIs (such as `window` and\n * `document`).\n *\n * @see https://webpack.js.org/configuration/output/#outputchunkformat\n */\n chunkFormat: 'commonjs',\n },\n\n /**\n * The module configuration. This is where we tell Webpack how to handle\n * different types of files.\n *\n * @see https://webpack.js.org/configuration/module/\n */\n module: {\n rules: [\n {\n test: /\\.(js|jsx|mjs|cjs|ts|tsx)$/u,\n exclude: /node_modules/u,\n use: await getDefaultLoader(config),\n },\n\n /**\n * This allows importing modules that uses `.js` and not `.mjs` for the\n * ES build.\n *\n * @see https://webpack.js.org/configuration/module/#resolvefullyspecified\n */\n {\n test: /\\.m?js$/u,\n resolve: {\n fullySpecified: false,\n },\n },\n\n /**\n * This allows importing `.svg` files as a string.\n */\n config.features.images && {\n test: /\\.svg$/u,\n // `asset/source` returns the source as a UTF-8 string.\n type: 'asset/source',\n },\n\n /**\n * This allows importing `.png` files as a data URL.\n */\n config.features.images && {\n test: /\\.png$/u,\n type: 'asset/inline',\n generator: {\n dataUrl: getImageSVG.bind(null, 'image/png'),\n },\n },\n\n /**\n * This allows importing `.jpe?g` files as a data URL.\n */\n config.features.images && {\n test: /\\.jpe?g$/u,\n type: 'asset/inline',\n generator: {\n dataUrl: getImageSVG.bind(null, 'image/jpeg'),\n },\n },\n\n config.experimental.wasm && {\n test: /\\.wasm$/u,\n use: getFunctionLoader(wasm, {}),\n },\n ],\n },\n\n /**\n * The resolve configuration. This tells Webpack how to resolve imports.\n * We set it to resolve `.js` and `.ts` files.\n *\n * @see https://webpack.js.org/configuration/resolve/\n */\n resolve: {\n /**\n * The extensions to resolve. We set it to resolve `.(c|m)?jsx?` and\n * `.tsx?` files.\n */\n extensions: ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'],\n\n /**\n * The fallback options. This tells Webpack how to handle imports that\n * aren't resolved. By default, we set Node.js built-ins to `false`, so\n * that they are ignored.\n */\n fallback: getFallbacks(config.polyfills),\n\n /**\n * The plugins to use. We use the {@link SnapsBuiltInResolver} to show\n * warnings about using Node.js built-ins, when no fallback is specified.\n */\n plugins: [builtInResolver],\n },\n\n /**\n * The plugins to use.\n *\n * @see https://webpack.js.org/configuration/plugins/\n */\n plugins: [\n /**\n * The `ForkTsCheckerWebpackPlugin` is a Webpack plugin that checks\n * Typescript type definitions, it does this in a separate process for speed.\n */\n config.typescript.enabled &&\n new ForkTsCheckerWebpackPlugin({\n typescript: {\n build: true,\n configFile: config.typescript.configFile,\n },\n }),\n\n /**\n * The `SnapsWebpackPlugin` is a Webpack plugin that checks and updates\n * the manifest file, and evaluates the bundle in SES. While not strictly\n * required, it's highly recommended to use this plugin.\n */\n new SnapsWebpackPlugin(\n {\n manifestPath: config.manifest.path,\n writeManifest: config.manifest.update,\n eval: options.evaluate,\n },\n options.spinner,\n ),\n\n /**\n * The `SnapsStatsPlugin` is a Webpack plugin that handles the stats\n * output. It's used to show the stats in the terminal, in a format that\n * is easy to read.\n */\n new SnapsStatsPlugin({ verbose: config.stats.verbose }, options.spinner),\n\n /**\n * The `DefinePlugin` is a Webpack plugin that adds static values to the\n * bundle. We use it to add the `NODE_DEBUG`, `NODE_ENV`, and `DEBUG`\n * environment variables, as well as any custom environment\n * variables (as `process.env`).\n */\n new DefinePlugin(getEnvironmentVariables(config.environment)),\n\n /**\n * The `ProgressPlugin` is a Webpack plugin that logs the progress of\n * the build. We set it to log the progress to the spinner.\n */\n new ProgressPlugin({\n handler: getProgressHandler(options.spinner, spinnerText),\n }),\n\n /**\n * The `SnapsBundleWarningPlugin` is a Webpack plugin that shows a\n * warning when the bundle is potentially incompatible with MetaMask\n * Snaps.\n */\n new SnapsBundleWarningsPlugin({\n builtInResolver,\n builtIns: Boolean(config.stats.builtIns),\n buffer: config.stats.buffer,\n }),\n\n /**\n * The `WatchPlugin` is a Webpack plugin that adds extra files to watch\n * for changes. This is useful for rebuilding the bundle when the\n * manifest file changes.\n */\n options.watch &&\n new SnapsWatchPlugin(\n {\n files: [config.manifest.path],\n },\n options.spinner,\n ),\n\n options.analyze &&\n new BundleAnalyzerPlugin({\n analyzerPort: 0,\n logLevel: 'silent',\n openAnalyzer: false,\n }),\n\n /**\n * The `ProviderPlugin` is a Webpack plugin that automatically load\n * modules instead of having to import or require them everywhere.\n */\n (config.polyfills === true ||\n (config.polyfills !== false && config.polyfills.buffer)) &&\n new ProvidePlugin({\n Buffer: ['buffer', 'Buffer'],\n }),\n ].filter(Boolean),\n\n /**\n * The optimization configuration. This tells Webpack how to optimize the\n * bundle. Most of the time, you won't need to change this, as the default\n * options set by the `mode` option are sufficient.\n */\n optimization: {\n minimize: config.output.minimize,\n\n /**\n * We disable the nodeEnv optimization as we already add process.NODE_ENV\n * via the DefinePlugin in the section above this.\n */\n nodeEnv: false,\n\n /**\n * The minimizer to use. We set it to use the `TerserPlugin`.\n */\n minimizer: [\n new TerserPlugin({\n parallel: true,\n }),\n ],\n },\n\n /**\n * The performance configuration. This tells Webpack how to handle\n * performance hints.\n *\n * @see https://webpack.js.org/configuration/performance/\n */\n performance: {\n /**\n * The hints to show. We set it to `false`, so that we don't get\n * performance hints, as they are not relevant for Snaps.\n *\n * @see https://webpack.js.org/configuration/performance/#performancehints\n */\n hints: false,\n },\n\n /**\n * The infrastructure logging configuration. This tells Webpack how to\n * log messages.\n *\n * @see https://webpack.js.org/configuration/infrastructure-logging\n */\n infrastructureLogging: {\n /**\n * The level of logging to use. We set it to `none`, so that we can\n * control the output ourselves.\n */\n level: 'none',\n },\n };\n}\n"]}
1
+ {"version":3,"file":"config.cjs","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":";;;;;;AAAA,0FAAgE;AAChE,oGAAwE;AAExE,kFAAiD;AAEjD,qCAAsE;AACtE,qEAA+D;AAE/D,iDAAoD;AACpD,2CAMmB;AACnB,uCAQiB;AAwCjB;;;;;;;;;;;;;;;;;GAiBG;AACI,KAAK,UAAU,uBAAuB,CAC3C,MAAuB,EACvB,UAA0B;IACxB,QAAQ,EAAE,MAAM,CAAC,QAAQ;CAC1B;IAED,MAAM,WAAW,GAAG,OAAO,CA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AK,IAAI,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;gBACxD,IAAI,uBAAa,CAAC;oBAChB,MAAM,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC;iBAC7B,CAAC;SACL,CAAC,MAAM,CAAC,OAAO,CAAC;QAEjB;;;;WAIG;QACH,YAAY,EAAE;YACZ,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,QAAQ;YAEhC;;;eAGG;YACH,OAAO,EAAE,KAAK;YAEd;;eAEG;YACH,SAAS,EAAE;gBACT,IAAI,+BAAY,CAAC;oBACf,QAAQ,EAAE,IAAI;iBACf,CAAC;aACH;SACF;QAED;;;;;WAKG;QACH,WAAW,EAAE;YACX;;;;;eAKG;YACH,KAAK,EAAE,KAAK;SACb;QAED;;;;;WAKG;QACH,qBAAqB,EAAE;YACrB;;;eAGG;YACH,KAAK,EAAE,MAAM;SACd;KACF,CAAC;AACJ,CAAC;AAxXD,0DAwXC","sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-webpack-plugin';\nimport ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';\nimport type { Ora } from 'ora';\nimport TerserPlugin from 'terser-webpack-plugin';\nimport type { Configuration } from 'webpack';\nimport { DefinePlugin, ProgressPlugin, ProvidePlugin } from 'webpack';\nimport { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';\n\nimport { getFunctionLoader, wasm } from './loaders';\nimport {\n PreinstalledSnapsBundlePlugin,\n SnapsBuiltInResolver,\n SnapsBundleWarningsPlugin,\n SnapsStatsPlugin,\n SnapsWatchPlugin,\n} from './plugins';\nimport {\n BROWSERSLIST_FILE,\n getDefaultLoader,\n getDevTool,\n getEnvironmentVariables,\n getFallbacks,\n getImageSVG,\n getProgressHandler,\n} from './utils';\nimport type { ProcessedConfig } from '../config';\n\nexport type WebpackOptions = {\n /**\n * Whether to analyze the bundle.\n */\n analyze?: boolean;\n\n /**\n * Whether to evaluate the bundle. If this is set, it will override the\n * `evaluate` option in the config object.\n */\n evaluate?: boolean;\n\n /**\n * Whether to build the Snap as a preinstalled Snap. If this is set, it will\n * output a `preinstalled-snap.json` instead of a regular bundle.\n */\n preinstalled?: boolean;\n\n /**\n * The preinstalled Snap options to use. See {@link SnapConfig.preinstalled}\n * for more details.\n *\n * This is ignored if `preinstalled` is not set to `true`.\n */\n preinstalledOptions?: ProcessedConfig['preinstalled'];\n\n /**\n * The spinner to use for logging.\n */\n spinner?: Ora;\n\n /**\n * Whether to watch for changes.\n */\n watch?: boolean;\n};\n\n/**\n * Get the default Webpack configuration. This is the configuration that will\n * be used if the user doesn't provide a custom Webpack configuration. The\n * configuration is based on the snap config.\n *\n * The default configuration includes:\n *\n * - `SWC` to transpile TypeScript and JavaScript files.\n * - `TerserPlugin` to minify the bundle.\n * - `SnapsWebpackPlugin` to validate the bundle and update the manifest.\n *\n * It can be customized through the `customizeWebpackConfig` function in the\n * snap config, but in most cases, you shouldn't need to do that.\n *\n * @param config - The processed snap Webpack config.\n * @param options - The Webpack options.\n * @returns The default Webpack configuration.\n */\nexport async function getDefaultConfiguration(\n config: ProcessedConfig,\n options: WebpackOptions = {\n evaluate: config.evaluate,\n },\n): Promise<Configuration> {\n const spinnerText = options.spinner?.text;\n const builtInResolver =\n config.stats.builtIns && new SnapsBuiltInResolver(config.stats.builtIns);\n\n return {\n /**\n * The target is set to `browserslist` so that Webpack will compile the\n * bundle to support the browsers specified in the `.browserslistrc` file.\n * This Browserslist file contains the browsers that are supported by\n * MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/target/\n */\n target: `browserslist:${BROWSERSLIST_FILE}`,\n\n /**\n * The mode is set to `production` by default, so that Webpack will minify\n * and optimize the bundle.\n *\n * @see https://webpack.js.org/configuration/mode/\n */\n mode: 'production',\n\n /**\n * The entry point is set to the `input` value from the config object.\n *\n * @see https://webpack.js.org/configuration/entry-context/\n */\n entry: config.input,\n\n /**\n * The devtool option controls how source maps are generated. We set it to\n * the `sourceMap` value from the config object.\n *\n * @see https://webpack.js.org/configuration/devtool/\n */\n devtool: getDevTool(config.sourceMap),\n\n /**\n * The stats option controls how much information is printed to the console\n * when Webpack is running. We set it to `none` so that we can control the\n * output ourselves.\n *\n * @see https://webpack.js.org/configuration/stats/\n */\n stats: 'none',\n\n /**\n * The output options.\n *\n * @see https://webpack.js.org/configuration/output/\n */\n output: {\n /**\n * This indicates whether Webpack should clear the output directory\n * before building. We set it to the `clean` value from the config\n * object.\n *\n * @see https://webpack.js.org/configuration/output/#outputclean\n */\n clean: config.output.clean,\n\n /**\n * The filename of the bundle. We set it to the `filename` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputfilename\n */\n filename: config.output.filename,\n\n /**\n * The path to the output directory. We set it to the `path` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputpath\n */\n path: config.output.path,\n\n /**\n * The public path of the bundle. We set it to `/` by default, so that\n * the bundle can be loaded from the root of the server.\n *\n * @see https://webpack.js.org/configuration/output/#outputpublicpath\n */\n publicPath: '/',\n\n /**\n * The library configuration. This tells Webpack how to export the\n * bundle.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrary\n */\n library: {\n /**\n * This tells Webpack to export the bundle via assignment to module.exports.\n * We do this to mimic CommonJS, but still allow for usage of async initialization logic\n * via top level await.\n *\n * CommonJS is currently the only supported format for MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrarytarget\n */\n type: 'assign',\n name: 'module.exports',\n },\n\n /**\n * The chunk format. This tells Webpack how to export chunks. This is\n * required because we use browserslist to target browsers, but Snaps are\n * not fully compatible with browser APIs (such as `window` and\n * `document`).\n *\n * @see https://webpack.js.org/configuration/output/#outputchunkformat\n */\n chunkFormat: 'commonjs',\n },\n\n /**\n * The module configuration. This is where we tell Webpack how to handle\n * different types of files.\n *\n * @see https://webpack.js.org/configuration/module/\n */\n module: {\n rules: [\n {\n test: /\\.(js|jsx|mjs|cjs|ts|tsx)$/u,\n exclude: /node_modules/u,\n use: await getDefaultLoader(config),\n },\n\n /**\n * This allows importing modules that uses `.js` and not `.mjs` for the\n * ES build.\n *\n * @see https://webpack.js.org/configuration/module/#resolvefullyspecified\n */\n {\n test: /\\.m?js$/u,\n resolve: {\n fullySpecified: false,\n },\n },\n\n /**\n * This allows importing `.svg` files as a string.\n */\n config.features.images && {\n test: /\\.svg$/u,\n // `asset/source` returns the source as a UTF-8 string.\n type: 'asset/source',\n },\n\n /**\n * This allows importing `.png` files as a data URL.\n */\n config.features.images && {\n test: /\\.png$/u,\n type: 'asset/inline',\n generator: {\n dataUrl: getImageSVG.bind(null, 'image/png'),\n },\n },\n\n /**\n * This allows importing `.jpe?g` files as a data URL.\n */\n config.features.images && {\n test: /\\.jpe?g$/u,\n type: 'asset/inline',\n generator: {\n dataUrl: getImageSVG.bind(null, 'image/jpeg'),\n },\n },\n\n config.experimental.wasm && {\n test: /\\.wasm$/u,\n use: getFunctionLoader(wasm, {}),\n },\n ],\n },\n\n /**\n * The resolve configuration. This tells Webpack how to resolve imports.\n * We set it to resolve `.js` and `.ts` files.\n *\n * @see https://webpack.js.org/configuration/resolve/\n */\n resolve: {\n /**\n * The extensions to resolve. We set it to resolve `.(c|m)?jsx?` and\n * `.tsx?` files.\n */\n extensions: ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'],\n\n /**\n * The fallback options. This tells Webpack how to handle imports that\n * aren't resolved. By default, we set Node.js built-ins to `false`, so\n * that they are ignored.\n */\n fallback: getFallbacks(config.polyfills),\n\n /**\n * The plugins to use. We use the {@link SnapsBuiltInResolver} to show\n * warnings about using Node.js built-ins, when no fallback is specified.\n */\n plugins: [builtInResolver],\n },\n\n /**\n * The plugins to use.\n *\n * @see https://webpack.js.org/configuration/plugins/\n */\n plugins: [\n /**\n * The `ForkTsCheckerWebpackPlugin` is a Webpack plugin that checks\n * Typescript type definitions, it does this in a separate process for speed.\n */\n config.typescript.enabled &&\n new ForkTsCheckerWebpackPlugin({\n typescript: {\n build: true,\n configFile: config.typescript.configFile,\n },\n }),\n\n /**\n * The `SnapsWebpackPlugin` is a Webpack plugin that checks and updates\n * the manifest file, and evaluates the bundle in SES. While not strictly\n * required, it's highly recommended to use this plugin.\n */\n new SnapsWebpackPlugin(\n {\n manifestPath: config.manifest.path,\n writeManifest: config.manifest.update,\n eval: options.evaluate,\n },\n options.spinner,\n ),\n\n /**\n * The `SnapsStatsPlugin` is a Webpack plugin that handles the stats\n * output. It's used to show the stats in the terminal, in a format that\n * is easy to read.\n */\n new SnapsStatsPlugin({ verbose: config.stats.verbose }, options.spinner),\n\n /**\n * The `DefinePlugin` is a Webpack plugin that adds static values to the\n * bundle. We use it to add the `NODE_DEBUG`, `NODE_ENV`, and `DEBUG`\n * environment variables, as well as any custom environment\n * variables (as `process.env`).\n */\n new DefinePlugin(getEnvironmentVariables(config.environment)),\n\n /**\n * The `ProgressPlugin` is a Webpack plugin that logs the progress of\n * the build. We set it to log the progress to the spinner.\n */\n new ProgressPlugin({\n handler: getProgressHandler(options.spinner, spinnerText),\n }),\n\n /**\n * The `SnapsBundleWarningPlugin` is a Webpack plugin that shows a\n * warning when the bundle is potentially incompatible with MetaMask\n * Snaps.\n */\n new SnapsBundleWarningsPlugin({\n builtInResolver,\n builtIns: Boolean(config.stats.builtIns),\n buffer: config.stats.buffer,\n }),\n\n /**\n * The `WatchPlugin` is a Webpack plugin that adds extra files to watch\n * for changes. This is useful for rebuilding the bundle when the\n * manifest file changes.\n */\n options.watch &&\n new SnapsWatchPlugin(\n {\n manifestPath: config.manifest.path,\n },\n options.spinner,\n ),\n\n options.analyze &&\n new BundleAnalyzerPlugin({\n analyzerPort: 0,\n logLevel: 'silent',\n openAnalyzer: false,\n }),\n\n options.preinstalled &&\n new PreinstalledSnapsBundlePlugin(\n {\n manifestPath: config.manifest.path,\n outputName: config.output.filename,\n preinstalledOptions: options.preinstalledOptions,\n },\n options.spinner,\n ),\n\n /**\n * The `ProviderPlugin` is a Webpack plugin that automatically load\n * modules instead of having to import or require them everywhere.\n */\n (config.polyfills === true ||\n (config.polyfills !== false && config.polyfills.buffer)) &&\n new ProvidePlugin({\n Buffer: ['buffer', 'Buffer'],\n }),\n ].filter(Boolean),\n\n /**\n * The optimization configuration. This tells Webpack how to optimize the\n * bundle. Most of the time, you won't need to change this, as the default\n * options set by the `mode` option are sufficient.\n */\n optimization: {\n minimize: config.output.minimize,\n\n /**\n * We disable the nodeEnv optimization as we already add process.NODE_ENV\n * via the DefinePlugin in the section above this.\n */\n nodeEnv: false,\n\n /**\n * The minimizer to use. We set it to use the `TerserPlugin`.\n */\n minimizer: [\n new TerserPlugin({\n parallel: true,\n }),\n ],\n },\n\n /**\n * The performance configuration. This tells Webpack how to handle\n * performance hints.\n *\n * @see https://webpack.js.org/configuration/performance/\n */\n performance: {\n /**\n * The hints to show. We set it to `false`, so that we don't get\n * performance hints, as they are not relevant for Snaps.\n *\n * @see https://webpack.js.org/configuration/performance/#performancehints\n */\n hints: false,\n },\n\n /**\n * The infrastructure logging configuration. This tells Webpack how to\n * log messages.\n *\n * @see https://webpack.js.org/configuration/infrastructure-logging\n */\n infrastructureLogging: {\n /**\n * The level of logging to use. We set it to `none`, so that we can\n * control the output ourselves.\n */\n level: 'none',\n },\n };\n}\n"]}
@@ -6,19 +6,31 @@ export type WebpackOptions = {
6
6
  * Whether to analyze the bundle.
7
7
  */
8
8
  analyze?: boolean;
9
- /**
10
- * Whether to watch for changes.
11
- */
12
- watch?: boolean;
13
9
  /**
14
10
  * Whether to evaluate the bundle. If this is set, it will override the
15
11
  * `evaluate` option in the config object.
16
12
  */
17
13
  evaluate?: boolean;
14
+ /**
15
+ * Whether to build the Snap as a preinstalled Snap. If this is set, it will
16
+ * output a `preinstalled-snap.json` instead of a regular bundle.
17
+ */
18
+ preinstalled?: boolean;
19
+ /**
20
+ * The preinstalled Snap options to use. See {@link SnapConfig.preinstalled}
21
+ * for more details.
22
+ *
23
+ * This is ignored if `preinstalled` is not set to `true`.
24
+ */
25
+ preinstalledOptions?: ProcessedConfig['preinstalled'];
18
26
  /**
19
27
  * The spinner to use for logging.
20
28
  */
21
29
  spinner?: Ora;
30
+ /**
31
+ * Whether to watch for changes.
32
+ */
33
+ watch?: boolean;
22
34
  };
23
35
  /**
24
36
  * Get the default Webpack configuration. This is the configuration that will
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.cts","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;AAE/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB;AAoB7C,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAkB;AAEjD,MAAM,MAAM,cAAc,GAAG;IAC3B;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;OAEG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;CACf,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,eAAe,EACvB,OAAO,GAAE,cAER,GACA,OAAO,CAAC,aAAa,CAAC,CAyWxB"}
1
+ {"version":3,"file":"config.d.cts","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;AAE/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB;AAqB7C,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAkB;AAEjD,MAAM,MAAM,cAAc,GAAG;IAC3B;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,eAAe,CAAC,cAAc,CAAC,CAAC;IAEtD;;OAEG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;IAEd;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,eAAe,EACvB,OAAO,GAAE,cAER,GACA,OAAO,CAAC,aAAa,CAAC,CAmXxB"}
@@ -6,19 +6,31 @@ export type WebpackOptions = {
6
6
  * Whether to analyze the bundle.
7
7
  */
8
8
  analyze?: boolean;
9
- /**
10
- * Whether to watch for changes.
11
- */
12
- watch?: boolean;
13
9
  /**
14
10
  * Whether to evaluate the bundle. If this is set, it will override the
15
11
  * `evaluate` option in the config object.
16
12
  */
17
13
  evaluate?: boolean;
14
+ /**
15
+ * Whether to build the Snap as a preinstalled Snap. If this is set, it will
16
+ * output a `preinstalled-snap.json` instead of a regular bundle.
17
+ */
18
+ preinstalled?: boolean;
19
+ /**
20
+ * The preinstalled Snap options to use. See {@link SnapConfig.preinstalled}
21
+ * for more details.
22
+ *
23
+ * This is ignored if `preinstalled` is not set to `true`.
24
+ */
25
+ preinstalledOptions?: ProcessedConfig['preinstalled'];
18
26
  /**
19
27
  * The spinner to use for logging.
20
28
  */
21
29
  spinner?: Ora;
30
+ /**
31
+ * Whether to watch for changes.
32
+ */
33
+ watch?: boolean;
22
34
  };
23
35
  /**
24
36
  * Get the default Webpack configuration. This is the configuration that will
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.mts","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;AAE/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB;AAoB7C,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAkB;AAEjD,MAAM,MAAM,cAAc,GAAG;IAC3B;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;OAEG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;CACf,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,eAAe,EACvB,OAAO,GAAE,cAER,GACA,OAAO,CAAC,aAAa,CAAC,CAyWxB"}
1
+ {"version":3,"file":"config.d.mts","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;AAE/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB;AAqB7C,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAkB;AAEjD,MAAM,MAAM,cAAc,GAAG;IAC3B;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,eAAe,CAAC,cAAc,CAAC,CAAC;IAEtD;;OAEG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;IAEd;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,eAAe,EACvB,OAAO,GAAE,cAER,GACA,OAAO,CAAC,aAAa,CAAC,CAmXxB"}
@@ -13,7 +13,7 @@ import $webpack from "webpack";
13
13
  const { DefinePlugin, ProgressPlugin, ProvidePlugin } = $webpack;
14
14
  import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
15
15
  import { getFunctionLoader, wasm } from "./loaders/index.mjs";
16
- import { SnapsBuiltInResolver, SnapsBundleWarningsPlugin, SnapsStatsPlugin, SnapsWatchPlugin } from "./plugins.mjs";
16
+ import { PreinstalledSnapsBundlePlugin, SnapsBuiltInResolver, SnapsBundleWarningsPlugin, SnapsStatsPlugin, SnapsWatchPlugin } from "./plugins.mjs";
17
17
  import { BROWSERSLIST_FILE, getDefaultLoader, getDevTool, getEnvironmentVariables, getFallbacks, getImageSVG, getProgressHandler } from "./utils.mjs";
18
18
  /**
19
19
  * Get the default Webpack configuration. This is the configuration that will
@@ -287,7 +287,7 @@ export async function getDefaultConfiguration(config, options = {
287
287
  */
288
288
  options.watch &&
289
289
  new SnapsWatchPlugin({
290
- files: [config.manifest.path],
290
+ manifestPath: config.manifest.path,
291
291
  }, options.spinner),
292
292
  options.analyze &&
293
293
  new BundleAnalyzerPlugin({
@@ -295,6 +295,12 @@ export async function getDefaultConfiguration(config, options = {
295
295
  logLevel: 'silent',
296
296
  openAnalyzer: false,
297
297
  }),
298
+ options.preinstalled &&
299
+ new PreinstalledSnapsBundlePlugin({
300
+ manifestPath: config.manifest.path,
301
+ outputName: config.output.filename,
302
+ preinstalledOptions: options.preinstalledOptions,
303
+ }, options.spinner),
298
304
  /**
299
305
  * The `ProviderPlugin` is a Webpack plugin that automatically load
300
306
  * modules instead of having to import or require them everywhere.
@@ -1 +1 @@
1
- {"version":3,"file":"config.mjs","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,kBAAkB,uCAAuC;AAChE,OAAO,2BAA0B,uCAAuC;;AAExE,OAAO,aAAY,8BAA8B;;;;AAGjD,OAAO,EAAE,oBAAoB,EAAE,gCAAgC;AAE/D,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,4BAAkB;AACpD,OAAO,EACL,oBAAoB,EACpB,yBAAyB,EACzB,gBAAgB,EAChB,gBAAgB,EACjB,sBAAkB;AACnB,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,UAAU,EACV,uBAAuB,EACvB,YAAY,EACZ,WAAW,EACX,kBAAkB,EACnB,oBAAgB;AA0BjB;;;;;;;;;;;;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Q,EAAE,QAAQ,CAAC;iBAC7B,CAAC;SACL,CAAC,MAAM,CAAC,OAAO,CAAC;QAEjB;;;;WAIG;QACH,YAAY,EAAE;YACZ,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,QAAQ;YAEhC;;;eAGG;YACH,OAAO,EAAE,KAAK;YAEd;;eAEG;YACH,SAAS,EAAE;gBACT,IAAI,YAAY,CAAC;oBACf,QAAQ,EAAE,IAAI;iBACf,CAAC;aACH;SACF;QAED;;;;;WAKG;QACH,WAAW,EAAE;YACX;;;;;eAKG;YACH,KAAK,EAAE,KAAK;SACb;QAED;;;;;WAKG;QACH,qBAAqB,EAAE;YACrB;;;eAGG;YACH,KAAK,EAAE,MAAM;SACd;KACF,CAAC;AACJ,CAAC","sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-webpack-plugin';\nimport ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';\nimport type { Ora } from 'ora';\nimport TerserPlugin from 'terser-webpack-plugin';\nimport type { Configuration } from 'webpack';\nimport { DefinePlugin, ProgressPlugin, ProvidePlugin } from 'webpack';\nimport { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';\n\nimport { getFunctionLoader, wasm } from './loaders';\nimport {\n SnapsBuiltInResolver,\n SnapsBundleWarningsPlugin,\n SnapsStatsPlugin,\n SnapsWatchPlugin,\n} from './plugins';\nimport {\n BROWSERSLIST_FILE,\n getDefaultLoader,\n getDevTool,\n getEnvironmentVariables,\n getFallbacks,\n getImageSVG,\n getProgressHandler,\n} from './utils';\nimport type { ProcessedConfig } from '../config';\n\nexport type WebpackOptions = {\n /**\n * Whether to analyze the bundle.\n */\n analyze?: boolean;\n\n /**\n * Whether to watch for changes.\n */\n watch?: boolean;\n\n /**\n * Whether to evaluate the bundle. If this is set, it will override the\n * `evaluate` option in the config object.\n */\n evaluate?: boolean;\n\n /**\n * The spinner to use for logging.\n */\n spinner?: Ora;\n};\n\n/**\n * Get the default Webpack configuration. This is the configuration that will\n * be used if the user doesn't provide a custom Webpack configuration. The\n * configuration is based on the snap config.\n *\n * The default configuration includes:\n *\n * - `SWC` to transpile TypeScript and JavaScript files.\n * - `TerserPlugin` to minify the bundle.\n * - `SnapsWebpackPlugin` to validate the bundle and update the manifest.\n *\n * It can be customized through the `customizeWebpackConfig` function in the\n * snap config, but in most cases, you shouldn't need to do that.\n *\n * @param config - The processed snap Webpack config.\n * @param options - The Webpack options.\n * @returns The default Webpack configuration.\n */\nexport async function getDefaultConfiguration(\n config: ProcessedConfig,\n options: WebpackOptions = {\n evaluate: config.evaluate,\n },\n): Promise<Configuration> {\n const spinnerText = options.spinner?.text;\n const builtInResolver =\n config.stats.builtIns && new SnapsBuiltInResolver(config.stats.builtIns);\n\n return {\n /**\n * The target is set to `browserslist` so that Webpack will compile the\n * bundle to support the browsers specified in the `.browserslistrc` file.\n * This Browserslist file contains the browsers that are supported by\n * MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/target/\n */\n target: `browserslist:${BROWSERSLIST_FILE}`,\n\n /**\n * The mode is set to `production` by default, so that Webpack will minify\n * and optimize the bundle.\n *\n * @see https://webpack.js.org/configuration/mode/\n */\n mode: 'production',\n\n /**\n * The entry point is set to the `input` value from the config object.\n *\n * @see https://webpack.js.org/configuration/entry-context/\n */\n entry: config.input,\n\n /**\n * The devtool option controls how source maps are generated. We set it to\n * the `sourceMap` value from the config object.\n *\n * @see https://webpack.js.org/configuration/devtool/\n */\n devtool: getDevTool(config.sourceMap),\n\n /**\n * The stats option controls how much information is printed to the console\n * when Webpack is running. We set it to `none` so that we can control the\n * output ourselves.\n *\n * @see https://webpack.js.org/configuration/stats/\n */\n stats: 'none',\n\n /**\n * The output options.\n *\n * @see https://webpack.js.org/configuration/output/\n */\n output: {\n /**\n * This indicates whether Webpack should clear the output directory\n * before building. We set it to the `clean` value from the config\n * object.\n *\n * @see https://webpack.js.org/configuration/output/#outputclean\n */\n clean: config.output.clean,\n\n /**\n * The filename of the bundle. We set it to the `filename` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputfilename\n */\n filename: config.output.filename,\n\n /**\n * The path to the output directory. We set it to the `path` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputpath\n */\n path: config.output.path,\n\n /**\n * The public path of the bundle. We set it to `/` by default, so that\n * the bundle can be loaded from the root of the server.\n *\n * @see https://webpack.js.org/configuration/output/#outputpublicpath\n */\n publicPath: '/',\n\n /**\n * The library configuration. This tells Webpack how to export the\n * bundle.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrary\n */\n library: {\n /**\n * This tells Webpack to export the bundle via assignment to module.exports.\n * We do this to mimic CommonJS, but still allow for usage of async initialization logic\n * via top level await.\n *\n * CommonJS is currently the only supported format for MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrarytarget\n */\n type: 'assign',\n name: 'module.exports',\n },\n\n /**\n * The chunk format. This tells Webpack how to export chunks. This is\n * required because we use browserslist to target browsers, but Snaps are\n * not fully compatible with browser APIs (such as `window` and\n * `document`).\n *\n * @see https://webpack.js.org/configuration/output/#outputchunkformat\n */\n chunkFormat: 'commonjs',\n },\n\n /**\n * The module configuration. This is where we tell Webpack how to handle\n * different types of files.\n *\n * @see https://webpack.js.org/configuration/module/\n */\n module: {\n rules: [\n {\n test: /\\.(js|jsx|mjs|cjs|ts|tsx)$/u,\n exclude: /node_modules/u,\n use: await getDefaultLoader(config),\n },\n\n /**\n * This allows importing modules that uses `.js` and not `.mjs` for the\n * ES build.\n *\n * @see https://webpack.js.org/configuration/module/#resolvefullyspecified\n */\n {\n test: /\\.m?js$/u,\n resolve: {\n fullySpecified: false,\n },\n },\n\n /**\n * This allows importing `.svg` files as a string.\n */\n config.features.images && {\n test: /\\.svg$/u,\n // `asset/source` returns the source as a UTF-8 string.\n type: 'asset/source',\n },\n\n /**\n * This allows importing `.png` files as a data URL.\n */\n config.features.images && {\n test: /\\.png$/u,\n type: 'asset/inline',\n generator: {\n dataUrl: getImageSVG.bind(null, 'image/png'),\n },\n },\n\n /**\n * This allows importing `.jpe?g` files as a data URL.\n */\n config.features.images && {\n test: /\\.jpe?g$/u,\n type: 'asset/inline',\n generator: {\n dataUrl: getImageSVG.bind(null, 'image/jpeg'),\n },\n },\n\n config.experimental.wasm && {\n test: /\\.wasm$/u,\n use: getFunctionLoader(wasm, {}),\n },\n ],\n },\n\n /**\n * The resolve configuration. This tells Webpack how to resolve imports.\n * We set it to resolve `.js` and `.ts` files.\n *\n * @see https://webpack.js.org/configuration/resolve/\n */\n resolve: {\n /**\n * The extensions to resolve. We set it to resolve `.(c|m)?jsx?` and\n * `.tsx?` files.\n */\n extensions: ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'],\n\n /**\n * The fallback options. This tells Webpack how to handle imports that\n * aren't resolved. By default, we set Node.js built-ins to `false`, so\n * that they are ignored.\n */\n fallback: getFallbacks(config.polyfills),\n\n /**\n * The plugins to use. We use the {@link SnapsBuiltInResolver} to show\n * warnings about using Node.js built-ins, when no fallback is specified.\n */\n plugins: [builtInResolver],\n },\n\n /**\n * The plugins to use.\n *\n * @see https://webpack.js.org/configuration/plugins/\n */\n plugins: [\n /**\n * The `ForkTsCheckerWebpackPlugin` is a Webpack plugin that checks\n * Typescript type definitions, it does this in a separate process for speed.\n */\n config.typescript.enabled &&\n new ForkTsCheckerWebpackPlugin({\n typescript: {\n build: true,\n configFile: config.typescript.configFile,\n },\n }),\n\n /**\n * The `SnapsWebpackPlugin` is a Webpack plugin that checks and updates\n * the manifest file, and evaluates the bundle in SES. While not strictly\n * required, it's highly recommended to use this plugin.\n */\n new SnapsWebpackPlugin(\n {\n manifestPath: config.manifest.path,\n writeManifest: config.manifest.update,\n eval: options.evaluate,\n },\n options.spinner,\n ),\n\n /**\n * The `SnapsStatsPlugin` is a Webpack plugin that handles the stats\n * output. It's used to show the stats in the terminal, in a format that\n * is easy to read.\n */\n new SnapsStatsPlugin({ verbose: config.stats.verbose }, options.spinner),\n\n /**\n * The `DefinePlugin` is a Webpack plugin that adds static values to the\n * bundle. We use it to add the `NODE_DEBUG`, `NODE_ENV`, and `DEBUG`\n * environment variables, as well as any custom environment\n * variables (as `process.env`).\n */\n new DefinePlugin(getEnvironmentVariables(config.environment)),\n\n /**\n * The `ProgressPlugin` is a Webpack plugin that logs the progress of\n * the build. We set it to log the progress to the spinner.\n */\n new ProgressPlugin({\n handler: getProgressHandler(options.spinner, spinnerText),\n }),\n\n /**\n * The `SnapsBundleWarningPlugin` is a Webpack plugin that shows a\n * warning when the bundle is potentially incompatible with MetaMask\n * Snaps.\n */\n new SnapsBundleWarningsPlugin({\n builtInResolver,\n builtIns: Boolean(config.stats.builtIns),\n buffer: config.stats.buffer,\n }),\n\n /**\n * The `WatchPlugin` is a Webpack plugin that adds extra files to watch\n * for changes. This is useful for rebuilding the bundle when the\n * manifest file changes.\n */\n options.watch &&\n new SnapsWatchPlugin(\n {\n files: [config.manifest.path],\n },\n options.spinner,\n ),\n\n options.analyze &&\n new BundleAnalyzerPlugin({\n analyzerPort: 0,\n logLevel: 'silent',\n openAnalyzer: false,\n }),\n\n /**\n * The `ProviderPlugin` is a Webpack plugin that automatically load\n * modules instead of having to import or require them everywhere.\n */\n (config.polyfills === true ||\n (config.polyfills !== false && config.polyfills.buffer)) &&\n new ProvidePlugin({\n Buffer: ['buffer', 'Buffer'],\n }),\n ].filter(Boolean),\n\n /**\n * The optimization configuration. This tells Webpack how to optimize the\n * bundle. Most of the time, you won't need to change this, as the default\n * options set by the `mode` option are sufficient.\n */\n optimization: {\n minimize: config.output.minimize,\n\n /**\n * We disable the nodeEnv optimization as we already add process.NODE_ENV\n * via the DefinePlugin in the section above this.\n */\n nodeEnv: false,\n\n /**\n * The minimizer to use. We set it to use the `TerserPlugin`.\n */\n minimizer: [\n new TerserPlugin({\n parallel: true,\n }),\n ],\n },\n\n /**\n * The performance configuration. This tells Webpack how to handle\n * performance hints.\n *\n * @see https://webpack.js.org/configuration/performance/\n */\n performance: {\n /**\n * The hints to show. We set it to `false`, so that we don't get\n * performance hints, as they are not relevant for Snaps.\n *\n * @see https://webpack.js.org/configuration/performance/#performancehints\n */\n hints: false,\n },\n\n /**\n * The infrastructure logging configuration. This tells Webpack how to\n * log messages.\n *\n * @see https://webpack.js.org/configuration/infrastructure-logging\n */\n infrastructureLogging: {\n /**\n * The level of logging to use. We set it to `none`, so that we can\n * control the output ourselves.\n */\n level: 'none',\n },\n };\n}\n"]}
1
+ {"version":3,"file":"config.mjs","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,kBAAkB,uCAAuC;AAChE,OAAO,2BAA0B,uCAAuC;;AAExE,OAAO,aAAY,8BAA8B;;;;AAGjD,OAAO,EAAE,oBAAoB,EAAE,gCAAgC;AAE/D,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,4BAAkB;AACpD,OAAO,EACL,6BAA6B,EAC7B,oBAAoB,EACpB,yBAAyB,EACzB,gBAAgB,EAChB,gBAAgB,EACjB,sBAAkB;AACnB,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,UAAU,EACV,uBAAuB,EACvB,YAAY,EACZ,WAAW,EACX,kBAAkB,EACnB,oBAAgB;AAwCjB;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,MAAuB,EACvB,UAA0B;IACxB,QAAQ,EAAE,MAAM,CAAC,QAAQ;CAC1B;IAED,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC;IAC1C,MAAM,eAAe,GACnB,MAAM,CAAC,KAAK,CAAC,QAAQ,IAAI,IAAI,oBAAoB,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAE3E,OAAO;QACL;;;;;;;WAOG;QACH,MAAM,EAAE,gBAAgB,iBAAiB,EAAE;QAE3C;;;;;WAKG;QACH,IAAI,EAAE,YAAY;QAElB;;;;WAIG;QACH,KAAK,EAAE,MAAM,CAA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AC;oBACf,QAAQ,EAAE,IAAI;iBACf,CAAC;aACH;SACF;QAED;;;;;WAKG;QACH,WAAW,EAAE;YACX;;;;;eAKG;YACH,KAAK,EAAE,KAAK;SACb;QAED;;;;;WAKG;QACH,qBAAqB,EAAE;YACrB;;;eAGG;YACH,KAAK,EAAE,MAAM;SACd;KACF,CAAC;AACJ,CAAC","sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-webpack-plugin';\nimport ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';\nimport type { Ora } from 'ora';\nimport TerserPlugin from 'terser-webpack-plugin';\nimport type { Configuration } from 'webpack';\nimport { DefinePlugin, ProgressPlugin, ProvidePlugin } from 'webpack';\nimport { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';\n\nimport { getFunctionLoader, wasm } from './loaders';\nimport {\n PreinstalledSnapsBundlePlugin,\n SnapsBuiltInResolver,\n SnapsBundleWarningsPlugin,\n SnapsStatsPlugin,\n SnapsWatchPlugin,\n} from './plugins';\nimport {\n BROWSERSLIST_FILE,\n getDefaultLoader,\n getDevTool,\n getEnvironmentVariables,\n getFallbacks,\n getImageSVG,\n getProgressHandler,\n} from './utils';\nimport type { ProcessedConfig } from '../config';\n\nexport type WebpackOptions = {\n /**\n * Whether to analyze the bundle.\n */\n analyze?: boolean;\n\n /**\n * Whether to evaluate the bundle. If this is set, it will override the\n * `evaluate` option in the config object.\n */\n evaluate?: boolean;\n\n /**\n * Whether to build the Snap as a preinstalled Snap. If this is set, it will\n * output a `preinstalled-snap.json` instead of a regular bundle.\n */\n preinstalled?: boolean;\n\n /**\n * The preinstalled Snap options to use. See {@link SnapConfig.preinstalled}\n * for more details.\n *\n * This is ignored if `preinstalled` is not set to `true`.\n */\n preinstalledOptions?: ProcessedConfig['preinstalled'];\n\n /**\n * The spinner to use for logging.\n */\n spinner?: Ora;\n\n /**\n * Whether to watch for changes.\n */\n watch?: boolean;\n};\n\n/**\n * Get the default Webpack configuration. This is the configuration that will\n * be used if the user doesn't provide a custom Webpack configuration. The\n * configuration is based on the snap config.\n *\n * The default configuration includes:\n *\n * - `SWC` to transpile TypeScript and JavaScript files.\n * - `TerserPlugin` to minify the bundle.\n * - `SnapsWebpackPlugin` to validate the bundle and update the manifest.\n *\n * It can be customized through the `customizeWebpackConfig` function in the\n * snap config, but in most cases, you shouldn't need to do that.\n *\n * @param config - The processed snap Webpack config.\n * @param options - The Webpack options.\n * @returns The default Webpack configuration.\n */\nexport async function getDefaultConfiguration(\n config: ProcessedConfig,\n options: WebpackOptions = {\n evaluate: config.evaluate,\n },\n): Promise<Configuration> {\n const spinnerText = options.spinner?.text;\n const builtInResolver =\n config.stats.builtIns && new SnapsBuiltInResolver(config.stats.builtIns);\n\n return {\n /**\n * The target is set to `browserslist` so that Webpack will compile the\n * bundle to support the browsers specified in the `.browserslistrc` file.\n * This Browserslist file contains the browsers that are supported by\n * MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/target/\n */\n target: `browserslist:${BROWSERSLIST_FILE}`,\n\n /**\n * The mode is set to `production` by default, so that Webpack will minify\n * and optimize the bundle.\n *\n * @see https://webpack.js.org/configuration/mode/\n */\n mode: 'production',\n\n /**\n * The entry point is set to the `input` value from the config object.\n *\n * @see https://webpack.js.org/configuration/entry-context/\n */\n entry: config.input,\n\n /**\n * The devtool option controls how source maps are generated. We set it to\n * the `sourceMap` value from the config object.\n *\n * @see https://webpack.js.org/configuration/devtool/\n */\n devtool: getDevTool(config.sourceMap),\n\n /**\n * The stats option controls how much information is printed to the console\n * when Webpack is running. We set it to `none` so that we can control the\n * output ourselves.\n *\n * @see https://webpack.js.org/configuration/stats/\n */\n stats: 'none',\n\n /**\n * The output options.\n *\n * @see https://webpack.js.org/configuration/output/\n */\n output: {\n /**\n * This indicates whether Webpack should clear the output directory\n * before building. We set it to the `clean` value from the config\n * object.\n *\n * @see https://webpack.js.org/configuration/output/#outputclean\n */\n clean: config.output.clean,\n\n /**\n * The filename of the bundle. We set it to the `filename` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputfilename\n */\n filename: config.output.filename,\n\n /**\n * The path to the output directory. We set it to the `path` value from\n * the config object.\n *\n * @see https://webpack.js.org/configuration/output/#outputpath\n */\n path: config.output.path,\n\n /**\n * The public path of the bundle. We set it to `/` by default, so that\n * the bundle can be loaded from the root of the server.\n *\n * @see https://webpack.js.org/configuration/output/#outputpublicpath\n */\n publicPath: '/',\n\n /**\n * The library configuration. This tells Webpack how to export the\n * bundle.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrary\n */\n library: {\n /**\n * This tells Webpack to export the bundle via assignment to module.exports.\n * We do this to mimic CommonJS, but still allow for usage of async initialization logic\n * via top level await.\n *\n * CommonJS is currently the only supported format for MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrarytarget\n */\n type: 'assign',\n name: 'module.exports',\n },\n\n /**\n * The chunk format. This tells Webpack how to export chunks. This is\n * required because we use browserslist to target browsers, but Snaps are\n * not fully compatible with browser APIs (such as `window` and\n * `document`).\n *\n * @see https://webpack.js.org/configuration/output/#outputchunkformat\n */\n chunkFormat: 'commonjs',\n },\n\n /**\n * The module configuration. This is where we tell Webpack how to handle\n * different types of files.\n *\n * @see https://webpack.js.org/configuration/module/\n */\n module: {\n rules: [\n {\n test: /\\.(js|jsx|mjs|cjs|ts|tsx)$/u,\n exclude: /node_modules/u,\n use: await getDefaultLoader(config),\n },\n\n /**\n * This allows importing modules that uses `.js` and not `.mjs` for the\n * ES build.\n *\n * @see https://webpack.js.org/configuration/module/#resolvefullyspecified\n */\n {\n test: /\\.m?js$/u,\n resolve: {\n fullySpecified: false,\n },\n },\n\n /**\n * This allows importing `.svg` files as a string.\n */\n config.features.images && {\n test: /\\.svg$/u,\n // `asset/source` returns the source as a UTF-8 string.\n type: 'asset/source',\n },\n\n /**\n * This allows importing `.png` files as a data URL.\n */\n config.features.images && {\n test: /\\.png$/u,\n type: 'asset/inline',\n generator: {\n dataUrl: getImageSVG.bind(null, 'image/png'),\n },\n },\n\n /**\n * This allows importing `.jpe?g` files as a data URL.\n */\n config.features.images && {\n test: /\\.jpe?g$/u,\n type: 'asset/inline',\n generator: {\n dataUrl: getImageSVG.bind(null, 'image/jpeg'),\n },\n },\n\n config.experimental.wasm && {\n test: /\\.wasm$/u,\n use: getFunctionLoader(wasm, {}),\n },\n ],\n },\n\n /**\n * The resolve configuration. This tells Webpack how to resolve imports.\n * We set it to resolve `.js` and `.ts` files.\n *\n * @see https://webpack.js.org/configuration/resolve/\n */\n resolve: {\n /**\n * The extensions to resolve. We set it to resolve `.(c|m)?jsx?` and\n * `.tsx?` files.\n */\n extensions: ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'],\n\n /**\n * The fallback options. This tells Webpack how to handle imports that\n * aren't resolved. By default, we set Node.js built-ins to `false`, so\n * that they are ignored.\n */\n fallback: getFallbacks(config.polyfills),\n\n /**\n * The plugins to use. We use the {@link SnapsBuiltInResolver} to show\n * warnings about using Node.js built-ins, when no fallback is specified.\n */\n plugins: [builtInResolver],\n },\n\n /**\n * The plugins to use.\n *\n * @see https://webpack.js.org/configuration/plugins/\n */\n plugins: [\n /**\n * The `ForkTsCheckerWebpackPlugin` is a Webpack plugin that checks\n * Typescript type definitions, it does this in a separate process for speed.\n */\n config.typescript.enabled &&\n new ForkTsCheckerWebpackPlugin({\n typescript: {\n build: true,\n configFile: config.typescript.configFile,\n },\n }),\n\n /**\n * The `SnapsWebpackPlugin` is a Webpack plugin that checks and updates\n * the manifest file, and evaluates the bundle in SES. While not strictly\n * required, it's highly recommended to use this plugin.\n */\n new SnapsWebpackPlugin(\n {\n manifestPath: config.manifest.path,\n writeManifest: config.manifest.update,\n eval: options.evaluate,\n },\n options.spinner,\n ),\n\n /**\n * The `SnapsStatsPlugin` is a Webpack plugin that handles the stats\n * output. It's used to show the stats in the terminal, in a format that\n * is easy to read.\n */\n new SnapsStatsPlugin({ verbose: config.stats.verbose }, options.spinner),\n\n /**\n * The `DefinePlugin` is a Webpack plugin that adds static values to the\n * bundle. We use it to add the `NODE_DEBUG`, `NODE_ENV`, and `DEBUG`\n * environment variables, as well as any custom environment\n * variables (as `process.env`).\n */\n new DefinePlugin(getEnvironmentVariables(config.environment)),\n\n /**\n * The `ProgressPlugin` is a Webpack plugin that logs the progress of\n * the build. We set it to log the progress to the spinner.\n */\n new ProgressPlugin({\n handler: getProgressHandler(options.spinner, spinnerText),\n }),\n\n /**\n * The `SnapsBundleWarningPlugin` is a Webpack plugin that shows a\n * warning when the bundle is potentially incompatible with MetaMask\n * Snaps.\n */\n new SnapsBundleWarningsPlugin({\n builtInResolver,\n builtIns: Boolean(config.stats.builtIns),\n buffer: config.stats.buffer,\n }),\n\n /**\n * The `WatchPlugin` is a Webpack plugin that adds extra files to watch\n * for changes. This is useful for rebuilding the bundle when the\n * manifest file changes.\n */\n options.watch &&\n new SnapsWatchPlugin(\n {\n manifestPath: config.manifest.path,\n },\n options.spinner,\n ),\n\n options.analyze &&\n new BundleAnalyzerPlugin({\n analyzerPort: 0,\n logLevel: 'silent',\n openAnalyzer: false,\n }),\n\n options.preinstalled &&\n new PreinstalledSnapsBundlePlugin(\n {\n manifestPath: config.manifest.path,\n outputName: config.output.filename,\n preinstalledOptions: options.preinstalledOptions,\n },\n options.spinner,\n ),\n\n /**\n * The `ProviderPlugin` is a Webpack plugin that automatically load\n * modules instead of having to import or require them everywhere.\n */\n (config.polyfills === true ||\n (config.polyfills !== false && config.polyfills.buffer)) &&\n new ProvidePlugin({\n Buffer: ['buffer', 'Buffer'],\n }),\n ].filter(Boolean),\n\n /**\n * The optimization configuration. This tells Webpack how to optimize the\n * bundle. Most of the time, you won't need to change this, as the default\n * options set by the `mode` option are sufficient.\n */\n optimization: {\n minimize: config.output.minimize,\n\n /**\n * We disable the nodeEnv optimization as we already add process.NODE_ENV\n * via the DefinePlugin in the section above this.\n */\n nodeEnv: false,\n\n /**\n * The minimizer to use. We set it to use the `TerserPlugin`.\n */\n minimizer: [\n new TerserPlugin({\n parallel: true,\n }),\n ],\n },\n\n /**\n * The performance configuration. This tells Webpack how to handle\n * performance hints.\n *\n * @see https://webpack.js.org/configuration/performance/\n */\n performance: {\n /**\n * The hints to show. We set it to `false`, so that we don't get\n * performance hints, as they are not relevant for Snaps.\n *\n * @see https://webpack.js.org/configuration/performance/#performancehints\n */\n hints: false,\n },\n\n /**\n * The infrastructure logging configuration. This tells Webpack how to\n * log messages.\n *\n * @see https://webpack.js.org/configuration/infrastructure-logging\n */\n infrastructureLogging: {\n /**\n * The level of logging to use. We set it to `none`, so that we can\n * control the output ourselves.\n */\n level: 'none',\n },\n };\n}\n"]}
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SnapsBundleWarningsPlugin = exports.SnapsBuiltInResolver = exports.SnapsWatchPlugin = exports.SnapsStatsPlugin = void 0;
3
+ exports.PreinstalledSnapsBundlePlugin = exports.SnapsBundleWarningsPlugin = exports.SnapsBuiltInResolver = exports.SnapsWatchPlugin = exports.SnapsStatsPlugin = void 0;
4
+ const node_1 = require("@metamask/snaps-utils/node");
4
5
  const utils_1 = require("@metamask/utils");
5
6
  const chalk_1 = require("chalk");
6
7
  const module_1 = require("module");
8
+ const path_1 = require("path");
7
9
  const webpack_1 = require("webpack");
8
10
  const utils_2 = require("./utils.cjs");
9
11
  const utils_3 = require("../utils/index.cjs");
@@ -115,7 +117,8 @@ class SnapsWatchPlugin {
115
117
  (0, utils_3.info)(`Changes detected in ${(0, chalk_1.yellow)(file)}, recompiling.`, this.#spinner);
116
118
  });
117
119
  compiler.hooks.afterEmit.tapPromise(this.constructor.name, async ({ fileDependencies }) => {
118
- this.options.files?.forEach(fileDependencies.add.bind(fileDependencies));
120
+ const { files } = await (0, node_1.loadManifest)(this.options.manifestPath);
121
+ files.forEach(fileDependencies.add.bind(fileDependencies));
119
122
  });
120
123
  }
121
124
  }
@@ -278,4 +281,89 @@ class SnapsBundleWarningsPlugin {
278
281
  }
279
282
  }
280
283
  exports.SnapsBundleWarningsPlugin = SnapsBundleWarningsPlugin;
284
+ /**
285
+ * A plugin that creates a preinstalled Snap bundle from the compiled bundle.
286
+ * This will read the manifest, and any required files (locales, icon), and
287
+ * create a `preinstalled-snap.json` file that can be used to install the Snap
288
+ * as a preinstalled Snap.
289
+ */
290
+ class PreinstalledSnapsBundlePlugin {
291
+ #options;
292
+ #spinner;
293
+ constructor(options, spinner) {
294
+ this.#options = options;
295
+ this.#spinner = spinner;
296
+ }
297
+ /**
298
+ * Apply the plugin to the Webpack compiler.
299
+ *
300
+ * @param compiler - The Webpack compiler.
301
+ */
302
+ apply(compiler) {
303
+ compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {
304
+ compilation.hooks.processAssets.tapPromise({
305
+ name: this.constructor.name,
306
+ // `PROCESS_ASSETS_STAGE_REPORT` is the last stage, so we ensure this
307
+ // plugin runs after all other plugins have finished processing
308
+ // assets.
309
+ stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT,
310
+ }, async () => {
311
+ (0, utils_3.info)('Creating preinstalled Snap bundle.', this.#spinner);
312
+ const asset = compilation.getAsset(this.#options.outputName);
313
+ if (!asset) {
314
+ compilation.errors.push(new webpack_1.WebpackError('Bundle asset not found. Make sure to build the project first.'));
315
+ return;
316
+ }
317
+ const bundleSource = asset.source.source().toString();
318
+ const preinstalledSnapBundleJson = JSON.stringify(await this.#createPreinstalledBundle(compilation, bundleSource), null, 2);
319
+ compilation.emitAsset('preinstalled-snap.json', new webpack_1.sources.RawSource(preinstalledSnapBundleJson));
320
+ });
321
+ });
322
+ }
323
+ /**
324
+ * Create a preinstalled bundle object from the given bundle source. This will
325
+ * load the manifest, read any required files (locales, icon), and return the
326
+ * preinstalled bundle object.
327
+ *
328
+ * Custom auxiliary files are not currently supported in preinstalled Snaps.
329
+ *
330
+ * @param compilation - The Webpack compilation.
331
+ * @param bundleSource - The source code of the bundle.
332
+ * @returns The preinstalled bundle object.
333
+ */
334
+ async #createPreinstalledBundle(compilation, bundleSource) {
335
+ const { mergedManifest } = await (0, node_1.loadManifest)(this.#options.manifestPath);
336
+ const manifest = mergedManifest;
337
+ const basePath = (0, path_1.dirname)(this.#options.manifestPath);
338
+ const files = [
339
+ {
340
+ path: manifest.source.location.npm.filePath,
341
+ value: bundleSource,
342
+ },
343
+ ];
344
+ if (manifest.source.locales) {
345
+ for (const locale of manifest.source.locales) {
346
+ files.push({
347
+ path: locale,
348
+ value: await (0, utils_2.readWebpackFile)(compilation.inputFileSystem, (0, path_1.resolve)(basePath, locale)),
349
+ });
350
+ }
351
+ }
352
+ if (manifest.source.location.npm.iconPath) {
353
+ const { iconPath } = manifest.source.location.npm;
354
+ files.push({
355
+ path: manifest.source.location.npm.iconPath,
356
+ // The icon is expected to be an SVG file, so we read it as UTF-8.
357
+ value: await (0, utils_2.readWebpackFile)(compilation.inputFileSystem, (0, path_1.resolve)(basePath, iconPath)),
358
+ });
359
+ }
360
+ return {
361
+ snapId: `npm:${manifest.source.location.npm.packageName}`,
362
+ manifest,
363
+ files,
364
+ ...this.#options.preinstalledOptions,
365
+ };
366
+ }
367
+ }
368
+ exports.PreinstalledSnapsBundlePlugin = PreinstalledSnapsBundlePlugin;
281
369
  //# sourceMappingURL=plugins.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.cjs","sourceRoot":"","sources":["../../src/webpack/plugins.ts"],"names":[],"mappings":";;;AAAA,2CAAgE;AAChE,iCAA+C;AAC/C,mCAAmC;AASnC,qCAAuC;AAEvC,uCAAgD;AAChD,8CAA8D;AAS9D;;;GAGG;AACH,MAAa,gBAAgB;IAC3B;;OAEG;IACM,OAAO,CAA0B;IAE1C;;OAEG;IACM,QAAQ,CAAO;IAExB,YACE,UAAmC;QACjC,OAAO,EAAE,KAAK;KACf,EACD,OAAa;QAEb,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;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5D,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBAC9B,OAAO;gBACT,CAAC;gBAED,WAAW,CAAC,QAAQ,CAAC,IAAI,CACvB,IAAI,sBAAY,CACd,mLAAmL,IAAA,YAAI,EACrL,UAAU,CACX,OAAO,IAAA,YAAI,EAAC,QAAQ,CAAC,WAAW,IAAA,YAAI,EACnC,aAAa,CACd,oEAAoE,IAAA,YAAI,EACvE,gBAAgB,CACjB,OAAO,IAAA,YAAI,EAAC,SAAS,CAAC,4BAA4B,CACpD,CACF,CAAC;YACJ,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA1ID,8DA0IC","sourcesContent":["import { assert, hasProperty, isObject } from '@metamask/utils';\nimport { bold, dim, red, yellow } from 'chalk';\nimport { isBuiltin } from 'module';\nimport type { Ora } from 'ora';\nimport type {\n Compiler,\n ProvidePlugin,\n Resolver,\n StatsError,\n WebpackPluginInstance,\n} from 'webpack';\nimport { WebpackError } from 'webpack';\n\nimport { formatText, pluralize } from './utils';\nimport { error, getErrorMessage, info, warn } from '../utils';\n\nexport type SnapsStatsPluginOptions = {\n /**\n * Whether to log the verbose stats.\n */\n verbose?: boolean;\n};\n\n/**\n * A plugin that logs the stats after compilation. This is useful for logging\n * the number of files compiled, and the time taken to compile them.\n */\nexport class SnapsStatsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsStatsPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsStatsPluginOptions = {\n verbose: false,\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.afterDone.tap(this.constructor.name, (stats) => {\n if (!stats) {\n return;\n }\n\n const { modules, time, errors, warnings } = stats.toJson();\n\n assert(modules, 'Modules must be defined in stats.');\n assert(time, 'Time must be defined in stats.');\n\n if (errors?.length) {\n const formattedErrors = errors\n .map((statsError) => this.#getStatsErrorMessage(statsError, red))\n .join('\\n\\n');\n\n error(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${errors.length} ${pluralize(\n errors.length,\n 'error',\n )}.\\n\\n${formattedErrors}\\n`,\n this.#spinner,\n );\n\n this.#spinner?.stop();\n\n process.exitCode = 1;\n return;\n }\n\n if (warnings?.length) {\n const formattedWarnings = warnings\n .map((statsWarning) =>\n this.#getStatsErrorMessage(statsWarning, yellow),\n )\n .join('\\n\\n');\n\n warn(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${warnings.length} ${pluralize(\n warnings.length,\n 'warning',\n )}.\\n\\n${formattedWarnings}\\n`,\n this.#spinner,\n );\n } else {\n info(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms.`,\n this.#spinner,\n );\n }\n\n if (compiler.watchMode) {\n // The spinner may be restarted by the watch plugin, outside of the\n // `executeSteps` flow, so we stop it here just in case.\n this.#spinner?.succeed('Done!');\n }\n });\n }\n\n /**\n * Get the error message for the given stats error.\n *\n * @param statsError - The stats error.\n * @param color - The color to use for the error message.\n * @returns The error message.\n */\n #getStatsErrorMessage(\n statsError: StatsError,\n color: typeof red | typeof yellow,\n ) {\n const baseMessage = this.options.verbose\n ? getErrorMessage(statsError)\n : statsError.message;\n\n const [first, ...rest] = baseMessage.split('\\n');\n\n return [\n color(formatText(`• ${first}`, 4, 2)),\n ...rest.map((message) => formatText(color(message), 4)),\n statsError.details && `\\n${formatText(dim(statsError.details), 6)}`,\n ]\n .filter(Boolean)\n .join('\\n');\n }\n}\n\n/**\n * The options for the {@link SnapsWatchPlugin}.\n */\nexport type SnapsWatchPluginOptions = {\n /**\n * The extra files to watch.\n */\n files?: string[];\n};\n\n/**\n * A plugin that adds extra files to watch. This is useful for watching files\n * that are not imported by the entry point, such as the `snap.manifest.json`\n * file.\n */\nexport class SnapsWatchPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsWatchPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(options: SnapsWatchPluginOptions, spinner?: Ora) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.invalid.tap(this.constructor.name, (file) => {\n this.#spinner?.start();\n info(`Changes detected in ${yellow(file)}, recompiling.`, this.#spinner);\n });\n\n compiler.hooks.afterEmit.tapPromise(\n this.constructor.name,\n async ({ fileDependencies }) => {\n this.options.files?.forEach(\n fileDependencies.add.bind(fileDependencies),\n );\n },\n );\n }\n}\n\n/**\n * The options for the {@link SnapsBuiltInResolver}.\n */\nexport type SnapsBuiltInResolverOptions = {\n /**\n * The built-in modules to ignore.\n */\n ignore?: string[];\n};\n\n/**\n * A Webpack resolve plugin.\n *\n * Copied from Webpack's own types, because the `ResolvePluginInstance` type is\n * a union, and can't be used as a type for a class.\n */\ntype ResolvePlugin = {\n apply: (resolver: Resolver) => void;\n};\n\n/**\n * A plugin that logs a message when a built-in module is not resolved. The\n * MetaMask Snaps CLI does not support built-in modules by default, and this\n * plugin is used to warn the user when they try to import a built-in module,\n * when no fallback is configured.\n */\nexport class SnapsBuiltInResolver implements ResolvePlugin {\n /**\n * The built-in modules that have been imported, but not resolved.\n */\n readonly unresolvedModules = new Set<string>();\n\n /**\n * The name of the resolver hook to tap into.\n */\n readonly #source = 'described-resolve';\n\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBuiltInResolverOptions;\n\n constructor(\n options: SnapsBuiltInResolverOptions = {\n ignore: [],\n },\n ) {\n this.options = options;\n }\n\n /**\n * Apply the plugin to the Webpack resolver.\n *\n * @param resolver - The Webpack resolver.\n */\n apply(resolver: Resolver) {\n resolver\n .getHook(this.#source)\n .tapAsync(\n this.constructor.name,\n ({ module: isModule, request }, _, callback) => {\n if (!isModule || !request) {\n return callback();\n }\n\n const baseRequest = request.split('/')[0];\n if (\n isBuiltin(baseRequest) &&\n !this.options.ignore?.includes(baseRequest)\n ) {\n const fallback = resolver.options.fallback.find(\n ({ name }) => name === baseRequest,\n );\n\n if (fallback && !fallback.alias) {\n this.unresolvedModules.add(baseRequest);\n }\n }\n\n return callback();\n },\n );\n }\n}\n\n/**\n * The options for the {@link SnapsBundleWarningsPlugin}.\n */\nexport type SnapsBundleWarningsPluginOptions = {\n /**\n * The {@link SnapsBuiltInResolver} instance to use for detecting built-in\n * modules.\n */\n builtInResolver?: SnapsBuiltInResolver | false;\n\n /**\n * Whether to show warnings if built-in modules are used, but not provided by\n * Webpack's `fallback` configuration.\n */\n builtIns?: boolean;\n\n /**\n * Whether to show warnings if the `Buffer` global is used, but not provided\n * by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n};\n\n/**\n * A plugin that logs a message when:\n *\n * - A built-in module is not resolved. The MetaMask Snaps CLI does not support\n * built-in modules by default, and this plugin is used to warn the user when\n * they try to import a built-in module, when no fallback is configured.\n * - A snap uses the `Buffer` global. The MetaMask Snaps CLI does not support\n * the `Buffer` global by default, and this plugin is used to warn the user when\n * they try to use the `Buffer` global.\n *\n * We use both a resolver and a plugin, because the resolver is used to detect\n * when a built-in module is imported, and the plugin is used to log a single\n * message when the compilation is complete. We can't do everything in a single\n * plugin, because the resolver doesn't have access to the compilation, and the\n * plugin doesn't have access to the resolver.\n */\n\nexport class SnapsBundleWarningsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBundleWarningsPluginOptions;\n\n constructor(\n options: SnapsBundleWarningsPluginOptions = {\n buffer: true,\n builtIns: true,\n },\n ) {\n this.options = options;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n if (this.options.builtIns) {\n this.#checkBuiltIns(compiler);\n }\n\n if (this.options.buffer) {\n this.#checkBuffer(compiler);\n }\n }\n\n /**\n * Check if a built-in module is used, but not provided by Webpack's\n * `fallback` configuration.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuiltIns(compiler: Compiler) {\n compiler.hooks.afterCompile.tap(this.constructor.name, (compilation) => {\n if (!this.options.builtInResolver) {\n return;\n }\n\n const { unresolvedModules } = this.options.builtInResolver;\n if (unresolvedModules.size === 0) {\n return;\n }\n\n const formattedModules = new Array(...unresolvedModules)\n .map((name) => `• ${name}`)\n .join('\\n');\n\n const webpackError = new WebpackError(\n `The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided. The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must set ${bold(\n '`polyfills`',\n )} to ${bold(\n '`true`',\n )} or an object with the builtins to polyfill as the key and ${bold(\n '`true`',\n )} as the value. To disable this warning, set ${bold(\n '`stats.builtIns`',\n )} to ${bold(\n '`false`',\n )} in your snap config file, or add the module to the ${bold(\n '`stats.builtIns.ignore`',\n )} array.`,\n );\n\n webpackError.details = formattedModules;\n compilation.warnings.push(webpackError);\n });\n }\n\n /**\n * Check if the given instance is a `ProvidePlugin`. This is not guaranteed to\n * be accurate, but it's good enough for our purposes. If we were to use\n * `instanceof` instead, it might not work if multiple versions of Webpack are\n * installed.\n *\n * @param instance - The instance to check.\n * @returns Whether the instance is a `ProvidePlugin`, i.e., whether it's an\n * object with the name `ProvidePlugin` and a `definitions` property.\n */\n #isProvidePlugin(instance: unknown): instance is ProvidePlugin {\n return (\n isObject(instance) &&\n instance.constructor.name === 'ProvidePlugin' &&\n hasProperty(instance, 'definitions')\n );\n }\n\n /**\n * Check if the `Buffer` global is used, but not provided by Webpack's\n * `DefinePlugin`.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuffer(compiler: Compiler) {\n const plugin = compiler.options.plugins?.find((instance) =>\n this.#isProvidePlugin(instance),\n ) as ProvidePlugin | undefined;\n\n // If the `ProvidePlugin` is configured to provide `Buffer`, then we don't\n // need to warn the user.\n if (plugin) {\n const { definitions } = plugin;\n if (definitions.Buffer) {\n return;\n }\n }\n\n compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {\n compilation.hooks.afterProcessAssets.tap(\n this.constructor.name,\n (assets) => {\n // Check if assets use `Buffer`.\n const bufferAssets = Object.entries(assets)\n .filter(([name]) => name.endsWith('.js'))\n .filter(([, asset]) => asset.source().includes('Buffer'));\n\n if (bufferAssets.length === 0) {\n return;\n }\n\n compilation.warnings.push(\n new WebpackError(\n `The snap attempted to use the Node.js Buffer global, which is not supported in the MetaMask Snaps CLI by default. To use the Buffer global, you must polyfill Buffer by setting ${bold(\n '`buffer`',\n )} to ${bold('`true`')} in the ${bold(\n '`polyfills`',\n )} config object in your snap config. To disable this warning, set ${bold(\n '`stats.buffer`',\n )} to ${bold('`false`')} in your snap config file.`,\n ),\n );\n },\n );\n });\n }\n}\n"]}
1
+ {"version":3,"file":"plugins.cjs","sourceRoot":"","sources":["../../src/webpack/plugins.ts"],"names":[],"mappings":";;;AACA,qDAA0D;AAC1D,2CAAgE;AAChE,iCAA+C;AAC/C,mCAAmC;AAEnC,+BAAwC;AAQxC,qCAA6D;AAG7D,uCAAiE;AACjE,8CAA8D;AAS9D;;;GAGG;AACH,MAAa,gBAAgB;IAC3B;;OAEG;IACM,OAAO,CAA0B;IAE1C;;OAEG;IACM,QAAQ,CAAO;IAExB,YACE,UAAmC;QACjC,OAAO,EAAE,KAAK;KACf,EACD,OAAa;QAEb,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,QAAkB;QACtB,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE;YAC5D,IAAI,CAAC,KAAK,EAAE,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AQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;YAC1C,MAAM,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;YAClD,KAAK,CAAC,IAAI,CAAC;gBACT,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ;gBAE3C,kEAAkE;gBAClE,KAAK,EAAE,MAAM,IAAA,uBAAe,EAC1B,WAAW,CAAC,eAAe,EAC3B,IAAA,cAAO,EAAC,QAAQ,EAAE,QAAQ,CAAC,CAC5B;aACF,CAAC,CAAC;QACL,CAAC;QAED,OAAO;YACL,MAAM,EAAE,OAAO,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,WAAW,EAAE;YACzD,QAAQ;YACR,KAAK;YACL,GAAG,IAAI,CAAC,QAAQ,CAAC,mBAAmB;SACrC,CAAC;IACJ,CAAC;CACF;AAlHD,sEAkHC","sourcesContent":["import type { SnapManifest } from '@metamask/snaps-utils';\nimport { loadManifest } from '@metamask/snaps-utils/node';\nimport { assert, hasProperty, isObject } from '@metamask/utils';\nimport { bold, dim, red, yellow } from 'chalk';\nimport { isBuiltin } from 'module';\nimport type { Ora } from 'ora';\nimport { dirname, resolve } from 'path';\nimport type {\n Compiler,\n ProvidePlugin,\n Resolver,\n StatsError,\n WebpackPluginInstance,\n} from 'webpack';\nimport { Compilation, WebpackError, sources } from 'webpack';\n\nimport type { WebpackOptions } from './config';\nimport { formatText, pluralize, readWebpackFile } from './utils';\nimport { error, getErrorMessage, info, warn } from '../utils';\n\nexport type SnapsStatsPluginOptions = {\n /**\n * Whether to log the verbose stats.\n */\n verbose?: boolean;\n};\n\n/**\n * A plugin that logs the stats after compilation. This is useful for logging\n * the number of files compiled, and the time taken to compile them.\n */\nexport class SnapsStatsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsStatsPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsStatsPluginOptions = {\n verbose: false,\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.afterDone.tap(this.constructor.name, (stats) => {\n if (!stats) {\n return;\n }\n\n const { modules, time, errors, warnings } = stats.toJson();\n\n assert(modules, 'Modules must be defined in stats.');\n assert(time, 'Time must be defined in stats.');\n\n if (errors?.length) {\n const formattedErrors = errors\n .map((statsError) => this.#getStatsErrorMessage(statsError, red))\n .join('\\n\\n');\n\n error(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${errors.length} ${pluralize(\n errors.length,\n 'error',\n )}.\\n\\n${formattedErrors}\\n`,\n this.#spinner,\n );\n\n this.#spinner?.stop();\n\n process.exitCode = 1;\n return;\n }\n\n if (warnings?.length) {\n const formattedWarnings = warnings\n .map((statsWarning) =>\n this.#getStatsErrorMessage(statsWarning, yellow),\n )\n .join('\\n\\n');\n\n warn(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${warnings.length} ${pluralize(\n warnings.length,\n 'warning',\n )}.\\n\\n${formattedWarnings}\\n`,\n this.#spinner,\n );\n } else {\n info(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms.`,\n this.#spinner,\n );\n }\n\n if (compiler.watchMode) {\n // The spinner may be restarted by the watch plugin, outside of the\n // `executeSteps` flow, so we stop it here just in case.\n this.#spinner?.succeed('Done!');\n }\n });\n }\n\n /**\n * Get the error message for the given stats error.\n *\n * @param statsError - The stats error.\n * @param color - The color to use for the error message.\n * @returns The error message.\n */\n #getStatsErrorMessage(\n statsError: StatsError,\n color: typeof red | typeof yellow,\n ) {\n const baseMessage = this.options.verbose\n ? getErrorMessage(statsError)\n : statsError.message;\n\n const [first, ...rest] = baseMessage.split('\\n');\n\n return [\n color(formatText(`• ${first}`, 4, 2)),\n ...rest.map((message) => formatText(color(message), 4)),\n statsError.details && `\\n${formatText(dim(statsError.details), 6)}`,\n ]\n .filter(Boolean)\n .join('\\n');\n }\n}\n\n/**\n * The options for the {@link SnapsWatchPlugin}.\n */\nexport type SnapsWatchPluginOptions = {\n /**\n * The path to the manifest, to determine which files to watch.\n */\n manifestPath: string;\n};\n\n/**\n * A plugin that adds extra files to watch. This is useful for watching files\n * that are not imported by the entry point, such as the `snap.manifest.json`\n * file.\n */\nexport class SnapsWatchPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsWatchPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(options: SnapsWatchPluginOptions, spinner?: Ora) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.invalid.tap(this.constructor.name, (file) => {\n this.#spinner?.start();\n info(`Changes detected in ${yellow(file)}, recompiling.`, this.#spinner);\n });\n\n compiler.hooks.afterEmit.tapPromise(\n this.constructor.name,\n async ({ fileDependencies }) => {\n const { files } = await loadManifest(this.options.manifestPath);\n\n files.forEach(fileDependencies.add.bind(fileDependencies));\n },\n );\n }\n}\n\n/**\n * The options for the {@link SnapsBuiltInResolver}.\n */\nexport type SnapsBuiltInResolverOptions = {\n /**\n * The built-in modules to ignore.\n */\n ignore?: string[];\n};\n\n/**\n * A Webpack resolve plugin.\n *\n * Copied from Webpack's own types, because the `ResolvePluginInstance` type is\n * a union, and can't be used as a type for a class.\n */\ntype ResolvePlugin = {\n apply: (resolver: Resolver) => void;\n};\n\n/**\n * A plugin that logs a message when a built-in module is not resolved. The\n * MetaMask Snaps CLI does not support built-in modules by default, and this\n * plugin is used to warn the user when they try to import a built-in module,\n * when no fallback is configured.\n */\nexport class SnapsBuiltInResolver implements ResolvePlugin {\n /**\n * The built-in modules that have been imported, but not resolved.\n */\n readonly unresolvedModules = new Set<string>();\n\n /**\n * The name of the resolver hook to tap into.\n */\n readonly #source = 'described-resolve';\n\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBuiltInResolverOptions;\n\n constructor(\n options: SnapsBuiltInResolverOptions = {\n ignore: [],\n },\n ) {\n this.options = options;\n }\n\n /**\n * Apply the plugin to the Webpack resolver.\n *\n * @param resolver - The Webpack resolver.\n */\n apply(resolver: Resolver) {\n resolver\n .getHook(this.#source)\n .tapAsync(\n this.constructor.name,\n ({ module: isModule, request }, _, callback) => {\n if (!isModule || !request) {\n return callback();\n }\n\n const baseRequest = request.split('/')[0];\n if (\n isBuiltin(baseRequest) &&\n !this.options.ignore?.includes(baseRequest)\n ) {\n const fallback = resolver.options.fallback.find(\n ({ name }) => name === baseRequest,\n );\n\n if (fallback && !fallback.alias) {\n this.unresolvedModules.add(baseRequest);\n }\n }\n\n return callback();\n },\n );\n }\n}\n\n/**\n * The options for the {@link SnapsBundleWarningsPlugin}.\n */\nexport type SnapsBundleWarningsPluginOptions = {\n /**\n * The {@link SnapsBuiltInResolver} instance to use for detecting built-in\n * modules.\n */\n builtInResolver?: SnapsBuiltInResolver | false;\n\n /**\n * Whether to show warnings if built-in modules are used, but not provided by\n * Webpack's `fallback` configuration.\n */\n builtIns?: boolean;\n\n /**\n * Whether to show warnings if the `Buffer` global is used, but not provided\n * by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n};\n\n/**\n * A plugin that logs a message when:\n *\n * - A built-in module is not resolved. The MetaMask Snaps CLI does not support\n * built-in modules by default, and this plugin is used to warn the user when\n * they try to import a built-in module, when no fallback is configured.\n * - A snap uses the `Buffer` global. The MetaMask Snaps CLI does not support\n * the `Buffer` global by default, and this plugin is used to warn the user when\n * they try to use the `Buffer` global.\n *\n * We use both a resolver and a plugin, because the resolver is used to detect\n * when a built-in module is imported, and the plugin is used to log a single\n * message when the compilation is complete. We can't do everything in a single\n * plugin, because the resolver doesn't have access to the compilation, and the\n * plugin doesn't have access to the resolver.\n */\n\nexport class SnapsBundleWarningsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBundleWarningsPluginOptions;\n\n constructor(\n options: SnapsBundleWarningsPluginOptions = {\n buffer: true,\n builtIns: true,\n },\n ) {\n this.options = options;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n if (this.options.builtIns) {\n this.#checkBuiltIns(compiler);\n }\n\n if (this.options.buffer) {\n this.#checkBuffer(compiler);\n }\n }\n\n /**\n * Check if a built-in module is used, but not provided by Webpack's\n * `fallback` configuration.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuiltIns(compiler: Compiler) {\n compiler.hooks.afterCompile.tap(this.constructor.name, (compilation) => {\n if (!this.options.builtInResolver) {\n return;\n }\n\n const { unresolvedModules } = this.options.builtInResolver;\n if (unresolvedModules.size === 0) {\n return;\n }\n\n const formattedModules = new Array(...unresolvedModules)\n .map((name) => `• ${name}`)\n .join('\\n');\n\n const webpackError = new WebpackError(\n `The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided. The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must set ${bold(\n '`polyfills`',\n )} to ${bold(\n '`true`',\n )} or an object with the builtins to polyfill as the key and ${bold(\n '`true`',\n )} as the value. To disable this warning, set ${bold(\n '`stats.builtIns`',\n )} to ${bold(\n '`false`',\n )} in your snap config file, or add the module to the ${bold(\n '`stats.builtIns.ignore`',\n )} array.`,\n );\n\n webpackError.details = formattedModules;\n compilation.warnings.push(webpackError);\n });\n }\n\n /**\n * Check if the given instance is a `ProvidePlugin`. This is not guaranteed to\n * be accurate, but it's good enough for our purposes. If we were to use\n * `instanceof` instead, it might not work if multiple versions of Webpack are\n * installed.\n *\n * @param instance - The instance to check.\n * @returns Whether the instance is a `ProvidePlugin`, i.e., whether it's an\n * object with the name `ProvidePlugin` and a `definitions` property.\n */\n #isProvidePlugin(instance: unknown): instance is ProvidePlugin {\n return (\n isObject(instance) &&\n instance.constructor.name === 'ProvidePlugin' &&\n hasProperty(instance, 'definitions')\n );\n }\n\n /**\n * Check if the `Buffer` global is used, but not provided by Webpack's\n * `DefinePlugin`.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuffer(compiler: Compiler) {\n const plugin = compiler.options.plugins?.find((instance) =>\n this.#isProvidePlugin(instance),\n ) as ProvidePlugin | undefined;\n\n // If the `ProvidePlugin` is configured to provide `Buffer`, then we don't\n // need to warn the user.\n if (plugin) {\n const { definitions } = plugin;\n if (definitions.Buffer) {\n return;\n }\n }\n\n compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {\n compilation.hooks.afterProcessAssets.tap(\n this.constructor.name,\n (assets) => {\n // Check if assets use `Buffer`.\n const bufferAssets = Object.entries(assets)\n .filter(([name]) => name.endsWith('.js'))\n .filter(([, asset]) => asset.source().includes('Buffer'));\n\n if (bufferAssets.length === 0) {\n return;\n }\n\n compilation.warnings.push(\n new WebpackError(\n `The snap attempted to use the Node.js Buffer global, which is not supported in the MetaMask Snaps CLI by default. To use the Buffer global, you must polyfill Buffer by setting ${bold(\n '`buffer`',\n )} to ${bold('`true`')} in the ${bold(\n '`polyfills`',\n )} config object in your snap config. To disable this warning, set ${bold(\n '`stats.buffer`',\n )} to ${bold('`false`')} in your snap config file.`,\n ),\n );\n },\n );\n });\n }\n}\n\n/**\n * The options for the {@link PreinstalledSnapsBundlePlugin}.\n */\nexport type PreinstalledSnapsBundlePluginOptions = {\n /**\n * The path to the manifest file.\n */\n manifestPath: string;\n\n /**\n * The name of the output file.\n */\n outputName: string;\n\n /**\n * The preinstalled options from the Webpack configuration.\n */\n preinstalledOptions: WebpackOptions['preinstalledOptions'];\n};\n\n/**\n * A plugin that creates a preinstalled Snap bundle from the compiled bundle.\n * This will read the manifest, and any required files (locales, icon), and\n * create a `preinstalled-snap.json` file that can be used to install the Snap\n * as a preinstalled Snap.\n */\nexport class PreinstalledSnapsBundlePlugin implements WebpackPluginInstance {\n readonly #options: PreinstalledSnapsBundlePluginOptions;\n\n readonly #spinner?: Ora;\n\n constructor(options: PreinstalledSnapsBundlePluginOptions, spinner?: Ora) {\n this.#options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {\n compilation.hooks.processAssets.tapPromise(\n {\n name: this.constructor.name,\n // `PROCESS_ASSETS_STAGE_REPORT` is the last stage, so we ensure this\n // plugin runs after all other plugins have finished processing\n // assets.\n stage: Compilation.PROCESS_ASSETS_STAGE_REPORT,\n },\n async () => {\n info('Creating preinstalled Snap bundle.', this.#spinner);\n\n const asset = compilation.getAsset(this.#options.outputName);\n if (!asset) {\n compilation.errors.push(\n new WebpackError(\n 'Bundle asset not found. Make sure to build the project first.',\n ),\n );\n\n return;\n }\n\n const bundleSource = asset.source.source().toString();\n const preinstalledSnapBundleJson = JSON.stringify(\n await this.#createPreinstalledBundle(compilation, bundleSource),\n null,\n 2,\n );\n\n compilation.emitAsset(\n 'preinstalled-snap.json',\n new sources.RawSource(preinstalledSnapBundleJson),\n );\n },\n );\n });\n }\n\n /**\n * Create a preinstalled bundle object from the given bundle source. This will\n * load the manifest, read any required files (locales, icon), and return the\n * preinstalled bundle object.\n *\n * Custom auxiliary files are not currently supported in preinstalled Snaps.\n *\n * @param compilation - The Webpack compilation.\n * @param bundleSource - The source code of the bundle.\n * @returns The preinstalled bundle object.\n */\n async #createPreinstalledBundle(\n compilation: Compilation,\n bundleSource: string,\n ) {\n const { mergedManifest } = await loadManifest(this.#options.manifestPath);\n const manifest = mergedManifest as SnapManifest;\n\n const basePath = dirname(this.#options.manifestPath);\n\n const files = [\n {\n path: manifest.source.location.npm.filePath,\n value: bundleSource,\n },\n ];\n\n if (manifest.source.locales) {\n for (const locale of manifest.source.locales) {\n files.push({\n path: locale,\n value: await readWebpackFile(\n compilation.inputFileSystem,\n resolve(basePath, locale),\n ),\n });\n }\n }\n\n if (manifest.source.location.npm.iconPath) {\n const { iconPath } = manifest.source.location.npm;\n files.push({\n path: manifest.source.location.npm.iconPath,\n\n // The icon is expected to be an SVG file, so we read it as UTF-8.\n value: await readWebpackFile(\n compilation.inputFileSystem,\n resolve(basePath, iconPath),\n ),\n });\n }\n\n return {\n snapId: `npm:${manifest.source.location.npm.packageName}`,\n manifest,\n files,\n ...this.#options.preinstalledOptions,\n };\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { Ora } from "ora/index.js";
2
2
  import type { Compiler, Resolver, WebpackPluginInstance } from "webpack";
3
+ import type { WebpackOptions } from "./config.cjs";
3
4
  export type SnapsStatsPluginOptions = {
4
5
  /**
5
6
  * Whether to log the verbose stats.
@@ -29,9 +30,9 @@ export declare class SnapsStatsPlugin implements WebpackPluginInstance {
29
30
  */
30
31
  export type SnapsWatchPluginOptions = {
31
32
  /**
32
- * The extra files to watch.
33
+ * The path to the manifest, to determine which files to watch.
33
34
  */
34
- files?: string[];
35
+ manifestPath: string;
35
36
  };
36
37
  /**
37
38
  * A plugin that adds extra files to watch. This is useful for watching files
@@ -144,5 +145,38 @@ export declare class SnapsBundleWarningsPlugin implements WebpackPluginInstance
144
145
  */
145
146
  apply(compiler: Compiler): void;
146
147
  }
148
+ /**
149
+ * The options for the {@link PreinstalledSnapsBundlePlugin}.
150
+ */
151
+ export type PreinstalledSnapsBundlePluginOptions = {
152
+ /**
153
+ * The path to the manifest file.
154
+ */
155
+ manifestPath: string;
156
+ /**
157
+ * The name of the output file.
158
+ */
159
+ outputName: string;
160
+ /**
161
+ * The preinstalled options from the Webpack configuration.
162
+ */
163
+ preinstalledOptions: WebpackOptions['preinstalledOptions'];
164
+ };
165
+ /**
166
+ * A plugin that creates a preinstalled Snap bundle from the compiled bundle.
167
+ * This will read the manifest, and any required files (locales, icon), and
168
+ * create a `preinstalled-snap.json` file that can be used to install the Snap
169
+ * as a preinstalled Snap.
170
+ */
171
+ export declare class PreinstalledSnapsBundlePlugin implements WebpackPluginInstance {
172
+ #private;
173
+ constructor(options: PreinstalledSnapsBundlePluginOptions, spinner?: Ora);
174
+ /**
175
+ * Apply the plugin to the Webpack compiler.
176
+ *
177
+ * @param compiler - The Webpack compiler.
178
+ */
179
+ apply(compiler: Compiler): void;
180
+ }
147
181
  export {};
148
182
  //# sourceMappingURL=plugins.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.d.cts","sourceRoot":"","sources":["../../src/webpack/plugins.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;AAC/B,OAAO,KAAK,EACV,QAAQ,EAER,QAAQ,EAER,qBAAqB,EACtB,gBAAgB;AAMjB,MAAM,MAAM,uBAAuB,GAAG;IACpC;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF;;;GAGG;AACH,qBAAa,gBAAiB,YAAW,qBAAqB;;IAC5D;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,uBAAuB,CAAC;gBAQxC,OAAO,GAAE,uBAER,EACD,OAAO,CAAC,EAAE,GAAG;IAMf;;;;OAIG;IACH,KAAK,CAAC,QAAQ,EAAE,QAAQ;CA6FzB;AAED;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB,CAAC;AAEF;;;;GAIG;AACH,qBAAa,gBAAiB,YAAW,qBAAqB;;IAC5D;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,uBAAuB,CAAC;gBAO9B,OAAO,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,GAAG;IAK3D;;;;OAIG;IACH,KAAK,CAAC,QAAQ,EAAE,QAAQ;CAezB;AAED;;GAEG;AACH,MAAM,MAAM,2BAA2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