@metamask/snaps-cli 8.1.1 → 8.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -1
- package/README.md +1 -1
- package/dist/commands/watch/__test__/invalid/snap.config.cjs +11 -0
- package/dist/commands/watch/__test__/invalid/snap.config.cjs.map +1 -0
- package/dist/commands/watch/__test__/invalid/snap.config.d.cts +4 -0
- package/dist/commands/watch/__test__/invalid/snap.config.d.cts.map +1 -0
- package/dist/commands/watch/__test__/invalid/snap.config.d.mts +4 -0
- package/dist/commands/watch/__test__/invalid/snap.config.d.mts.map +1 -0
- package/dist/commands/watch/__test__/invalid/snap.config.mjs +9 -0
- package/dist/commands/watch/__test__/invalid/snap.config.mjs.map +1 -0
- package/dist/webpack/config.cjs +1 -4
- package/dist/webpack/config.cjs.map +1 -1
- package/dist/webpack/config.d.cts.map +1 -1
- package/dist/webpack/config.d.mts.map +1 -1
- package/dist/webpack/config.mjs +1 -4
- package/dist/webpack/config.mjs.map +1 -1
- package/dist/webpack/plugins.cjs +0 -21
- package/dist/webpack/plugins.cjs.map +1 -1
- package/dist/webpack/plugins.d.cts +0 -10
- package/dist/webpack/plugins.d.cts.map +1 -1
- package/dist/webpack/plugins.d.mts +0 -10
- package/dist/webpack/plugins.d.mts.map +1 -1
- package/dist/webpack/plugins.mjs +0 -21
- package/dist/webpack/plugins.mjs.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [8.3.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Merge manifest validation reports to include latest validation errors and warnings ([#3567](https://github.com/MetaMask/snaps/pull/3567))
|
|
15
|
+
|
|
16
|
+
## [8.2.0]
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Add support for eval in watch mode ([#3553](https://github.com/MetaMask/snaps/pull/3553))
|
|
21
|
+
- This enables some extra validation checks in watch mode, which can help
|
|
22
|
+
catch issues earlier in the development process.
|
|
23
|
+
|
|
10
24
|
## [8.1.1]
|
|
11
25
|
|
|
12
26
|
### Fixed
|
|
@@ -393,7 +407,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
393
407
|
- The version of the package no longer needs to match the version of all other
|
|
394
408
|
MetaMask Snaps packages.
|
|
395
409
|
|
|
396
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@8.
|
|
410
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@8.3.0...HEAD
|
|
411
|
+
[8.3.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@8.2.0...@metamask/snaps-cli@8.3.0
|
|
412
|
+
[8.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@8.1.1...@metamask/snaps-cli@8.2.0
|
|
397
413
|
[8.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@8.1.0...@metamask/snaps-cli@8.1.1
|
|
398
414
|
[8.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@8.0.0...@metamask/snaps-cli@8.1.0
|
|
399
415
|
[8.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@7.2.0...@metamask/snaps-cli@8.0.0
|
package/README.md
CHANGED
|
@@ -116,7 +116,7 @@ snap-project/
|
|
|
116
116
|
|
|
117
117
|
Source files other than `index.js` are located through its imports. The
|
|
118
118
|
defaults can be overwritten using the `snap.config.js` or (`snap.config.ts`)
|
|
119
|
-
[config file](#configuration
|
|
119
|
+
[config file](#configuration).
|
|
120
120
|
|
|
121
121
|
## Configuration
|
|
122
122
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snap.config.cjs","sourceRoot":"","sources":["../../../../../src/commands/watch/__test__/invalid/snap.config.ts"],"names":[],"mappings":";;AAEA,MAAM,MAAM,GAAe;IACzB,KAAK,EAAE,WAAW;IAClB,MAAM,EAAE;QACN,IAAI,EAAE,QAAQ;QACd,QAAQ,EAAE,WAAW;KACtB;CACF,CAAC;AAEF,kBAAe,MAAM,CAAC","sourcesContent":["import type { SnapConfig } from '@metamask/snaps-cli';\n\nconst config: SnapConfig = {\n input: 'input.mjs',\n output: {\n path: './dist',\n filename: 'bundle.js',\n },\n};\n\nexport default config;\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snap.config.d.cts","sourceRoot":"","sources":["../../../../../src/commands/watch/__test__/invalid/snap.config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,4BAA4B;AAEtD,QAAA,MAAM,MAAM,EAAE,UAMb,CAAC;AAEF,eAAe,MAAM,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snap.config.d.mts","sourceRoot":"","sources":["../../../../../src/commands/watch/__test__/invalid/snap.config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,4BAA4B;AAEtD,QAAA,MAAM,MAAM,EAAE,UAMb,CAAC;AAEF,eAAe,MAAM,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snap.config.mjs","sourceRoot":"","sources":["../../../../../src/commands/watch/__test__/invalid/snap.config.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,GAAe;IACzB,KAAK,EAAE,WAAW;IAClB,MAAM,EAAE;QACN,IAAI,EAAE,QAAQ;QACd,QAAQ,EAAE,WAAW;KACtB;CACF,CAAC;AAEF,eAAe,MAAM,CAAC","sourcesContent":["import type { SnapConfig } from '@metamask/snaps-cli';\n\nconst config: SnapConfig = {\n input: 'input.mjs',\n output: {\n path: './dist',\n filename: 'bundle.js',\n },\n};\n\nexport default config;\n"]}
|
package/dist/webpack/config.cjs
CHANGED
|
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.getDefaultConfiguration = void 0;
|
|
7
7
|
const snaps_webpack_plugin_1 = __importDefault(require("@metamask/snaps-webpack-plugin"));
|
|
8
8
|
const fork_ts_checker_webpack_plugin_1 = __importDefault(require("fork-ts-checker-webpack-plugin"));
|
|
9
|
-
const path_1 = require("path");
|
|
10
9
|
const terser_webpack_plugin_1 = __importDefault(require("terser-webpack-plugin"));
|
|
11
10
|
const webpack_1 = require("webpack");
|
|
12
11
|
const webpack_bundle_analyzer_1 = require("webpack-bundle-analyzer");
|
|
@@ -246,7 +245,7 @@ async function getDefaultConfiguration(config, options = {
|
|
|
246
245
|
new snaps_webpack_plugin_1.default({
|
|
247
246
|
manifestPath: config.manifest.path,
|
|
248
247
|
writeManifest: config.manifest.update,
|
|
249
|
-
eval:
|
|
248
|
+
eval: options.evaluate,
|
|
250
249
|
}, options.spinner),
|
|
251
250
|
/**
|
|
252
251
|
* The `SnapsStatsPlugin` is a Webpack plugin that handles the stats
|
|
@@ -285,8 +284,6 @@ async function getDefaultConfiguration(config, options = {
|
|
|
285
284
|
*/
|
|
286
285
|
options.watch &&
|
|
287
286
|
new plugins_1.SnapsWatchPlugin({
|
|
288
|
-
bundle: (0, path_1.resolve)(config.output.path, config.output.filename),
|
|
289
|
-
evaluate: options.evaluate,
|
|
290
287
|
files: [config.manifest.path],
|
|
291
288
|
}, options.spinner),
|
|
292
289
|
options.analyze &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":";;;;;;AAAA,0FAAgE;AAChE,oGAAwE;AAExE,+BAA+B;AAC/B,kFAAiD;AAEjD,qCAAsE;AACtE,qEAA+D;AAE/D,iDAAoD;AACpD,2CAKmB;AACnB,uCAQiB;AA0BjB;;;;;;;;;;;;;;;;;GAiBG;AACI,K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;;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;AAhXD,0DAgXC","sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-webpack-plugin';\nimport ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';\nimport type { Ora } from 'ora';\nimport { resolve } from 'path';\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.watch && 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 bundle: resolve(config.output.path, config.output.filename),\n evaluate: options.evaluate,\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,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,KAA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H,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.cts","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.mts","sourceRoot":"","sources":["../../src/webpack/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;
|
|
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"}
|
package/dist/webpack/config.mjs
CHANGED
|
@@ -7,7 +7,6 @@ function $importDefault(module) {
|
|
|
7
7
|
import SnapsWebpackPlugin from "@metamask/snaps-webpack-plugin";
|
|
8
8
|
import $ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
|
|
9
9
|
const ForkTsCheckerWebpackPlugin = $importDefault($ForkTsCheckerWebpackPlugin);
|
|
10
|
-
import { resolve } from "path";
|
|
11
10
|
import $TerserPlugin from "terser-webpack-plugin";
|
|
12
11
|
const TerserPlugin = $importDefault($TerserPlugin);
|
|
13
12
|
import $webpack from "webpack";
|
|
@@ -249,7 +248,7 @@ export async function getDefaultConfiguration(config, options = {
|
|
|
249
248
|
new SnapsWebpackPlugin({
|
|
250
249
|
manifestPath: config.manifest.path,
|
|
251
250
|
writeManifest: config.manifest.update,
|
|
252
|
-
eval:
|
|
251
|
+
eval: options.evaluate,
|
|
253
252
|
}, options.spinner),
|
|
254
253
|
/**
|
|
255
254
|
* The `SnapsStatsPlugin` is a Webpack plugin that handles the stats
|
|
@@ -288,8 +287,6 @@ export async function getDefaultConfiguration(config, options = {
|
|
|
288
287
|
*/
|
|
289
288
|
options.watch &&
|
|
290
289
|
new SnapsWatchPlugin({
|
|
291
|
-
bundle: resolve(config.output.path, config.output.filename),
|
|
292
|
-
evaluate: options.evaluate,
|
|
293
290
|
files: [config.manifest.path],
|
|
294
291
|
}, options.spinner),
|
|
295
292
|
options.analyze &&
|
|
@@ -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,EAAE,OAAO,EAAE,aAAa;AAC/B,OAAO,aAAY,8BA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AAC,QAAQ,CAAC;oBAC3D,QAAQ,EAAE,OAAO,CAAC,QAAQ;oBAC1B,KAAK,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;iBAC9B,EACD,OAAO,CAAC,OAAO,CAChB;YAEH,OAAO,CAAC,OAAO;gBACb,IAAI,oBAAoB,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,aAAa,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,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 { resolve } from 'path';\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.watch && 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 bundle: resolve(config.output.path, config.output.filename),\n evaluate: options.evaluate,\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,oBAAoB,EACpB,yBAAyB,EACzB,gBAAgB,EAChB,gBAAgB,EACjB,sBAAkB;AACnB,OAAO,EACL,iBAAiB,EACjB,gBAAgB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AI,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;gBACxD,IAAI,aAAa,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,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"]}
|
package/dist/webpack/plugins.cjs
CHANGED
|
@@ -6,7 +6,6 @@ const chalk_1 = require("chalk");
|
|
|
6
6
|
const module_1 = require("module");
|
|
7
7
|
const webpack_1 = require("webpack");
|
|
8
8
|
const utils_2 = require("./utils.cjs");
|
|
9
|
-
const eval_1 = require("../commands/eval/index.cjs");
|
|
10
9
|
const utils_3 = require("../utils/index.cjs");
|
|
11
10
|
/**
|
|
12
11
|
* A plugin that logs the stats after compilation. This is useful for logging
|
|
@@ -117,28 +116,8 @@ class SnapsWatchPlugin {
|
|
|
117
116
|
});
|
|
118
117
|
compiler.hooks.afterEmit.tapPromise(this.constructor.name, async ({ fileDependencies }) => {
|
|
119
118
|
this.options.files?.forEach(fileDependencies.add.bind(fileDependencies));
|
|
120
|
-
if (this.options.bundle && this.options.evaluate) {
|
|
121
|
-
await this.#safeEvaluate(this.options.bundle);
|
|
122
|
-
}
|
|
123
119
|
});
|
|
124
120
|
}
|
|
125
|
-
/**
|
|
126
|
-
* Safely evaluate the bundle at the given path. If an error occurs, it will
|
|
127
|
-
* be logged to the console, rather than throwing an error.
|
|
128
|
-
*
|
|
129
|
-
* This function should never throw an error.
|
|
130
|
-
*
|
|
131
|
-
* @param bundlePath - The path to the bundle.
|
|
132
|
-
*/
|
|
133
|
-
async #safeEvaluate(bundlePath) {
|
|
134
|
-
try {
|
|
135
|
-
await (0, eval_1.evaluate)(bundlePath);
|
|
136
|
-
(0, utils_3.info)(`Snap bundle evaluated successfully.`, this.#spinner);
|
|
137
|
-
}
|
|
138
|
-
catch (evaluateError) {
|
|
139
|
-
(0, utils_3.error)(evaluateError.message, this.#spinner);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
121
|
}
|
|
143
122
|
exports.SnapsWatchPlugin = SnapsWatchPlugin;
|
|
144
123
|
/**
|
|
@@ -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,qDAA4C;AAC5C,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,CAAC;gBACX,OAAO;YACT,CAAC;YAED,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;YAE3D,IAAA,cAAM,EAAC,OAAO,EAAE,mCAAmC,CAAC,CAAC;YACrD,IAAA,cAAM,EAAC,IAAI,EAAE,gCAAgC,CAAC,CAAC;YAE/C,IAAI,MAAM,EAAE,MAAM,EAAE,CAAC;gBACnB,MAAM,eAAe,GAAG,MAAM;qBAC3B,G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C,CAAC;gBAE5D,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 { evaluate } from '../commands/eval';\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 bundle path. This is the file that will be evaluated, if the `evaluate`\n * option is set.\n */\n bundle?: string;\n\n /**\n * Whether to evaluate the bundle. This only applies if the `bundle` option is\n * set.\n */\n evaluate?: boolean;\n\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 if (this.options.bundle && this.options.evaluate) {\n await this.#safeEvaluate(this.options.bundle);\n }\n },\n );\n }\n\n /**\n * Safely evaluate the bundle at the given path. If an error occurs, it will\n * be logged to the console, rather than throwing an error.\n *\n * This function should never throw an error.\n *\n * @param bundlePath - The path to the bundle.\n */\n async #safeEvaluate(bundlePath: string) {\n try {\n await evaluate(bundlePath);\n info(`Snap bundle evaluated successfully.`, this.#spinner);\n } catch (evaluateError) {\n error(evaluateError.message, this.#spinner);\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":";;;AAAA,2CAAgE;AAChE,iCAA+C;AAC/C,mCAAmC;AASnC,qCAAuC;AAEvC,uCAAgD;AAChD,8CAA8D;A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AC,MAAM,CAAC;qBACxC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;qBACxC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAE5D,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"]}
|
|
@@ -28,16 +28,6 @@ export declare class SnapsStatsPlugin implements WebpackPluginInstance {
|
|
|
28
28
|
* The options for the {@link SnapsWatchPlugin}.
|
|
29
29
|
*/
|
|
30
30
|
export type SnapsWatchPluginOptions = {
|
|
31
|
-
/**
|
|
32
|
-
* The bundle path. This is the file that will be evaluated, if the `evaluate`
|
|
33
|
-
* option is set.
|
|
34
|
-
*/
|
|
35
|
-
bundle?: string;
|
|
36
|
-
/**
|
|
37
|
-
* Whether to evaluate the bundle. This only applies if the `bundle` option is
|
|
38
|
-
* set.
|
|
39
|
-
*/
|
|
40
|
-
evaluate?: boolean;
|
|
41
31
|
/**
|
|
42
32
|
* The extra files to watch.
|
|
43
33
|
*/
|
|
@@ -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;
|
|
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,2BAA2B,GAAG;IACxC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;GAKG;AACH,KAAK,aAAa,GAAG;IACnB,KAAK,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;CACrC,CAAC;AAEF;;;;;GAKG;AACH,qBAAa,oBAAqB,YAAW,aAAa;;IACxD;;OAEG;IACH,QAAQ,CAAC,iBAAiB,cAAqB;IAO/C;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,2BAA2B,CAAC;gBAG5C,OAAO,GAAE,2BAER;IAKH;;;;OAIG;IACH,KAAK,CAAC,QAAQ,EAAE,QAAQ;CA4BzB;AAED;;GAEG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C;;;OAGG;IACH,eAAe,CAAC,EAAE,oBAAoB,GAAG,KAAK,CAAC;IAE/C;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AAEH,qBAAa,yBAA0B,YAAW,qBAAqB;;IACrE;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,gCAAgC,CAAC;gBAGjD,OAAO,GAAE,gCAGR;IAKH;;;;OAIG;IACH,KAAK,CAAC,QAAQ,EAAE,QAAQ;CAsHzB"}
|
|
@@ -28,16 +28,6 @@ export declare class SnapsStatsPlugin implements WebpackPluginInstance {
|
|
|
28
28
|
* The options for the {@link SnapsWatchPlugin}.
|
|
29
29
|
*/
|
|
30
30
|
export type SnapsWatchPluginOptions = {
|
|
31
|
-
/**
|
|
32
|
-
* The bundle path. This is the file that will be evaluated, if the `evaluate`
|
|
33
|
-
* option is set.
|
|
34
|
-
*/
|
|
35
|
-
bundle?: string;
|
|
36
|
-
/**
|
|
37
|
-
* Whether to evaluate the bundle. This only applies if the `bundle` option is
|
|
38
|
-
* set.
|
|
39
|
-
*/
|
|
40
|
-
evaluate?: boolean;
|
|
41
31
|
/**
|
|
42
32
|
* The extra files to watch.
|
|
43
33
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.d.mts","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;
|
|
1
|
+
{"version":3,"file":"plugins.d.mts","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,2BAA2B,GAAG;IACxC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;GAKG;AACH,KAAK,aAAa,GAAG;IACnB,KAAK,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;CACrC,CAAC;AAEF;;;;;GAKG;AACH,qBAAa,oBAAqB,YAAW,aAAa;;IACxD;;OAEG;IACH,QAAQ,CAAC,iBAAiB,cAAqB;IAO/C;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,2BAA2B,CAAC;gBAG5C,OAAO,GAAE,2BAER;IAKH;;;;OAIG;IACH,KAAK,CAAC,QAAQ,EAAE,QAAQ;CA4BzB;AAED;;GAEG;AACH,MAAM,MAAM,gCAAgC,GAAG;IAC7C;;;OAGG;IACH,eAAe,CAAC,EAAE,oBAAoB,GAAG,KAAK,CAAC;IAE/C;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AAEH,qBAAa,yBAA0B,YAAW,qBAAqB;;IACrE;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,gCAAgC,CAAC;gBAGjD,OAAO,GAAE,gCAGR;IAKH;;;;OAIG;IACH,KAAK,CAAC,QAAQ,EAAE,QAAQ;CAsHzB"}
|
package/dist/webpack/plugins.mjs
CHANGED
|
@@ -5,7 +5,6 @@ import { isBuiltin } from "module";
|
|
|
5
5
|
import $webpack from "webpack";
|
|
6
6
|
const { WebpackError } = $webpack;
|
|
7
7
|
import { formatText, pluralize } from "./utils.mjs";
|
|
8
|
-
import { evaluate } from "../commands/eval/index.mjs";
|
|
9
8
|
import { error, getErrorMessage, info, warn } from "../utils/index.mjs";
|
|
10
9
|
/**
|
|
11
10
|
* A plugin that logs the stats after compilation. This is useful for logging
|
|
@@ -115,28 +114,8 @@ export class SnapsWatchPlugin {
|
|
|
115
114
|
});
|
|
116
115
|
compiler.hooks.afterEmit.tapPromise(this.constructor.name, async ({ fileDependencies }) => {
|
|
117
116
|
this.options.files?.forEach(fileDependencies.add.bind(fileDependencies));
|
|
118
|
-
if (this.options.bundle && this.options.evaluate) {
|
|
119
|
-
await this.#safeEvaluate(this.options.bundle);
|
|
120
|
-
}
|
|
121
117
|
});
|
|
122
118
|
}
|
|
123
|
-
/**
|
|
124
|
-
* Safely evaluate the bundle at the given path. If an error occurs, it will
|
|
125
|
-
* be logged to the console, rather than throwing an error.
|
|
126
|
-
*
|
|
127
|
-
* This function should never throw an error.
|
|
128
|
-
*
|
|
129
|
-
* @param bundlePath - The path to the bundle.
|
|
130
|
-
*/
|
|
131
|
-
async #safeEvaluate(bundlePath) {
|
|
132
|
-
try {
|
|
133
|
-
await evaluate(bundlePath);
|
|
134
|
-
info(`Snap bundle evaluated successfully.`, this.#spinner);
|
|
135
|
-
}
|
|
136
|
-
catch (evaluateError) {
|
|
137
|
-
error(evaluateError.message, this.#spinner);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
119
|
}
|
|
141
120
|
/**
|
|
142
121
|
* A plugin that logs a message when a built-in module is not resolved. The
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.mjs","sourceRoot":"","sources":["../../src/webpack/plugins.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;;;AAEhE,OAAO,EAAE,SAAS,EAAE,eAAe;;;AAWnC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,oBAAgB;AAChD,OAAO,EAAE,QAAQ,EAAE,mCAAyB;AAC5C,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,IAAI,EAAE,2BAAiB;AAS9D;;;GAGG;AACH,MAAM,OAAO,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,CA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EACrB,CAAC,MAAM,EAAE,EAAE;gBACT,gCAAgC;gBAChC,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;qBACxC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;qBACxC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAE5D,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBAC9B,OAAO;gBACT,CAAC;gBAED,WAAW,CAAC,QAAQ,CAAC,IAAI,CACvB,IAAI,YAAY,CACd,mLAAmL,IAAI,CACrL,UAAU,CACX,OAAO,IAAI,CAAC,QAAQ,CAAC,WAAW,IAAI,CACnC,aAAa,CACd,oEAAoE,IAAI,CACvE,gBAAgB,CACjB,OAAO,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACpD,CACF,CAAC;YACJ,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF","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 { evaluate } from '../commands/eval';\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 bundle path. This is the file that will be evaluated, if the `evaluate`\n * option is set.\n */\n bundle?: string;\n\n /**\n * Whether to evaluate the bundle. This only applies if the `bundle` option is\n * set.\n */\n evaluate?: boolean;\n\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 if (this.options.bundle && this.options.evaluate) {\n await this.#safeEvaluate(this.options.bundle);\n }\n },\n );\n }\n\n /**\n * Safely evaluate the bundle at the given path. If an error occurs, it will\n * be logged to the console, rather than throwing an error.\n *\n * This function should never throw an error.\n *\n * @param bundlePath - The path to the bundle.\n */\n async #safeEvaluate(bundlePath: string) {\n try {\n await evaluate(bundlePath);\n info(`Snap bundle evaluated successfully.`, this.#spinner);\n } catch (evaluateError) {\n error(evaluateError.message, this.#spinner);\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.mjs","sourceRoot":"","sources":["../../src/webpack/plugins.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;;;AAEhE,OAAO,EAAE,SAAS,EAAE,eAAe;;;AAWnC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,oBAAgB;AAChD,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,IAAI,EAAE,2BAAiB;AAS9D;;;GAGG;AACH,MAAM,OAAO,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,CAAC;gBACX,OAAO;YACT,CAAC;YAED,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;YAE3D,MAAM,CAAC,OAAO,EAAE,mCAAmC,CAAC,CAAC;YACrD,MAAM,CAAC,IAAI,EAAE,gCAAgC,CAAC,CAAC;YAE/C,IAAI,MAAM,EAAE,MAAM,EAAE,CAAC;gBACnB,MAAM,eAAe,GAAG,MAAM;qBAC3B,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,C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,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE;YACpE,WAAW,CAAC,KAAK,CAAC,kBAAkB,CAAC,GAAG,CACtC,IAAI,CAAC,WAAW,CAAC,IAAI,EACrB,CAAC,MAAM,EAAE,EAAE;gBACT,gCAAgC;gBAChC,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;qBACxC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;qBACxC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAE5D,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBAC9B,OAAO;gBACT,CAAC;gBAED,WAAW,CAAC,QAAQ,CAAC,IAAI,CACvB,IAAI,YAAY,CACd,mLAAmL,IAAI,CACrL,UAAU,CACX,OAAO,IAAI,CAAC,QAAQ,CAAC,WAAW,IAAI,CACnC,aAAa,CACd,oEAAoE,IAAI,CACvE,gBAAgB,CACjB,OAAO,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACpD,CACF,CAAC;YACJ,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF","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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-cli",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.3.0",
|
|
4
4
|
"description": "A CLI for developing MetaMask Snaps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -64,11 +64,11 @@
|
|
|
64
64
|
"test:watch": "jest --watch"
|
|
65
65
|
},
|
|
66
66
|
"dependencies": {
|
|
67
|
-
"@metamask/snaps-rpc-methods": "^13.
|
|
67
|
+
"@metamask/snaps-rpc-methods": "^13.5.0",
|
|
68
68
|
"@metamask/snaps-sandbox": "^1.0.0",
|
|
69
|
-
"@metamask/snaps-sdk": "^9.
|
|
70
|
-
"@metamask/snaps-utils": "^11.
|
|
71
|
-
"@metamask/snaps-webpack-plugin": "^5.
|
|
69
|
+
"@metamask/snaps-sdk": "^9.3.0",
|
|
70
|
+
"@metamask/snaps-utils": "^11.5.0",
|
|
71
|
+
"@metamask/snaps-webpack-plugin": "^5.1.0",
|
|
72
72
|
"@metamask/superstruct": "^3.2.1",
|
|
73
73
|
"@metamask/utils": "^11.4.2",
|
|
74
74
|
"@swc/core": "1.11.31",
|