@metamask/snaps-cli 5.0.0 → 5.1.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 CHANGED
@@ -6,6 +6,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [5.1.0]
10
+ ### Changed
11
+ - Optimize CLI Webpack configuration ([#2175](https://github.com/MetaMask/snaps/pull/2175))
12
+ - This can reduce the size of Snaps in certain cases.
13
+ - Show Webpack compilation warnings in CLI ([#2186](https://github.com/MetaMask/snaps/pull/2186), [#2192](https://github.com/MetaMask/snaps/pull/2192))
14
+ - Add a warning when no icon is found and when icon is not square ([#2185](https://github.com/MetaMask/snaps/pull/2185))
15
+
9
16
  ## [5.0.0]
10
17
  ### Changed
11
18
  - **BREAKING:** Disable source maps by default ([#2166](https://github.com/MetaMask/snaps/pull/2166))
@@ -102,7 +109,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
102
109
  - The version of the package no longer needs to match the version of all other
103
110
  MetaMask Snaps packages.
104
111
 
105
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@5.0.0...HEAD
112
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@5.1.0...HEAD
113
+ [5.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@5.0.0...@metamask/snaps-cli@5.1.0
106
114
  [5.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@4.0.1...@metamask/snaps-cli@5.0.0
107
115
  [4.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@4.0.0...@metamask/snaps-cli@4.0.1
108
116
  [4.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-cli@3.0.5...@metamask/snaps-cli@4.0.0
@@ -118,11 +118,7 @@ const SnapsWebpackConfigStruct = (0, _superstruct.object)({
118
118
  root: (0, _superstruct.defaulted)((0, _snapsutils.file)(), process.cwd()),
119
119
  port: (0, _superstruct.defaulted)((0, _superstruct.number)(), 8081)
120
120
  }), {}),
121
- environment: (0, _superstruct.defaulted)((0, _superstruct.record)((0, _superstruct.string)(), (0, _superstruct.unknown)()), {
122
- NODE_DEBUG: false,
123
- NODE_ENV: 'production',
124
- DEBUG: false
125
- }),
121
+ environment: (0, _superstruct.defaulted)((0, _superstruct.record)((0, _superstruct.string)(), (0, _superstruct.unknown)()), {}),
126
122
  stats: (0, _superstruct.defaulted)((0, _superstruct.object)({
127
123
  verbose: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
128
124
  builtIns: (0, _superstruct.defaulted)((0, _snapssdk.union)([
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config.ts"],"sourcesContent":["import { literal, union } from '@metamask/snaps-sdk';\nimport {\n createFromStruct,\n file,\n indent,\n isFile,\n SnapsStructError,\n named,\n} from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\nimport { transform } from '@swc/core';\nimport type { BrowserifyObject } from 'browserify';\nimport { dim } from 'chalk';\nimport { readFile } from 'fs/promises';\nimport Module from 'module';\nimport { basename, dirname, resolve } from 'path';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n defaulted,\n define,\n func,\n number,\n object,\n optional,\n record,\n string,\n type,\n unknown,\n empty,\n} from 'superstruct';\nimport type { Configuration as WebpackConfiguration } from 'webpack';\n\nimport { TranspilationModes } from './builders';\nimport { ConfigError } from './errors';\nimport type { YargsArgs } from './types/yargs';\nimport { CONFIG_FILE, TS_CONFIG_FILE } from './utils';\n\nconst CONFIG_FILES = [CONFIG_FILE, TS_CONFIG_FILE];\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n *\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\nexport type SnapBrowserifyConfig = {\n /**\n * The bundler to use to build the snap. For backwards compatibility, if not\n * specified, Browserify will be used. However, the Browserify bundler is\n * deprecated and will be removed in a future release, so it's recommended to\n * use the Webpack bundler instead.\n */\n bundler?: 'browserify';\n\n /**\n * The options for the Snaps CLI. These are merged with the options passed to\n * the CLI, with the CLI options taking precedence.\n *\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\n cliOptions?: {\n /**\n * The path to the snap bundle file.\n *\n * @default 'dist/bundle.js'\n */\n bundle?: string;\n\n /**\n * The directory to output the snap to. This is only used if `bundle` is\n * not specified.\n *\n * @default 'dist'\n */\n dist?: string;\n\n /**\n * Whether to attempt to evaluate the snap in SES. This can catch some errors\n * that would otherwise only be caught at runtime.\n *\n * @default true\n */\n eval?: boolean;\n\n /**\n * Whether to validate the snap manifest.\n *\n * @default true\n */\n manifest?: boolean;\n\n /**\n * The name of the bundle file. This is only used if `bundle` is not\n * specified.\n *\n * @default 'bundle.js'\n */\n outfileName?: string;\n\n /**\n * The port to run the server on.\n *\n * @default 8081\n */\n port?: number;\n\n /**\n * The root directory to serve the snap from.\n *\n * @default `process.cwd()`\n */\n root?: string;\n\n /**\n * Whether to generate source maps for the snap bundle.\n *\n * @default false\n */\n sourceMaps?: boolean;\n\n /**\n * The path to the snap entry point.\n *\n * @default 'src/index.js'\n */\n src?: string;\n\n /**\n * Whether to remove comments from the bundle.\n *\n * @default true\n */\n stripComments?: boolean;\n\n /**\n * Whether to suppress warnings.\n *\n * @default false\n */\n suppressWarnings?: boolean;\n\n /**\n * The transpilation mode to use, which determines which files are\n * transpiled.\n *\n * - `'localAndDeps'`: Transpile the snap entry point and all dependencies.\n * - `'localOnly'`: Transpile only the snap entry point.\n * - `'none'`: Don't transpile any files.\n *\n * @default 'localOnly'\n */\n transpilationMode?: 'localAndDeps' | 'localOnly' | 'none';\n\n /**\n * The dependencies to transpile when `transpilationMode` is set to\n * `'localAndDeps'`. If not specified, all dependencies will be transpiled.\n */\n depsToTranspile?: string[];\n\n /**\n * Whether to show original errors.\n *\n * @default true\n */\n verboseErrors?: boolean;\n\n /**\n * Whether to write the updated manifest to disk.\n *\n * @default true\n */\n writeManifest?: boolean;\n\n /**\n * Whether to serve the snap locally.\n *\n * @default true\n */\n serve?: boolean;\n };\n\n /**\n * A function that can be used to customize the Browserify instance used to\n * build the snap.\n *\n * @param bundler - The Browserify instance.\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\n bundlerCustomizer?: (bundler: BrowserifyObject) => void;\n};\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n */\nexport type SnapWebpackConfig = {\n /**\n * The bundler to use to build the snap. For backwards compatibility, if not\n * specified, Browserify will be used. However, the Browserify bundler is\n * deprecated and will be removed in a future release, so it's recommended to\n * use the Webpack bundler instead.\n */\n bundler: 'webpack';\n\n /**\n * The path to the snap entry point. This should be a JavaScript or TypeScript\n * file.\n */\n input: string;\n\n /**\n * Whether to generate source maps for the snap. If `true`, source maps will\n * be generated as separate files. If `'inline'`, source maps will be\n * inlined in the generated JavaScript bundle.\n *\n * @default true\n */\n sourceMap?: boolean | 'inline';\n\n /**\n * Whether to attempt to evaluate the snap in SES. This can catch some errors\n * that would otherwise only be caught at runtime.\n *\n * @default true\n */\n evaluate?: boolean;\n\n output?: {\n /**\n * The path to the directory where the snap will be built. This directory\n * will be created if it doesn't exist.\n *\n * If the path is relative, it will be resolved relative to the current\n * working directory.\n *\n * @default 'dist'\n */\n path?: string;\n\n /**\n * The name of the JavaScript bundle file.\n *\n * @default 'bundle.js'\n */\n filename?: string;\n\n /**\n * Whether to clean the output directory before building the snap. If\n * `true`, the output directory will be deleted and recreated. Otherwise,\n * the output directory will be left as-is.\n *\n * @default false\n */\n clean?: boolean;\n\n /**\n * Whether to minimize the snap bundle. If `true`, the bundle will be\n * minified. Otherwise, the bundle will be left as-is.\n *\n * @default true\n */\n minimize?: boolean;\n };\n\n manifest?: {\n /**\n * The path to the snap manifest file. If the path is relative, it will be\n * resolved relative to the current working directory.\n *\n * @default 'snap.manifest.json'\n */\n path?: string;\n\n /**\n * Whether to automatically update the manifest. If `true`, the manifest\n * will be updated with the latest shasum of the snap bundle, and some\n * common fields will be updated if they are missing or incorrect. If\n * `false`, the manifest will be left as-is.\n *\n * @default true\n */\n update?: boolean;\n };\n\n server?: {\n /**\n * Whether to enable the local server. If `true`, the snap will be served\n * from a local server, when running the `watch` command. If `false`, the\n * snap will not be served.\n *\n * @default true\n */\n enabled?: boolean;\n\n /**\n * The root directory to serve the snap from. If the path is relative, it\n * will be resolved relative to the current working directory.\n *\n * @default `process.cwd()`\n */\n root?: string;\n\n /**\n * The port to run the server on.\n *\n * @default 8081\n */\n port?: number;\n };\n\n /**\n * The environment variables to set when building the snap. These will be\n * available in the snap as `process.env`. In addition to these environment\n * variables, the following environment variables will always be set:\n *\n * - `NODE_DEBUG`: `false`\n * - `NODE_ENV`: `'production'`\n * - `DEBUG`: `false`\n *\n * Any environment variables specified here will override these defaults. You\n * can also override any variables here by setting them in your shell when\n * running the CLI.\n */\n environment?: Record<string, unknown>;\n\n /**\n * Options that control the logging output of the CLI.\n */\n stats?: {\n /**\n * Whether to enable verbose logging.\n *\n * @default false\n */\n verbose?: boolean;\n\n /**\n * Whether to log warnings about unresolved built-in modules. If `false`,\n * warnings will not be logged.\n */\n builtIns?:\n | {\n /**\n * The built-in modules to ignore when resolving modules. If a module\n * is ignored, no warning will be logged if it is not resolved.\n */\n ignore?: string[];\n }\n | false;\n\n /**\n * Whether to log warnings about the use of the `Buffer` global. If `false`,\n * warnings will not be logged. If `true`, the CLI will warn if the `Buffer`\n * global is used, but not provided by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n };\n\n /**\n * Whether to provide polyfills for node builtins. If `true`, all the available\n * polyfills will be provided. If `false` no polyfills will be provided. If a\n * configuration object is passed only the polyfills set to `true` will be provided.\n *\n * @default false\n * @example\n * ```ts\n * polyfills: true\n *\n * // or\n *\n * polyfills: {\n * assert: true,\n * buffer: true\n * }\n * ```\n */\n polyfills?:\n | boolean\n | {\n assert?: boolean;\n buffer?: boolean;\n console?: boolean;\n constants?: boolean;\n crypto?: boolean;\n domain?: boolean;\n events?: boolean;\n http?: boolean;\n https?: boolean;\n os?: boolean;\n path?: boolean;\n punycode?: boolean;\n process?: boolean;\n querystring?: boolean;\n stream?: boolean;\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex?: boolean;\n _stream_passthrough?: boolean;\n _stream_readable?: boolean;\n _stream_transform?: boolean;\n _stream_writable?: boolean;\n string_decoder?: boolean;\n /* eslint-enable @typescript-eslint/naming-convention */\n sys?: boolean;\n timers?: boolean;\n tty?: boolean;\n url?: boolean;\n util?: boolean;\n vm?: boolean;\n zlib?: boolean;\n };\n\n /**\n * A function to customize the Webpack configuration used to build the snap.\n * This function will be called with the default Webpack configuration, and\n * should return the modified configuration. If not specified, the default\n * configuration will be used.\n *\n * It's recommended to use the `webpack-merge` package to merge the default\n * configuration with your customizations. The merge function is exported as\n * `merge` from the `@metamask/snaps-cli` package.\n *\n * @example\n * ```ts\n * import type { SnapsConfig } from '@metamask/snaps-cli';\n * import { merge } from '@metamask/snaps-cli';\n *\n * const config: SnapsConfig = {\n * bundler: 'webpack',\n * entry: 'src/index.ts',\n * customizeWebpackConfig: (config) => merge(config, {\n * module: {\n * rules: [\n * {\n * test: /\\.wasm$/,\n * type: 'assets/resource',\n * },\n * ],\n * },\n * }),\n * };\n *\n * export default config;\n * ```\n */\n customizeWebpackConfig?: (\n config: WebpackConfiguration,\n ) => WebpackConfiguration;\n\n /**\n * Experimental features that can be enabled. These features are not\n * guaranteed to be stable, and may be removed or changed in a future release.\n */\n experimental?: {\n /**\n * Whether to enable WebAssembly support. If `true`, the Webpack\n * configuration will be modified to support WebAssembly. If `false`, the\n * Webpack configuration will not be modified.\n *\n * @default false\n */\n wasm?: boolean;\n };\n};\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n */\nexport type SnapConfig = SnapBrowserifyConfig | SnapWebpackConfig;\n\ntype SnapsBrowserifyBundlerCustomizerFunction = (\n bundler: BrowserifyObject,\n) => void;\n\n// This struct is essentially the same as the `func` struct, but it's defined\n// separately so that we include the function type in the inferred TypeScript\n// type definitions.\nconst SnapsBrowserifyBundlerCustomizerFunctionStruct =\n define<SnapsBrowserifyBundlerCustomizerFunction>(\n 'function',\n func().validator,\n );\n\nexport const SnapsBrowserifyConfigStruct = object({\n bundler: defaulted(literal('browserify'), 'browserify'),\n cliOptions: defaulted(\n object({\n bundle: optional(file()),\n dist: defaulted(file(), 'dist'),\n eval: defaulted(boolean(), true),\n manifest: defaulted(boolean(), true),\n port: defaulted(number(), 8081),\n outfileName: defaulted(string(), 'bundle.js'),\n root: defaulted(file(), process.cwd()),\n sourceMaps: defaulted(boolean(), false),\n src: defaulted(file(), 'src/index.js'),\n stripComments: defaulted(boolean(), true),\n suppressWarnings: defaulted(boolean(), false),\n transpilationMode: defaulted(\n union([literal('localAndDeps'), literal('localOnly'), literal('none')]),\n 'localOnly',\n ),\n depsToTranspile: defaulted(array(string()), []),\n verboseErrors: defaulted(boolean(), true),\n writeManifest: defaulted(boolean(), true),\n serve: defaulted(boolean(), true),\n }),\n {},\n ),\n bundlerCustomizer: optional(SnapsBrowserifyBundlerCustomizerFunctionStruct),\n});\n\ntype SnapsWebpackCustomizeWebpackConfigFunction = (\n config: WebpackConfiguration,\n) => WebpackConfiguration;\n\n// This struct is essentially the same as the `func` struct, but it's defined\n// separately so that we include the function type in the inferred TypeScript\n// type definitions.\nconst SnapsWebpackCustomizeWebpackConfigFunctionStruct =\n define<SnapsWebpackCustomizeWebpackConfigFunction>(\n 'function',\n func().validator,\n );\n\nexport const SnapsWebpackConfigStruct = object({\n bundler: literal('webpack'),\n input: defaulted(file(), resolve(process.cwd(), 'src/index.js')),\n sourceMap: defaulted(union([boolean(), literal('inline')]), false),\n evaluate: defaulted(boolean(), true),\n\n output: defaulted(\n object({\n path: defaulted(file(), resolve(process.cwd(), 'dist')),\n filename: defaulted(string(), 'bundle.js'),\n clean: defaulted(boolean(), false),\n minimize: defaulted(boolean(), true),\n }),\n {},\n ),\n\n manifest: defaulted(\n object({\n path: defaulted(file(), resolve(process.cwd(), 'snap.manifest.json')),\n update: defaulted(boolean(), true),\n }),\n {},\n ),\n\n server: defaulted(\n object({\n enabled: defaulted(boolean(), true),\n root: defaulted(file(), process.cwd()),\n port: defaulted(number(), 8081),\n }),\n {},\n ),\n\n environment: defaulted(record(string(), unknown()), {\n NODE_DEBUG: false,\n NODE_ENV: 'production',\n DEBUG: false,\n }),\n\n stats: defaulted(\n object({\n verbose: defaulted(boolean(), false),\n builtIns: defaulted(\n union([\n object({ ignore: defaulted(array(string()), []) }),\n literal(false),\n ]),\n {},\n ),\n buffer: defaulted(boolean(), true),\n }),\n {},\n ),\n\n polyfills: defaulted(\n union([\n boolean(),\n object({\n assert: defaulted(boolean(), false),\n buffer: defaulted(boolean(), false),\n console: defaulted(boolean(), false),\n constants: defaulted(boolean(), false),\n crypto: defaulted(boolean(), false),\n domain: defaulted(boolean(), false),\n events: defaulted(boolean(), false),\n http: defaulted(boolean(), false),\n https: defaulted(boolean(), false),\n os: defaulted(boolean(), false),\n path: defaulted(boolean(), false),\n punycode: defaulted(boolean(), false),\n process: defaulted(boolean(), false),\n querystring: defaulted(boolean(), false),\n stream: defaulted(boolean(), false),\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex: defaulted(boolean(), false),\n _stream_passthrough: defaulted(boolean(), false),\n _stream_readable: defaulted(boolean(), false),\n _stream_transform: defaulted(boolean(), false),\n _stream_writable: defaulted(boolean(), false),\n string_decoder: defaulted(boolean(), false),\n /* eslint-enable @typescript-eslint/naming-convention */\n sys: defaulted(boolean(), false),\n timers: defaulted(boolean(), false),\n tty: defaulted(boolean(), false),\n url: defaulted(boolean(), false),\n util: defaulted(boolean(), false),\n vm: defaulted(boolean(), false),\n zlib: defaulted(boolean(), false),\n }),\n ]),\n false,\n ),\n\n customizeWebpackConfig: optional(\n SnapsWebpackCustomizeWebpackConfigFunctionStruct,\n ),\n\n experimental: defaulted(\n object({\n wasm: defaulted(boolean(), false),\n }),\n {},\n ),\n});\n\nexport const SnapsConfigStruct = type({\n bundler: defaulted(\n union([literal('browserify'), literal('webpack')]),\n 'browserify',\n ),\n});\n\nexport const LegacyOptionsStruct = union([\n named(\n 'object with `transpilationMode` set to `localAndDeps` and `depsToTranspile` set to an array of strings',\n type({\n depsToTranspile: array(string()),\n transpilationMode: literal(TranspilationModes.LocalAndDeps),\n writeManifest: boolean(),\n bundlerCustomizer: optional(\n SnapsBrowserifyBundlerCustomizerFunctionStruct,\n ),\n }),\n ),\n named(\n 'object without `depsToTranspile`',\n type({\n depsToTranspile: named('empty array', empty(array())),\n transpilationMode: union([\n literal(TranspilationModes.LocalOnly),\n literal(TranspilationModes.None),\n ]),\n writeManifest: boolean(),\n bundlerCustomizer: optional(\n SnapsBrowserifyBundlerCustomizerFunctionStruct,\n ),\n }),\n ),\n]);\n\nexport type LegacyOptions = Infer<typeof LegacyOptionsStruct>;\n\nexport type ProcessedBrowserifyConfig = Infer<\n typeof SnapsBrowserifyConfigStruct\n>;\n\nexport type ProcessedWebpackConfig = Infer<typeof SnapsWebpackConfigStruct> & {\n /**\n * The legacy Browserify config, if the bundler is Browserify. This is used\n * to support the legacy config format.\n */\n legacy?: LegacyOptions;\n};\n\nexport type ProcessedConfig = ProcessedWebpackConfig;\n\n/**\n * Get a validated snap config. This validates the config and adds default\n * values for any missing properties.\n *\n * @param config - The config to validate.\n * @param argv - The CLI arguments.\n * @returns The validated config.\n */\nexport function getConfig(config: unknown, argv: YargsArgs): ProcessedConfig {\n const prefix = 'The snap config file is invalid';\n const suffix = dim(\n // TODO: Link to `docs.metamask.io` once the docs are published.\n 'Refer to the documentation for more information: https://github.com/MetaMask/snaps/tree/main/packages/snaps-cli/',\n );\n\n const { bundler } = createFromStruct(\n config,\n SnapsConfigStruct,\n prefix,\n suffix,\n );\n\n if (bundler === 'browserify') {\n const legacyConfig = createFromStruct(\n config,\n SnapsBrowserifyConfigStruct,\n prefix,\n suffix,\n );\n\n return getWebpackConfig(mergeLegacyOptions(argv, legacyConfig));\n }\n\n return createFromStruct(config, SnapsWebpackConfigStruct, prefix, suffix);\n}\n\n/**\n * Load a snap config from a file. This supports both JavaScript and TypeScript\n * config files, in the CommonJS module format and the ES module format.\n *\n * This assumes that the config file exports a default object, either through\n * `module.exports` or `export default`.\n *\n * @param path - The full path to the config file.\n * @param argv - The CLI arguments.\n * @returns The validated config.\n * @throws If the config file is invalid, or if the config file does not have a\n * default export.\n */\nexport async function loadConfig(path: string, argv: YargsArgs) {\n try {\n const contents = await readFile(path, 'utf8');\n const source = await transform(contents, {\n swcrc: false,\n jsc: {\n parser: {\n syntax: 'typescript',\n },\n },\n module: {\n type: 'commonjs',\n },\n });\n\n const config = new Module(path);\n\n // @ts-expect-error - This function is not typed.\n config.paths = Module._nodeModulePaths(dirname(path));\n\n // @ts-expect-error - This function is not typed.\n config._compile(source.code, path);\n\n if (!hasProperty(config.exports, 'default')) {\n return getConfig(config.exports, argv);\n }\n\n return getConfig(config.exports.default, argv);\n } catch (error) {\n if (error instanceof SnapsStructError) {\n throw new ConfigError(error.message);\n }\n\n throw new ConfigError(\n `Unable to load snap config file at \"${path}\".\\n\\n${indent(\n error.message,\n )}`,\n );\n }\n}\n\n/**\n * Resolve a snap config. This function will look for a `snap.config.js` or\n * `snap.config.ts` file in the current or specified directory.\n *\n * @param path - The path to resolve the snap config from. Defaults to the\n * current working directory.\n * @param argv - The CLI arguments.\n * @returns The resolved and validated snap config.\n * @throws If a snap config could not be found.\n */\nexport async function resolveConfig(path: string, argv: YargsArgs) {\n for (const configFile of CONFIG_FILES) {\n const filePath = resolve(path, configFile);\n if (await isFile(filePath)) {\n return await loadConfig(filePath, argv);\n }\n }\n\n throw new ConfigError(\n `Could not find a \"snap.config.js\" or \"snap.config.ts\" file in the current or specified directory (\"${path}\").`,\n );\n}\n\n/**\n * Get a snap config from the CLI arguments. This will either load the config\n * from the specified config file, or resolve the config from the current\n * working directory.\n *\n * @param argv - The CLI arguments.\n * @param cwd - The current working directory. Defaults to `process.cwd()`.\n * @returns The resolved and validated snap config.\n */\nexport async function getConfigByArgv(\n argv: YargsArgs,\n cwd: string = process.cwd(),\n) {\n if (argv.config) {\n if (!(await isFile(argv.config))) {\n throw new ConfigError(\n `Could not find a config file at \"${argv.config}\". Make sure that the path is correct.`,\n );\n }\n\n return await loadConfig(argv.config, argv);\n }\n\n return await resolveConfig(cwd, argv);\n}\n\n/**\n * Merge legacy CLI options into the config. This is used to support the legacy\n * config format, where options can be specified both in the config file and\n * through CLI flags.\n *\n * @param argv - The CLI arguments.\n * @param config - The config to merge the CLI options into.\n * @returns The config with the CLI options merged in.\n * @deprecated This function is only used to support the legacy config format.\n */\nexport function mergeLegacyOptions(\n argv: YargsArgs,\n config: ProcessedBrowserifyConfig,\n) {\n const cliOptions = Object.keys(config.cliOptions).reduce<\n ProcessedBrowserifyConfig['cliOptions']\n >((accumulator, key) => {\n if (argv[key] !== undefined) {\n return {\n ...accumulator,\n [key]: argv[key],\n };\n }\n\n return accumulator;\n }, config.cliOptions);\n\n return {\n ...config,\n cliOptions,\n };\n}\n\n/**\n * Get a Webpack config from a legacy browserify config. This is used to\n * support the legacy config format, and convert it to the new format.\n *\n * @param legacyConfig - The legacy browserify config.\n * @returns The Webpack config.\n */\nexport function getWebpackConfig(\n legacyConfig: ProcessedBrowserifyConfig,\n): ProcessedWebpackConfig {\n const defaultConfig = create(\n { bundler: 'webpack' },\n SnapsWebpackConfigStruct,\n );\n\n // The legacy config has two options for specifying the output path and\n // filename: `bundle`, and `dist` + `outfileName`. If `bundle` is specified,\n // we use that as the output path and filename. Otherwise, we use `dist` and\n // `outfileName`.\n const path = legacyConfig.cliOptions.bundle\n ? dirname(legacyConfig.cliOptions.bundle)\n : legacyConfig.cliOptions.dist;\n\n const filename = legacyConfig.cliOptions.bundle\n ? basename(legacyConfig.cliOptions.bundle)\n : legacyConfig.cliOptions.outfileName;\n\n return {\n ...defaultConfig,\n input: legacyConfig.cliOptions.src,\n evaluate: legacyConfig.cliOptions.eval,\n sourceMap: legacyConfig.cliOptions.sourceMaps,\n output: {\n path,\n filename,\n\n // The legacy config has an option to remove comments from the bundle, but\n // the terser plugin does this by default, so we only enable the terser if\n // the legacy config has `stripComments` set to `true`. This is not a\n // perfect solution, but it's the best we can do without breaking the\n // legacy config.\n minimize: legacyConfig.cliOptions.stripComments,\n\n // The legacy config does not have a `clean` option, so we default to\n // `false` here.\n clean: false,\n },\n manifest: {\n // The legacy config does not have a `manifest` option, so we default to\n // `process.cwd()/snap.manifest.json`.\n path: resolve(process.cwd(), 'snap.manifest.json'),\n update: legacyConfig.cliOptions.writeManifest,\n },\n server: {\n enabled: legacyConfig.cliOptions.serve,\n port: legacyConfig.cliOptions.port,\n root: legacyConfig.cliOptions.root,\n },\n stats: {\n verbose: false,\n\n // These plugins are designed to be used with the modern config format, so\n // we disable them for the legacy config format.\n builtIns: false,\n buffer: false,\n },\n legacy: createFromStruct(\n {\n ...legacyConfig.cliOptions,\n bundlerCustomizer: legacyConfig.bundlerCustomizer,\n },\n LegacyOptionsStruct,\n 'Invalid Browserify CLI options',\n ),\n };\n}\n"],"names":["SnapsBrowserifyConfigStruct","SnapsWebpackConfigStruct","SnapsConfigStruct","LegacyOptionsStruct","getConfig","loadConfig","resolveConfig","getConfigByArgv","mergeLegacyOptions","getWebpackConfig","CONFIG_FILES","CONFIG_FILE","TS_CONFIG_FILE","SnapsBrowserifyBundlerCustomizerFunctionStruct","define","func","validator","object","bundler","defaulted","literal","cliOptions","bundle","optional","file","dist","eval","boolean","manifest","port","number","outfileName","string","root","process","cwd","sourceMaps","src","stripComments","suppressWarnings","transpilationMode","union","depsToTranspile","array","verboseErrors","writeManifest","serve","bundlerCustomizer","SnapsWebpackCustomizeWebpackConfigFunctionStruct","input","resolve","sourceMap","evaluate","output","path","filename","clean","minimize","update","server","enabled","environment","record","unknown","NODE_DEBUG","NODE_ENV","DEBUG","stats","verbose","builtIns","ignore","buffer","polyfills","assert","console","constants","crypto","domain","events","http","https","os","punycode","querystring","stream","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_writable","string_decoder","sys","timers","tty","url","util","vm","zlib","customizeWebpackConfig","experimental","wasm","type","named","TranspilationModes","LocalAndDeps","empty","LocalOnly","None","config","argv","prefix","suffix","dim","createFromStruct","legacyConfig","contents","readFile","source","transform","swcrc","jsc","parser","syntax","module","Module","paths","_nodeModulePaths","dirname","_compile","code","hasProperty","exports","default","error","SnapsStructError","ConfigError","message","indent","configFile","filePath","isFile","Object","keys","reduce","accumulator","key","undefined","defaultConfig","create","basename","legacy"],"mappings":";;;;;;;;;;;IAyeaA,2BAA2B;eAA3BA;;IA0CAC,wBAAwB;eAAxBA;;IAyGAC,iBAAiB;eAAjBA;;IAOAC,mBAAmB;eAAnBA;;IAoDGC,SAAS;eAATA;;IAyCMC,UAAU;eAAVA;;IAmDAC,aAAa;eAAbA;;IAsBAC,eAAe;eAAfA;;IA2BNC,kBAAkB;eAAlBA;;IA8BAC,gBAAgB;eAAhBA;;;0BAl2Be;4BAQxB;uBACqB;sBACF;uBAEN;0BACK;+DACN;sBACwB;6BAiBpC;0BAG4B;wBACP;wBAEgB;;;;;;AAE5C,MAAMC,eAAe;IAACC,mBAAW;IAAEC,sBAAc;CAAC;AAwblD,6EAA6E;AAC7E,6EAA6E;AAC7E,oBAAoB;AACpB,MAAMC,iDACJC,IAAAA,mBAAM,EACJ,YACAC,IAAAA,iBAAI,IAAGC,SAAS;AAGb,MAAMhB,8BAA8BiB,IAAAA,mBAAM,EAAC;IAChDC,SAASC,IAAAA,sBAAS,EAACC,IAAAA,iBAAO,EAAC,eAAe;IAC1CC,YAAYF,IAAAA,sBAAS,EACnBF,IAAAA,mBAAM,EAAC;QACLK,QAAQC,IAAAA,qBAAQ,EAAC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,GAAGoH,aAAa;QAChBlG,OAAOiE,aAAa7F,UAAU,CAACgB,GAAG;QAClCe,UAAU8D,aAAa7F,UAAU,CAACK,IAAI;QACtCyB,WAAW+D,aAAa7F,UAAU,CAACe,UAAU;QAC7CiB,QAAQ;YACNC;YACAC;YAEA,0EAA0E;YAC1E,0EAA0E;YAC1E,qEAAqE;YACrE,qEAAqE;YACrE,iBAAiB;YACjBE,UAAUyD,aAAa7F,UAAU,CAACiB,aAAa;YAE/C,qEAAqE;YACrE,gBAAgB;YAChBkB,OAAO;QACT;QACA5B,UAAU;YACR,wEAAwE;YACxE,sCAAsC;YACtC0B,MAAMJ,IAAAA,aAAO,EAAChB,QAAQC,GAAG,IAAI;YAC7BuB,QAAQwD,aAAa7F,UAAU,CAACwB,aAAa;QAC/C;QACAc,QAAQ;YACNC,SAASsD,aAAa7F,UAAU,CAACyB,KAAK;YACtCjB,MAAMqF,aAAa7F,UAAU,CAACQ,IAAI;YAClCI,MAAMiF,aAAa7F,UAAU,CAACY,IAAI;QACpC;QACAkC,OAAO;YACLC,SAAS;YAET,0EAA0E;YAC1E,gDAAgD;YAChDC,UAAU;YACVE,QAAQ;QACV;QACA+E,QAAQrC,IAAAA,4BAAgB,EACtB;YACE,GAAGC,aAAa7F,UAAU;YAC1B0B,mBAAmBmE,aAAanE,iBAAiB;QACnD,GACA5C,qBACA;IAEJ;AACF"}
1
+ {"version":3,"sources":["../../src/config.ts"],"sourcesContent":["import { literal, union } from '@metamask/snaps-sdk';\nimport {\n createFromStruct,\n file,\n indent,\n isFile,\n SnapsStructError,\n named,\n} from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\nimport { transform } from '@swc/core';\nimport type { BrowserifyObject } from 'browserify';\nimport { dim } from 'chalk';\nimport { readFile } from 'fs/promises';\nimport Module from 'module';\nimport { basename, dirname, resolve } from 'path';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n defaulted,\n define,\n func,\n number,\n object,\n optional,\n record,\n string,\n type,\n unknown,\n empty,\n} from 'superstruct';\nimport type { Configuration as WebpackConfiguration } from 'webpack';\n\nimport { TranspilationModes } from './builders';\nimport { ConfigError } from './errors';\nimport type { YargsArgs } from './types/yargs';\nimport { CONFIG_FILE, TS_CONFIG_FILE } from './utils';\n\nconst CONFIG_FILES = [CONFIG_FILE, TS_CONFIG_FILE];\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n *\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\nexport type SnapBrowserifyConfig = {\n /**\n * The bundler to use to build the snap. For backwards compatibility, if not\n * specified, Browserify will be used. However, the Browserify bundler is\n * deprecated and will be removed in a future release, so it's recommended to\n * use the Webpack bundler instead.\n */\n bundler?: 'browserify';\n\n /**\n * The options for the Snaps CLI. These are merged with the options passed to\n * the CLI, with the CLI options taking precedence.\n *\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\n cliOptions?: {\n /**\n * The path to the snap bundle file.\n *\n * @default 'dist/bundle.js'\n */\n bundle?: string;\n\n /**\n * The directory to output the snap to. This is only used if `bundle` is\n * not specified.\n *\n * @default 'dist'\n */\n dist?: string;\n\n /**\n * Whether to attempt to evaluate the snap in SES. This can catch some errors\n * that would otherwise only be caught at runtime.\n *\n * @default true\n */\n eval?: boolean;\n\n /**\n * Whether to validate the snap manifest.\n *\n * @default true\n */\n manifest?: boolean;\n\n /**\n * The name of the bundle file. This is only used if `bundle` is not\n * specified.\n *\n * @default 'bundle.js'\n */\n outfileName?: string;\n\n /**\n * The port to run the server on.\n *\n * @default 8081\n */\n port?: number;\n\n /**\n * The root directory to serve the snap from.\n *\n * @default `process.cwd()`\n */\n root?: string;\n\n /**\n * Whether to generate source maps for the snap bundle.\n *\n * @default false\n */\n sourceMaps?: boolean;\n\n /**\n * The path to the snap entry point.\n *\n * @default 'src/index.js'\n */\n src?: string;\n\n /**\n * Whether to remove comments from the bundle.\n *\n * @default true\n */\n stripComments?: boolean;\n\n /**\n * Whether to suppress warnings.\n *\n * @default false\n */\n suppressWarnings?: boolean;\n\n /**\n * The transpilation mode to use, which determines which files are\n * transpiled.\n *\n * - `'localAndDeps'`: Transpile the snap entry point and all dependencies.\n * - `'localOnly'`: Transpile only the snap entry point.\n * - `'none'`: Don't transpile any files.\n *\n * @default 'localOnly'\n */\n transpilationMode?: 'localAndDeps' | 'localOnly' | 'none';\n\n /**\n * The dependencies to transpile when `transpilationMode` is set to\n * `'localAndDeps'`. If not specified, all dependencies will be transpiled.\n */\n depsToTranspile?: string[];\n\n /**\n * Whether to show original errors.\n *\n * @default true\n */\n verboseErrors?: boolean;\n\n /**\n * Whether to write the updated manifest to disk.\n *\n * @default true\n */\n writeManifest?: boolean;\n\n /**\n * Whether to serve the snap locally.\n *\n * @default true\n */\n serve?: boolean;\n };\n\n /**\n * A function that can be used to customize the Browserify instance used to\n * build the snap.\n *\n * @param bundler - The Browserify instance.\n * @deprecated The Browserify bundler is deprecated and will be removed in a\n * future release. Use the Webpack bundler instead.\n */\n bundlerCustomizer?: (bundler: BrowserifyObject) => void;\n};\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n */\nexport type SnapWebpackConfig = {\n /**\n * The bundler to use to build the snap. For backwards compatibility, if not\n * specified, Browserify will be used. However, the Browserify bundler is\n * deprecated and will be removed in a future release, so it's recommended to\n * use the Webpack bundler instead.\n */\n bundler: 'webpack';\n\n /**\n * The path to the snap entry point. This should be a JavaScript or TypeScript\n * file.\n */\n input: string;\n\n /**\n * Whether to generate source maps for the snap. If `true`, source maps will\n * be generated as separate files. If `'inline'`, source maps will be\n * inlined in the generated JavaScript bundle.\n *\n * @default true\n */\n sourceMap?: boolean | 'inline';\n\n /**\n * Whether to attempt to evaluate the snap in SES. This can catch some errors\n * that would otherwise only be caught at runtime.\n *\n * @default true\n */\n evaluate?: boolean;\n\n output?: {\n /**\n * The path to the directory where the snap will be built. This directory\n * will be created if it doesn't exist.\n *\n * If the path is relative, it will be resolved relative to the current\n * working directory.\n *\n * @default 'dist'\n */\n path?: string;\n\n /**\n * The name of the JavaScript bundle file.\n *\n * @default 'bundle.js'\n */\n filename?: string;\n\n /**\n * Whether to clean the output directory before building the snap. If\n * `true`, the output directory will be deleted and recreated. Otherwise,\n * the output directory will be left as-is.\n *\n * @default false\n */\n clean?: boolean;\n\n /**\n * Whether to minimize the snap bundle. If `true`, the bundle will be\n * minified. Otherwise, the bundle will be left as-is.\n *\n * @default true\n */\n minimize?: boolean;\n };\n\n manifest?: {\n /**\n * The path to the snap manifest file. If the path is relative, it will be\n * resolved relative to the current working directory.\n *\n * @default 'snap.manifest.json'\n */\n path?: string;\n\n /**\n * Whether to automatically update the manifest. If `true`, the manifest\n * will be updated with the latest shasum of the snap bundle, and some\n * common fields will be updated if they are missing or incorrect. If\n * `false`, the manifest will be left as-is.\n *\n * @default true\n */\n update?: boolean;\n };\n\n server?: {\n /**\n * Whether to enable the local server. If `true`, the snap will be served\n * from a local server, when running the `watch` command. If `false`, the\n * snap will not be served.\n *\n * @default true\n */\n enabled?: boolean;\n\n /**\n * The root directory to serve the snap from. If the path is relative, it\n * will be resolved relative to the current working directory.\n *\n * @default `process.cwd()`\n */\n root?: string;\n\n /**\n * The port to run the server on.\n *\n * @default 8081\n */\n port?: number;\n };\n\n /**\n * The environment variables to set when building the snap. These will be\n * available in the snap as `process.env`. In addition to these environment\n * variables, the following environment variables will always be set:\n *\n * - `NODE_DEBUG`: `false`\n * - `NODE_ENV`: `'production'`\n * - `DEBUG`: `false`\n *\n * Any environment variables specified here will override these defaults. You\n * can also override any variables here by setting them in your shell when\n * running the CLI.\n */\n environment?: Record<string, unknown>;\n\n /**\n * Options that control the logging output of the CLI.\n */\n stats?: {\n /**\n * Whether to enable verbose logging.\n *\n * @default false\n */\n verbose?: boolean;\n\n /**\n * Whether to log warnings about unresolved built-in modules. If `false`,\n * warnings will not be logged.\n */\n builtIns?:\n | {\n /**\n * The built-in modules to ignore when resolving modules. If a module\n * is ignored, no warning will be logged if it is not resolved.\n */\n ignore?: string[];\n }\n | false;\n\n /**\n * Whether to log warnings about the use of the `Buffer` global. If `false`,\n * warnings will not be logged. If `true`, the CLI will warn if the `Buffer`\n * global is used, but not provided by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n };\n\n /**\n * Whether to provide polyfills for node builtins. If `true`, all the available\n * polyfills will be provided. If `false` no polyfills will be provided. If a\n * configuration object is passed only the polyfills set to `true` will be provided.\n *\n * @default false\n * @example\n * ```ts\n * polyfills: true\n *\n * // or\n *\n * polyfills: {\n * assert: true,\n * buffer: true\n * }\n * ```\n */\n polyfills?:\n | boolean\n | {\n assert?: boolean;\n buffer?: boolean;\n console?: boolean;\n constants?: boolean;\n crypto?: boolean;\n domain?: boolean;\n events?: boolean;\n http?: boolean;\n https?: boolean;\n os?: boolean;\n path?: boolean;\n punycode?: boolean;\n process?: boolean;\n querystring?: boolean;\n stream?: boolean;\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex?: boolean;\n _stream_passthrough?: boolean;\n _stream_readable?: boolean;\n _stream_transform?: boolean;\n _stream_writable?: boolean;\n string_decoder?: boolean;\n /* eslint-enable @typescript-eslint/naming-convention */\n sys?: boolean;\n timers?: boolean;\n tty?: boolean;\n url?: boolean;\n util?: boolean;\n vm?: boolean;\n zlib?: boolean;\n };\n\n /**\n * A function to customize the Webpack configuration used to build the snap.\n * This function will be called with the default Webpack configuration, and\n * should return the modified configuration. If not specified, the default\n * configuration will be used.\n *\n * It's recommended to use the `webpack-merge` package to merge the default\n * configuration with your customizations. The merge function is exported as\n * `merge` from the `@metamask/snaps-cli` package.\n *\n * @example\n * ```ts\n * import type { SnapsConfig } from '@metamask/snaps-cli';\n * import { merge } from '@metamask/snaps-cli';\n *\n * const config: SnapsConfig = {\n * bundler: 'webpack',\n * entry: 'src/index.ts',\n * customizeWebpackConfig: (config) => merge(config, {\n * module: {\n * rules: [\n * {\n * test: /\\.wasm$/,\n * type: 'assets/resource',\n * },\n * ],\n * },\n * }),\n * };\n *\n * export default config;\n * ```\n */\n customizeWebpackConfig?: (\n config: WebpackConfiguration,\n ) => WebpackConfiguration;\n\n /**\n * Experimental features that can be enabled. These features are not\n * guaranteed to be stable, and may be removed or changed in a future release.\n */\n experimental?: {\n /**\n * Whether to enable WebAssembly support. If `true`, the Webpack\n * configuration will be modified to support WebAssembly. If `false`, the\n * Webpack configuration will not be modified.\n *\n * @default false\n */\n wasm?: boolean;\n };\n};\n\n/**\n * The configuration for the Snaps CLI, stored as `snap.config.js` or\n * `snap.config.ts` in the root of the project.\n */\nexport type SnapConfig = SnapBrowserifyConfig | SnapWebpackConfig;\n\ntype SnapsBrowserifyBundlerCustomizerFunction = (\n bundler: BrowserifyObject,\n) => void;\n\n// This struct is essentially the same as the `func` struct, but it's defined\n// separately so that we include the function type in the inferred TypeScript\n// type definitions.\nconst SnapsBrowserifyBundlerCustomizerFunctionStruct =\n define<SnapsBrowserifyBundlerCustomizerFunction>(\n 'function',\n func().validator,\n );\n\nexport const SnapsBrowserifyConfigStruct = object({\n bundler: defaulted(literal('browserify'), 'browserify'),\n cliOptions: defaulted(\n object({\n bundle: optional(file()),\n dist: defaulted(file(), 'dist'),\n eval: defaulted(boolean(), true),\n manifest: defaulted(boolean(), true),\n port: defaulted(number(), 8081),\n outfileName: defaulted(string(), 'bundle.js'),\n root: defaulted(file(), process.cwd()),\n sourceMaps: defaulted(boolean(), false),\n src: defaulted(file(), 'src/index.js'),\n stripComments: defaulted(boolean(), true),\n suppressWarnings: defaulted(boolean(), false),\n transpilationMode: defaulted(\n union([literal('localAndDeps'), literal('localOnly'), literal('none')]),\n 'localOnly',\n ),\n depsToTranspile: defaulted(array(string()), []),\n verboseErrors: defaulted(boolean(), true),\n writeManifest: defaulted(boolean(), true),\n serve: defaulted(boolean(), true),\n }),\n {},\n ),\n bundlerCustomizer: optional(SnapsBrowserifyBundlerCustomizerFunctionStruct),\n});\n\ntype SnapsWebpackCustomizeWebpackConfigFunction = (\n config: WebpackConfiguration,\n) => WebpackConfiguration;\n\n// This struct is essentially the same as the `func` struct, but it's defined\n// separately so that we include the function type in the inferred TypeScript\n// type definitions.\nconst SnapsWebpackCustomizeWebpackConfigFunctionStruct =\n define<SnapsWebpackCustomizeWebpackConfigFunction>(\n 'function',\n func().validator,\n );\n\nexport const SnapsWebpackConfigStruct = object({\n bundler: literal('webpack'),\n input: defaulted(file(), resolve(process.cwd(), 'src/index.js')),\n sourceMap: defaulted(union([boolean(), literal('inline')]), false),\n evaluate: defaulted(boolean(), true),\n\n output: defaulted(\n object({\n path: defaulted(file(), resolve(process.cwd(), 'dist')),\n filename: defaulted(string(), 'bundle.js'),\n clean: defaulted(boolean(), false),\n minimize: defaulted(boolean(), true),\n }),\n {},\n ),\n\n manifest: defaulted(\n object({\n path: defaulted(file(), resolve(process.cwd(), 'snap.manifest.json')),\n update: defaulted(boolean(), true),\n }),\n {},\n ),\n\n server: defaulted(\n object({\n enabled: defaulted(boolean(), true),\n root: defaulted(file(), process.cwd()),\n port: defaulted(number(), 8081),\n }),\n {},\n ),\n\n environment: defaulted(record(string(), unknown()), {}),\n\n stats: defaulted(\n object({\n verbose: defaulted(boolean(), false),\n builtIns: defaulted(\n union([\n object({ ignore: defaulted(array(string()), []) }),\n literal(false),\n ]),\n {},\n ),\n buffer: defaulted(boolean(), true),\n }),\n {},\n ),\n\n polyfills: defaulted(\n union([\n boolean(),\n object({\n assert: defaulted(boolean(), false),\n buffer: defaulted(boolean(), false),\n console: defaulted(boolean(), false),\n constants: defaulted(boolean(), false),\n crypto: defaulted(boolean(), false),\n domain: defaulted(boolean(), false),\n events: defaulted(boolean(), false),\n http: defaulted(boolean(), false),\n https: defaulted(boolean(), false),\n os: defaulted(boolean(), false),\n path: defaulted(boolean(), false),\n punycode: defaulted(boolean(), false),\n process: defaulted(boolean(), false),\n querystring: defaulted(boolean(), false),\n stream: defaulted(boolean(), false),\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex: defaulted(boolean(), false),\n _stream_passthrough: defaulted(boolean(), false),\n _stream_readable: defaulted(boolean(), false),\n _stream_transform: defaulted(boolean(), false),\n _stream_writable: defaulted(boolean(), false),\n string_decoder: defaulted(boolean(), false),\n /* eslint-enable @typescript-eslint/naming-convention */\n sys: defaulted(boolean(), false),\n timers: defaulted(boolean(), false),\n tty: defaulted(boolean(), false),\n url: defaulted(boolean(), false),\n util: defaulted(boolean(), false),\n vm: defaulted(boolean(), false),\n zlib: defaulted(boolean(), false),\n }),\n ]),\n false,\n ),\n\n customizeWebpackConfig: optional(\n SnapsWebpackCustomizeWebpackConfigFunctionStruct,\n ),\n\n experimental: defaulted(\n object({\n wasm: defaulted(boolean(), false),\n }),\n {},\n ),\n});\n\nexport const SnapsConfigStruct = type({\n bundler: defaulted(\n union([literal('browserify'), literal('webpack')]),\n 'browserify',\n ),\n});\n\nexport const LegacyOptionsStruct = union([\n named(\n 'object with `transpilationMode` set to `localAndDeps` and `depsToTranspile` set to an array of strings',\n type({\n depsToTranspile: array(string()),\n transpilationMode: literal(TranspilationModes.LocalAndDeps),\n writeManifest: boolean(),\n bundlerCustomizer: optional(\n SnapsBrowserifyBundlerCustomizerFunctionStruct,\n ),\n }),\n ),\n named(\n 'object without `depsToTranspile`',\n type({\n depsToTranspile: named('empty array', empty(array())),\n transpilationMode: union([\n literal(TranspilationModes.LocalOnly),\n literal(TranspilationModes.None),\n ]),\n writeManifest: boolean(),\n bundlerCustomizer: optional(\n SnapsBrowserifyBundlerCustomizerFunctionStruct,\n ),\n }),\n ),\n]);\n\nexport type LegacyOptions = Infer<typeof LegacyOptionsStruct>;\n\nexport type ProcessedBrowserifyConfig = Infer<\n typeof SnapsBrowserifyConfigStruct\n>;\n\nexport type ProcessedWebpackConfig = Infer<typeof SnapsWebpackConfigStruct> & {\n /**\n * The legacy Browserify config, if the bundler is Browserify. This is used\n * to support the legacy config format.\n */\n legacy?: LegacyOptions;\n};\n\nexport type ProcessedConfig = ProcessedWebpackConfig;\n\n/**\n * Get a validated snap config. This validates the config and adds default\n * values for any missing properties.\n *\n * @param config - The config to validate.\n * @param argv - The CLI arguments.\n * @returns The validated config.\n */\nexport function getConfig(config: unknown, argv: YargsArgs): ProcessedConfig {\n const prefix = 'The snap config file is invalid';\n const suffix = dim(\n // TODO: Link to `docs.metamask.io` once the docs are published.\n 'Refer to the documentation for more information: https://github.com/MetaMask/snaps/tree/main/packages/snaps-cli/',\n );\n\n const { bundler } = createFromStruct(\n config,\n SnapsConfigStruct,\n prefix,\n suffix,\n );\n\n if (bundler === 'browserify') {\n const legacyConfig = createFromStruct(\n config,\n SnapsBrowserifyConfigStruct,\n prefix,\n suffix,\n );\n\n return getWebpackConfig(mergeLegacyOptions(argv, legacyConfig));\n }\n\n return createFromStruct(config, SnapsWebpackConfigStruct, prefix, suffix);\n}\n\n/**\n * Load a snap config from a file. This supports both JavaScript and TypeScript\n * config files, in the CommonJS module format and the ES module format.\n *\n * This assumes that the config file exports a default object, either through\n * `module.exports` or `export default`.\n *\n * @param path - The full path to the config file.\n * @param argv - The CLI arguments.\n * @returns The validated config.\n * @throws If the config file is invalid, or if the config file does not have a\n * default export.\n */\nexport async function loadConfig(path: string, argv: YargsArgs) {\n try {\n const contents = await readFile(path, 'utf8');\n const source = await transform(contents, {\n swcrc: false,\n jsc: {\n parser: {\n syntax: 'typescript',\n },\n },\n module: {\n type: 'commonjs',\n },\n });\n\n const config = new Module(path);\n\n // @ts-expect-error - This function is not typed.\n config.paths = Module._nodeModulePaths(dirname(path));\n\n // @ts-expect-error - This function is not typed.\n config._compile(source.code, path);\n\n if (!hasProperty(config.exports, 'default')) {\n return getConfig(config.exports, argv);\n }\n\n return getConfig(config.exports.default, argv);\n } catch (error) {\n if (error instanceof SnapsStructError) {\n throw new ConfigError(error.message);\n }\n\n throw new ConfigError(\n `Unable to load snap config file at \"${path}\".\\n\\n${indent(\n error.message,\n )}`,\n );\n }\n}\n\n/**\n * Resolve a snap config. This function will look for a `snap.config.js` or\n * `snap.config.ts` file in the current or specified directory.\n *\n * @param path - The path to resolve the snap config from. Defaults to the\n * current working directory.\n * @param argv - The CLI arguments.\n * @returns The resolved and validated snap config.\n * @throws If a snap config could not be found.\n */\nexport async function resolveConfig(path: string, argv: YargsArgs) {\n for (const configFile of CONFIG_FILES) {\n const filePath = resolve(path, configFile);\n if (await isFile(filePath)) {\n return await loadConfig(filePath, argv);\n }\n }\n\n throw new ConfigError(\n `Could not find a \"snap.config.js\" or \"snap.config.ts\" file in the current or specified directory (\"${path}\").`,\n );\n}\n\n/**\n * Get a snap config from the CLI arguments. This will either load the config\n * from the specified config file, or resolve the config from the current\n * working directory.\n *\n * @param argv - The CLI arguments.\n * @param cwd - The current working directory. Defaults to `process.cwd()`.\n * @returns The resolved and validated snap config.\n */\nexport async function getConfigByArgv(\n argv: YargsArgs,\n cwd: string = process.cwd(),\n) {\n if (argv.config) {\n if (!(await isFile(argv.config))) {\n throw new ConfigError(\n `Could not find a config file at \"${argv.config}\". Make sure that the path is correct.`,\n );\n }\n\n return await loadConfig(argv.config, argv);\n }\n\n return await resolveConfig(cwd, argv);\n}\n\n/**\n * Merge legacy CLI options into the config. This is used to support the legacy\n * config format, where options can be specified both in the config file and\n * through CLI flags.\n *\n * @param argv - The CLI arguments.\n * @param config - The config to merge the CLI options into.\n * @returns The config with the CLI options merged in.\n * @deprecated This function is only used to support the legacy config format.\n */\nexport function mergeLegacyOptions(\n argv: YargsArgs,\n config: ProcessedBrowserifyConfig,\n) {\n const cliOptions = Object.keys(config.cliOptions).reduce<\n ProcessedBrowserifyConfig['cliOptions']\n >((accumulator, key) => {\n if (argv[key] !== undefined) {\n return {\n ...accumulator,\n [key]: argv[key],\n };\n }\n\n return accumulator;\n }, config.cliOptions);\n\n return {\n ...config,\n cliOptions,\n };\n}\n\n/**\n * Get a Webpack config from a legacy browserify config. This is used to\n * support the legacy config format, and convert it to the new format.\n *\n * @param legacyConfig - The legacy browserify config.\n * @returns The Webpack config.\n */\nexport function getWebpackConfig(\n legacyConfig: ProcessedBrowserifyConfig,\n): ProcessedWebpackConfig {\n const defaultConfig = create(\n { bundler: 'webpack' },\n SnapsWebpackConfigStruct,\n );\n\n // The legacy config has two options for specifying the output path and\n // filename: `bundle`, and `dist` + `outfileName`. If `bundle` is specified,\n // we use that as the output path and filename. Otherwise, we use `dist` and\n // `outfileName`.\n const path = legacyConfig.cliOptions.bundle\n ? dirname(legacyConfig.cliOptions.bundle)\n : legacyConfig.cliOptions.dist;\n\n const filename = legacyConfig.cliOptions.bundle\n ? basename(legacyConfig.cliOptions.bundle)\n : legacyConfig.cliOptions.outfileName;\n\n return {\n ...defaultConfig,\n input: legacyConfig.cliOptions.src,\n evaluate: legacyConfig.cliOptions.eval,\n sourceMap: legacyConfig.cliOptions.sourceMaps,\n output: {\n path,\n filename,\n\n // The legacy config has an option to remove comments from the bundle, but\n // the terser plugin does this by default, so we only enable the terser if\n // the legacy config has `stripComments` set to `true`. This is not a\n // perfect solution, but it's the best we can do without breaking the\n // legacy config.\n minimize: legacyConfig.cliOptions.stripComments,\n\n // The legacy config does not have a `clean` option, so we default to\n // `false` here.\n clean: false,\n },\n manifest: {\n // The legacy config does not have a `manifest` option, so we default to\n // `process.cwd()/snap.manifest.json`.\n path: resolve(process.cwd(), 'snap.manifest.json'),\n update: legacyConfig.cliOptions.writeManifest,\n },\n server: {\n enabled: legacyConfig.cliOptions.serve,\n port: legacyConfig.cliOptions.port,\n root: legacyConfig.cliOptions.root,\n },\n stats: {\n verbose: false,\n\n // These plugins are designed to be used with the modern config format, so\n // we disable them for the legacy config format.\n builtIns: false,\n buffer: false,\n },\n legacy: createFromStruct(\n {\n ...legacyConfig.cliOptions,\n bundlerCustomizer: legacyConfig.bundlerCustomizer,\n },\n LegacyOptionsStruct,\n 'Invalid Browserify CLI options',\n ),\n };\n}\n"],"names":["SnapsBrowserifyConfigStruct","SnapsWebpackConfigStruct","SnapsConfigStruct","LegacyOptionsStruct","getConfig","loadConfig","resolveConfig","getConfigByArgv","mergeLegacyOptions","getWebpackConfig","CONFIG_FILES","CONFIG_FILE","TS_CONFIG_FILE","SnapsBrowserifyBundlerCustomizerFunctionStruct","define","func","validator","object","bundler","defaulted","literal","cliOptions","bundle","optional","file","dist","eval","boolean","manifest","port","number","outfileName","string","root","process","cwd","sourceMaps","src","stripComments","suppressWarnings","transpilationMode","union","depsToTranspile","array","verboseErrors","writeManifest","serve","bundlerCustomizer","SnapsWebpackCustomizeWebpackConfigFunctionStruct","input","resolve","sourceMap","evaluate","output","path","filename","clean","minimize","update","server","enabled","environment","record","unknown","stats","verbose","builtIns","ignore","buffer","polyfills","assert","console","constants","crypto","domain","events","http","https","os","punycode","querystring","stream","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_writable","string_decoder","sys","timers","tty","url","util","vm","zlib","customizeWebpackConfig","experimental","wasm","type","named","TranspilationModes","LocalAndDeps","empty","LocalOnly","None","config","argv","prefix","suffix","dim","createFromStruct","legacyConfig","contents","readFile","source","transform","swcrc","jsc","parser","syntax","module","Module","paths","_nodeModulePaths","dirname","_compile","code","hasProperty","exports","default","error","SnapsStructError","ConfigError","message","indent","configFile","filePath","isFile","Object","keys","reduce","accumulator","key","undefined","defaultConfig","create","basename","legacy"],"mappings":";;;;;;;;;;;IAyeaA,2BAA2B;eAA3BA;;IA0CAC,wBAAwB;eAAxBA;;IAqGAC,iBAAiB;eAAjBA;;IAOAC,mBAAmB;eAAnBA;;IAoDGC,SAAS;eAATA;;IAyCMC,UAAU;eAAVA;;IAmDAC,aAAa;eAAbA;;IAsBAC,eAAe;eAAfA;;IA2BNC,kBAAkB;eAAlBA;;IA8BAC,gBAAgB;eAAhBA;;;0BA91Be;4BAQxB;uBACqB;sBACF;uBAEN;0BACK;+DACN;sBACwB;6BAiBpC;0BAG4B;wBACP;wBAEgB;;;;;;AAE5C,MAAMC,eAAe;IAACC,mBAAW;IAAEC,sBAAc;CAAC;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AOyD,aAAa1F,UAAU,CAACC,MAAM,GACvCsG,IAAAA,aAAO,EAACb,aAAa1F,UAAU,CAACC,MAAM,IACtCyF,aAAa1F,UAAU,CAACI,IAAI;IAEhC,MAAM8B,WAAWwD,aAAa1F,UAAU,CAACC,MAAM,GAC3C4H,IAAAA,cAAQ,EAACnC,aAAa1F,UAAU,CAACC,MAAM,IACvCyF,aAAa1F,UAAU,CAACU,WAAW;IAEvC,OAAO;QACL,GAAGiH,aAAa;QAChB/F,OAAO8D,aAAa1F,UAAU,CAACgB,GAAG;QAClCe,UAAU2D,aAAa1F,UAAU,CAACK,IAAI;QACtCyB,WAAW4D,aAAa1F,UAAU,CAACe,UAAU;QAC7CiB,QAAQ;YACNC;YACAC;YAEA,0EAA0E;YAC1E,0EAA0E;YAC1E,qEAAqE;YACrE,qEAAqE;YACrE,iBAAiB;YACjBE,UAAUsD,aAAa1F,UAAU,CAACiB,aAAa;YAE/C,qEAAqE;YACrE,gBAAgB;YAChBkB,OAAO;QACT;QACA5B,UAAU;YACR,wEAAwE;YACxE,sCAAsC;YACtC0B,MAAMJ,IAAAA,aAAO,EAAChB,QAAQC,GAAG,IAAI;YAC7BuB,QAAQqD,aAAa1F,UAAU,CAACwB,aAAa;QAC/C;QACAc,QAAQ;YACNC,SAASmD,aAAa1F,UAAU,CAACyB,KAAK;YACtCjB,MAAMkF,aAAa1F,UAAU,CAACQ,IAAI;YAClCI,MAAM8E,aAAa1F,UAAU,CAACY,IAAI;QACpC;QACA+B,OAAO;YACLC,SAAS;YAET,0EAA0E;YAC1E,gDAAgD;YAChDC,UAAU;YACVE,QAAQ;QACV;QACA+E,QAAQrC,IAAAA,4BAAgB,EACtB;YACE,GAAGC,aAAa1F,UAAU;YAC1B0B,mBAAmBgE,aAAahE,iBAAiB;QACnD,GACA5C,qBACA;IAEJ;AACF"}
@@ -117,7 +117,7 @@ async function getDefaultConfiguration(config, options = {
117
117
  */ module: {
118
118
  rules: [
119
119
  {
120
- test: /\.[tj]sx?$/u,
120
+ test: /\.(js|mjs|cjs|ts)$/u,
121
121
  exclude: /node_modules/u,
122
122
  use: await (0, _utils.getDefaultLoader)(config)
123
123
  },
@@ -147,10 +147,12 @@ async function getDefaultConfiguration(config, options = {
147
147
  * @see https://webpack.js.org/configuration/resolve/
148
148
  */ resolve: {
149
149
  /**
150
- * The extensions to resolve. We set it to resolve `.js` and `.ts`
150
+ * The extensions to resolve. We set it to resolve `.(c|m)?js` and `.ts`
151
151
  * files.
152
152
  */ extensions: [
153
153
  '.js',
154
+ '.mjs',
155
+ '.cjs',
154
156
  '.ts'
155
157
  ],
156
158
  /**
@@ -187,10 +189,11 @@ async function getDefaultConfiguration(config, options = {
187
189
  verbose: config.stats.verbose
188
190
  }, options.spinner),
189
191
  /**
190
- * The `EnvironmentPlugin` is a Webpack plugin that adds environment
191
- * variables to the bundle. We use it to add the `NODE_ENV` and `DEBUG`
192
- * environment variables.
193
- */ new _webpack.EnvironmentPlugin(config.environment),
192
+ * The `DefinePlugin` is a Webpack plugin that adds static values to the
193
+ * bundle. We use it to add the `NODE_DEBUG`, `NODE_ENV`, and `DEBUG`
194
+ * environment variables, as well as any custom environment
195
+ * variables (as `process.env`).
196
+ */ new _webpack.DefinePlugin((0, _utils.getEnvironmentVariables)(config.environment)),
194
197
  /**
195
198
  * The `ProgressPlugin` is a Webpack plugin that logs the progress of
196
199
  * the build. We set it to log the progress to the spinner.
@@ -205,7 +208,7 @@ async function getDefaultConfiguration(config, options = {
205
208
  builtInResolver,
206
209
  builtIns: Boolean(config.stats.builtIns),
207
210
  buffer: config.stats.buffer
208
- }, options.spinner),
211
+ }),
209
212
  /**
210
213
  * The `WatchPlugin` is a Webpack plugin that adds extra files to watch
211
214
  * for changes. This is useful for rebuilding the bundle when the
@@ -242,6 +245,19 @@ async function getDefaultConfiguration(config, options = {
242
245
  ]
243
246
  },
244
247
  /**
248
+ * The performance configuration. This tells Webpack how to handle
249
+ * performance hints.
250
+ *
251
+ * @see https://webpack.js.org/configuration/performance/
252
+ */ performance: {
253
+ /**
254
+ * The hints to show. We set it to `false`, so that we don't get
255
+ * performance hints, as they are not relevant for Snaps.
256
+ *
257
+ * @see https://webpack.js.org/configuration/performance/#performancehints
258
+ */ hints: false
259
+ },
260
+ /**
245
261
  * The infrastructure logging configuration. This tells Webpack how to
246
262
  * log messages.
247
263
  *
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/webpack/config.ts"],"sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-webpack-plugin';\nimport type { Ora } from 'ora';\nimport { resolve } from 'path';\nimport TerserPlugin from 'terser-webpack-plugin';\nimport type { Configuration } from 'webpack';\nimport { EnvironmentPlugin, ProgressPlugin, ProvidePlugin } from 'webpack';\n\nimport type { ProcessedWebpackConfig } from '../config';\nimport {\n SnapsBuiltInResolver,\n SnapsBundleWarningsPlugin,\n SnapsStatsPlugin,\n SnapsWatchPlugin,\n} from './plugins';\nimport {\n BROWSERSLIST_FILE,\n getDefaultLoader,\n getDevTool,\n getFallbacks,\n getProgressHandler,\n} from './utils';\n\nexport type WebpackOptions = {\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: ProcessedWebpackConfig,\n options: WebpackOptions = {\n evaluate: config.evaluate,\n },\n): Promise<Configuration> {\n const spinnerText = options.spinner?.text;\n const builtInResolver =\n config.stats.builtIns &&\n new SnapsBuiltInResolver(config.stats.builtIns, options.spinner);\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 as a CommonJS module. This\n * is necessary for MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrarytarget\n */\n type: 'commonjs',\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: /\\.[tj]sx?$/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 config.experimental.wasm && {\n test: /\\.wasm$/u,\n use: {\n loader: resolve(__dirname, 'loaders', 'wasm'),\n },\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 `.js` and `.ts`\n * files.\n */\n extensions: ['.js', '.ts'],\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 `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 manifestPath: config.manifest.path,\n writeManifest: config.manifest.update,\n eval: !options.watch && options.evaluate,\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 `EnvironmentPlugin` is a Webpack plugin that adds environment\n * variables to the bundle. We use it to add the `NODE_ENV` and `DEBUG`\n * environment variables.\n */\n new EnvironmentPlugin(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 {\n builtInResolver,\n builtIns: Boolean(config.stats.builtIns),\n buffer: config.stats.buffer,\n },\n options.spinner,\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 /**\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 * 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 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"],"names":["getDefaultConfiguration","config","options","evaluate","spinnerText","spinner","text","builtInResolver","stats","builtIns","SnapsBuiltInResolver","target","BROWSERSLIST_FILE","mode","entry","input","devtool","getDevTool","sourceMap","output","clean","filename","path","publicPath","library","type","chunkFormat","module","rules","test","exclude","use","getDefaultLoader","resolve","fullySpecified","experimental","wasm","loader","__dirname","extensions","fallback","getFallbacks","polyfills","plugins","SnapsWebpackPlugin","manifestPath","manifest","writeManifest","update","eval","watch","SnapsStatsPlugin","verbose","EnvironmentPlugin","environment","ProgressPlugin","handler","getProgressHandler","SnapsBundleWarningsPlugin","Boolean","buffer","SnapsWatchPlugin","bundle","files","ProvidePlugin","Buffer","filter","optimization","minimize","minimizer","TerserPlugin","parallel","infrastructureLogging","level"],"mappings":";;;;+BA0DsBA;;;eAAAA;;;2EA1DS;sBAEP;4EACC;yBAEwC;yBAQ1D;uBAOA;;;;;;AAsCA,eAAeA,wBACpBC,MAA8B,EAC9BC,UAA0B;IACxBC,UAAUF,OAAOE,QAAQ;AAC3B,CAAC;IAED,MAAMC,cAAcF,QAAQG,OAAO,EAAEC;IACrC,MAAMC,kBACJN,OAAOO,KAAK,CAACC,QAAQ,IACrB,IAAIC,6BAAoB,CAACT,OAAOO,KAAK,CAACC,QAAQ,EAAEP,QAAQG,OAAO;IAEjE,OAAO;QACL;;;;;;;KAOC,GACDM,QAAQ,CAAC,aAAa,EAAEC,wBAAiB,CAAC,CAAC;QAE3C;;;;;KAKC,GACDC,MAAM;QAEN;;;;KAIC,GACDC,OAAOb,OAAOc,KAAK;QAEnB;;;;;KAKC,GACDC,SAASC,IAAAA,iBAAU,EAAChB,OAAOiB,SAAS;QAEpC;;;;;;KAMC,GACDV,OAAO;QAEP;;;;KAIC,GACD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iB,CAACpD,OAAOqD,WAAW;YAExC;;;OAGC,GACD,IAAIC,uBAAc,CAAC;gBACjBC,SAASC,IAAAA,yBAAkB,EAACvD,QAAQG,OAAO,EAAED;YAC/C;YAEA;;;;OAIC,GACD,IAAIsD,kCAAyB,CAC3B;gBACEnD;gBACAE,UAAUkD,QAAQ1D,OAAOO,KAAK,CAACC,QAAQ;gBACvCmD,QAAQ3D,OAAOO,KAAK,CAACoD,MAAM;YAC7B,GACA1D,QAAQG,OAAO;YAGjB;;;;OAIC,GACDH,QAAQgD,KAAK,IACX,IAAIW,yBAAgB,CAClB;gBACEC,QAAQ7B,IAAAA,aAAO,EAAChC,OAAOkB,MAAM,CAACG,IAAI,EAAErB,OAAOkB,MAAM,CAACE,QAAQ;gBAC1DlB,UAAUD,QAAQC,QAAQ;gBAC1B4D,OAAO;oBAAC9D,OAAO6C,QAAQ,CAACxB,IAAI;iBAAC;YAC/B,GACApB,QAAQG,OAAO;YAGnB;;;OAGC,GACAJ,CAAAA,OAAOyC,SAAS,KAAK,QACnBzC,OAAOyC,SAAS,KAAK,SAASzC,OAAOyC,SAAS,CAACkB,MAAM,KACtD,IAAII,sBAAa,CAAC;gBAChBC,QAAQ;oBAAC;oBAAU;iBAAS;YAC9B;SACH,CAACC,MAAM,CAACP;QAET;;;;KAIC,GACDQ,cAAc;YACZC,UAAUnE,OAAOkB,MAAM,CAACiD,QAAQ;YAEhC;;OAEC,GACDC,WAAW;gBACT,IAAIC,4BAAY,CAAC;oBACfC,UAAU;gBACZ;aACD;QACH;QAEA;;;;;KAKC,GACDC,uBAAuB;YACrB;;;OAGC,GACDC,OAAO;QACT;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/webpack/config.ts"],"sourcesContent":["import SnapsWebpackPlugin from '@metamask/snaps-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';\n\nimport type { ProcessedWebpackConfig } from '../config';\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 getProgressHandler,\n} from './utils';\n\nexport type WebpackOptions = {\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: ProcessedWebpackConfig,\n options: WebpackOptions = {\n evaluate: config.evaluate,\n },\n): Promise<Configuration> {\n const spinnerText = options.spinner?.text;\n const builtInResolver =\n config.stats.builtIns &&\n new SnapsBuiltInResolver(config.stats.builtIns, options.spinner);\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 as a CommonJS module. This\n * is necessary for MetaMask Snaps.\n *\n * @see https://webpack.js.org/configuration/output/#outputlibrarytarget\n */\n type: 'commonjs',\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|mjs|cjs|ts)$/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 config.experimental.wasm && {\n test: /\\.wasm$/u,\n use: {\n loader: resolve(__dirname, 'loaders', 'wasm'),\n },\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)?js` and `.ts`\n * files.\n */\n extensions: ['.js', '.mjs', '.cjs', '.ts'],\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 `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 manifestPath: config.manifest.path,\n writeManifest: config.manifest.update,\n eval: !options.watch && options.evaluate,\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 /**\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 * 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"],"names":["getDefaultConfiguration","config","options","evaluate","spinnerText","spinner","text","builtInResolver","stats","builtIns","SnapsBuiltInResolver","target","BROWSERSLIST_FILE","mode","entry","input","devtool","getDevTool","sourceMap","output","clean","filename","path","publicPath","library","type","chunkFormat","module","rules","test","exclude","use","getDefaultLoader","resolve","fullySpecified","experimental","wasm","loader","__dirname","extensions","fallback","getFallbacks","polyfills","plugins","SnapsWebpackPlugin","manifestPath","manifest","writeManifest","update","eval","watch","SnapsStatsPlugin","verbose","DefinePlugin","getEnvironmentVariables","environment","ProgressPlugin","handler","getProgressHandler","SnapsBundleWarningsPlugin","Boolean","buffer","SnapsWatchPlugin","bundle","files","ProvidePlugin","Buffer","filter","optimization","minimize","minimizer","TerserPlugin","parallel","performance","hints","infrastructureLogging","level"],"mappings":";;;;+BA2DsBA;;;eAAAA;;;2EA3DS;sBAEP;4EACC;yBAEmC;yBAQrD;uBAQA;;;;;;AAsCA,eAAeA,wBACpBC,MAA8B,EAC9BC,UAA0B;IACxBC,UAAUF,OAAOE,QAAQ;AAC3B,CAAC;IAED,MAAMC,cAAcF,QAAQG,OAAO,EAAEC;IACrC,MAAMC,kBACJN,OAAOO,KAAK,CAACC,QAAQ,IACrB,IAAIC,6BAAoB,CAACT,OAAOO,KAAK,CAACC,QAAQ,EAAEP,QAAQG,OAAO;IAEjE,OAAO;QACL;;;;;;;KAOC,GACDM,QAAQ,CAAC,aAAa,EAAEC,wBAAiB,CAAC,CAAC;QAE3C;;;;;KAKC,GACDC,MAAM;QAEN;;;;KAIC,GACDC,OAAOb,OAAOc,KAAK;QAEnB;;;;;KAKC,GACDC,SAASC,IAAAA,iBAAU,EAAChB,OAAOiB,SAAS;QAEpC;;;;;;KAMC,GACDV,OAAO;QAEP;;;;KAIC,GACDW,QAAQ;YACN;;;;;;OAMC,GACDC,OAAOnB,OAAOkB,MAAM,CAACC,KAAK;YAE1B;;;;;OAKC,GACDC,UAAUpB,OAAOkB,MAAM,CAACE,QAAQ;YAEhC;;;;;OAKC,GACDC,MAAM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AAED;YAC/C;YAEA;;;;OAIC,GACD,IAAIuD,kCAAyB,CAAC;gBAC5BpD;gBACAE,UAAUmD,QAAQ3D,OAAOO,KAAK,CAACC,QAAQ;gBACvCoD,QAAQ5D,OAAOO,KAAK,CAACqD,MAAM;YAC7B;YAEA;;;;OAIC,GACD3D,QAAQgD,KAAK,IACX,IAAIY,yBAAgB,CAClB;gBACEC,QAAQ9B,IAAAA,aAAO,EAAChC,OAAOkB,MAAM,CAACG,IAAI,EAAErB,OAAOkB,MAAM,CAACE,QAAQ;gBAC1DlB,UAAUD,QAAQC,QAAQ;gBAC1B6D,OAAO;oBAAC/D,OAAO6C,QAAQ,CAACxB,IAAI;iBAAC;YAC/B,GACApB,QAAQG,OAAO;YAGnB;;;OAGC,GACAJ,CAAAA,OAAOyC,SAAS,KAAK,QACnBzC,OAAOyC,SAAS,KAAK,SAASzC,OAAOyC,SAAS,CAACmB,MAAM,KACtD,IAAII,sBAAa,CAAC;gBAChBC,QAAQ;oBAAC;oBAAU;iBAAS;YAC9B;SACH,CAACC,MAAM,CAACP;QAET;;;;KAIC,GACDQ,cAAc;YACZC,UAAUpE,OAAOkB,MAAM,CAACkD,QAAQ;YAEhC;;OAEC,GACDC,WAAW;gBACT,IAAIC,4BAAY,CAAC;oBACfC,UAAU;gBACZ;aACD;QACH;QAEA;;;;;KAKC,GACDC,aAAa;YACX;;;;;OAKC,GACDC,OAAO;QACT;QAEA;;;;;KAKC,GACDC,uBAAuB;YACrB;;;OAGC,GACDC,OAAO;QACT;IACF;AACF"}
@@ -26,6 +26,7 @@ _export(exports, {
26
26
  }
27
27
  });
28
28
  const _utils = require("@metamask/utils");
29
+ const _path = require("path");
29
30
  function getImports(importMap) {
30
31
  return Object.entries(importMap).map(([moduleName, exportNames])=>`import { ${exportNames.join(', ')} } from ${JSON.stringify(moduleName)};`).join('\n');
31
32
  }
@@ -68,8 +69,9 @@ const loader = async function loader(source) {
68
69
  }, {});
69
70
  // Add the WASM import as a dependency so that Webpack will watch it for
70
71
  // changes.
72
+ const path = (0, _path.dirname)(this.resourcePath);
71
73
  for (const name of Object.keys(imports)){
72
- this.addDependency(name);
74
+ this.addDependency((0, _path.resolve)(path, name));
73
75
  }
74
76
  return `
75
77
  ${getImports(imports)}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/webpack/loaders/wasm.ts"],"sourcesContent":["/* eslint-disable no-restricted-globals */\n\nimport { assert } from '@metamask/utils';\nimport type { LoaderDefinitionFunction } from 'webpack';\n\n/**\n * Get the imports code for the WASM module. This code imports each of the\n * imports from the WASM module.\n *\n * @param importMap - The import map for the WASM module.\n * @returns The imports code for the WASM module.\n */\nexport function getImports(importMap: Record<string, string[]>) {\n return Object.entries(importMap)\n .map(\n ([moduleName, exportNames]) =>\n `import { ${exportNames.join(', ')} } from ${JSON.stringify(\n moduleName,\n )};`,\n )\n .join('\\n');\n}\n\n/**\n * Get the imports code to use in `WebAssembly.Instance`. This code adds each of\n * the imports to the `imports` object.\n *\n * @param importMap - The import map for the WASM module.\n * @returns The imports code for the WASM module.\n */\nexport function getModuleImports(importMap: Record<string, string[]>) {\n return Object.entries(importMap)\n .map(\n ([moduleName, exportNames]) =>\n `${JSON.stringify(moduleName)}: { ${exportNames.join(', ')} },`,\n )\n .join('\\n');\n}\n\n/**\n * Get the exports code for the WASM module. This code exports each of the\n * exports from the WASM module as a variable. This function assumes that the\n * exports are available in a variable named `exports`.\n *\n * @param descriptors - The export descriptors from the WASM module.\n * @returns The exports code for the WASM module.\n */\nexport function getExports(descriptors: WebAssembly.ModuleExportDescriptor[]) {\n return descriptors\n .map((descriptor) => {\n if (descriptor.name === 'default') {\n return `export default exports[${JSON.stringify(descriptor.name)}];`;\n }\n\n return `export const ${descriptor.name} = exports[${JSON.stringify(\n descriptor.name,\n )}];`;\n })\n .join('\\n');\n}\n\n/**\n * A Webpack loader that synchronously loads the WASM module. This makes it\n * possible to import the WASM module directly.\n *\n * @param source - The WASM module as `Uint8Array`.\n * @returns The WASM module as a JavaScript string.\n * @example\n * ```ts\n * import * as wasm from './program.wasm';\n *\n * // Do something with the WASM module...\n * ```\n */\n// Note: This function needs to be defined like this, so that Webpack can bind\n// `this` to the loader context, and TypeScript can infer the type of `this`.\nconst loader: LoaderDefinitionFunction = async function loader(\n source: unknown,\n) {\n assert(source instanceof Uint8Array, 'Expected source to be a Uint8Array.');\n\n const bytes = new Uint8Array(source);\n const wasmModule = await WebAssembly.compile(bytes);\n\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const exports = WebAssembly.Module.exports(wasmModule);\n const imports = WebAssembly.Module.imports(wasmModule).reduce<\n Record<string, string[]>\n >((target, descriptor) => {\n target[descriptor.module] ??= [];\n target[descriptor.module].push(descriptor.name);\n\n return target;\n }, {});\n\n // Add the WASM import as a dependency so that Webpack will watch it for\n // changes.\n for (const name of Object.keys(imports)) {\n this.addDependency(name);\n }\n\n return `\n ${getImports(imports)}\n\n const bytes = new Uint8Array(${JSON.stringify(Array.from(source))});\n const module = new WebAssembly.Module(bytes);\n const instance = new WebAssembly.Instance(module, {\n ${getModuleImports(imports)}\n });\n\n const exports = instance.exports;\n ${getExports(exports)}\n `;\n};\n\nexport default loader;\n\n// By setting `raw` to `true`, we are telling Webpack to provide the source as a\n// `Uint8Array` instead of converting it to a string. This allows us to avoid\n// having to convert the source back to a `Uint8Array` in the loader.\nexport const raw = true;\n"],"names":["getImports","getModuleImports","getExports","raw","importMap","Object","entries","map","moduleName","exportNames","join","JSON","stringify","descriptors","descriptor","name","loader","source","assert","Uint8Array","bytes","wasmModule","WebAssembly","compile","exports","Module","imports","reduce","target","module","push","keys","addDependency","Array","from"],"mappings":"AAAA,wCAAwC;;;;;;;;;;;IAYxBA,UAAU;eAAVA;;IAkBAC,gBAAgB;eAAhBA;;IAiBAC,UAAU;eAAVA;;IAoEhB,OAAsB;eAAtB;;IAKaC,GAAG;eAAHA;;;uBAtHU;AAUhB,SAASH,WAAWI,SAAmC;IAC5D,OAAOC,OAAOC,OAAO,CAACF,W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,CAACd,WAAWe,MAAM,CAAC,CAACC,IAAI,CAAChB,WAAWC,IAAI;QAE9C,OAAOa;IACT,GAAG,CAAC;IAEJ,wEAAwE;IACxE,WAAW;IACX,KAAK,MAAMb,QAAQV,OAAO0B,IAAI,CAACL,SAAU;QACvC,IAAI,CAACM,aAAa,CAACjB;IACrB;IAEA,OAAO,CAAC;IACN,EAAEf,WAAW0B,SAAS;;iCAEO,EAAEf,KAAKC,SAAS,CAACqB,MAAMC,IAAI,CAACjB,SAAS;;;MAGhE,EAAEhB,iBAAiByB,SAAS;;;;IAI9B,EAAExB,WAAWsB,UAAS;EACxB,CAAC;AACH;MAEA,WAAeR;AAKR,MAAMb,MAAM"}
1
+ {"version":3,"sources":["../../../../src/webpack/loaders/wasm.ts"],"sourcesContent":["/* eslint-disable no-restricted-globals */\n\nimport { assert } from '@metamask/utils';\nimport { dirname, resolve } from 'path';\nimport type { LoaderDefinitionFunction } from 'webpack';\n\n/**\n * Get the imports code for the WASM module. This code imports each of the\n * imports from the WASM module.\n *\n * @param importMap - The import map for the WASM module.\n * @returns The imports code for the WASM module.\n */\nexport function getImports(importMap: Record<string, string[]>) {\n return Object.entries(importMap)\n .map(\n ([moduleName, exportNames]) =>\n `import { ${exportNames.join(', ')} } from ${JSON.stringify(\n moduleName,\n )};`,\n )\n .join('\\n');\n}\n\n/**\n * Get the imports code to use in `WebAssembly.Instance`. This code adds each of\n * the imports to the `imports` object.\n *\n * @param importMap - The import map for the WASM module.\n * @returns The imports code for the WASM module.\n */\nexport function getModuleImports(importMap: Record<string, string[]>) {\n return Object.entries(importMap)\n .map(\n ([moduleName, exportNames]) =>\n `${JSON.stringify(moduleName)}: { ${exportNames.join(', ')} },`,\n )\n .join('\\n');\n}\n\n/**\n * Get the exports code for the WASM module. This code exports each of the\n * exports from the WASM module as a variable. This function assumes that the\n * exports are available in a variable named `exports`.\n *\n * @param descriptors - The export descriptors from the WASM module.\n * @returns The exports code for the WASM module.\n */\nexport function getExports(descriptors: WebAssembly.ModuleExportDescriptor[]) {\n return descriptors\n .map((descriptor) => {\n if (descriptor.name === 'default') {\n return `export default exports[${JSON.stringify(descriptor.name)}];`;\n }\n\n return `export const ${descriptor.name} = exports[${JSON.stringify(\n descriptor.name,\n )}];`;\n })\n .join('\\n');\n}\n\n/**\n * A Webpack loader that synchronously loads the WASM module. This makes it\n * possible to import the WASM module directly.\n *\n * @param source - The WASM module as `Uint8Array`.\n * @returns The WASM module as a JavaScript string.\n * @example\n * ```ts\n * import * as wasm from './program.wasm';\n *\n * // Do something with the WASM module...\n * ```\n */\n// Note: This function needs to be defined like this, so that Webpack can bind\n// `this` to the loader context, and TypeScript can infer the type of `this`.\nconst loader: LoaderDefinitionFunction = async function loader(\n source: unknown,\n) {\n assert(source instanceof Uint8Array, 'Expected source to be a Uint8Array.');\n\n const bytes = new Uint8Array(source);\n const wasmModule = await WebAssembly.compile(bytes);\n\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const exports = WebAssembly.Module.exports(wasmModule);\n const imports = WebAssembly.Module.imports(wasmModule).reduce<\n Record<string, string[]>\n >((target, descriptor) => {\n target[descriptor.module] ??= [];\n target[descriptor.module].push(descriptor.name);\n\n return target;\n }, {});\n\n // Add the WASM import as a dependency so that Webpack will watch it for\n // changes.\n const path = dirname(this.resourcePath);\n for (const name of Object.keys(imports)) {\n this.addDependency(resolve(path, name));\n }\n\n return `\n ${getImports(imports)}\n\n const bytes = new Uint8Array(${JSON.stringify(Array.from(source))});\n const module = new WebAssembly.Module(bytes);\n const instance = new WebAssembly.Instance(module, {\n ${getModuleImports(imports)}\n });\n\n const exports = instance.exports;\n ${getExports(exports)}\n `;\n};\n\nexport default loader;\n\n// By setting `raw` to `true`, we are telling Webpack to provide the source as a\n// `Uint8Array` instead of converting it to a string. This allows us to avoid\n// having to convert the source back to a `Uint8Array` in the loader.\nexport const raw = true;\n"],"names":["getImports","getModuleImports","getExports","raw","importMap","Object","entries","map","moduleName","exportNames","join","JSON","stringify","descriptors","descriptor","name","loader","source","assert","Uint8Array","bytes","wasmModule","WebAssembly","compile","exports","Module","imports","reduce","target","module","push","path","dirname","resourcePath","keys","addDependency","resolve","Array","from"],"mappings":"AAAA,wCAAwC;;;;;;;;;;;IAaxBA,UAAU;eAAVA;;IAkBAC,gBAAgB;eAAhBA;;IAiBAC,UAAU;eAAVA;;IAqEhB,OAAsB;eAAtB;;IAKaC,GAAG;eAAHA;;;uBAxHU;sBACU;AAU1B,SAASH,WAAWI,SAAmC;IAC5D,OAAOC,OAAOC,OAAO,CAACF,WACnBG,GAAG,CACF,CAAC,CAACC,YAAYC,YAAY,GACxB,CAAC,SAAS,EAAEA,YAAYC,IAAI,CAAC,MAAM,QAAQ,EAAEC,KAAKC,SAAS,CACzDJ,YACA,CAAC,CAAC,EAEPE,IAAI,CAAC;AACV;AASO,SAAST,iBAAiBG,SAAmC;IAClE,OAAOC,OAAOC,OAAO,CAACF,WACnBG,GAAG,CACF,CAAC,CAACC,YAAYC,YAAY,GACxB,CAAC,EAAEE,KAAKC,SAAS,CAACJ,YAAY,IAAI,EAAEC,YAAYC,IAAI,CAAC,MAAM,GAAG,CAAC,EAElEA,IAAI,CAAC;AACV;AAUO,SAASR,WAAWW,WAAiD;IAC1E,OAAOA,YACJN,GAAG,CAAC,CAACO;QACJ,IAAIA,WAAWC,IAAI,KAAK,WAAW;YACjC,OAAO,CAAC,uBAAuB,EAAEJ,KAAKC,SAAS,CAACE,WAAWC,IAAI,EAAE,EAAE,CAAC;QACtE;QAEA,OAAO,CAAC,aAAa,EAAED,WAAWC,IAAI,CAAC,WAAW,EAAEJ,KAAKC,SAAS,CAChEE,WAAWC,IAAI,EACf,EAAE,CAAC;IACP,GACCL,IAAI,CAAC;AACV;AAEA;;;;;;;;;;;;CAYC,GACD,8EAA8E;AAC9E,6EAA6E;AAC7E,MAAMM,SAAmC,eAAeA,OACtDC,MAAe;IAEfC,IAAAA,aAAM,EAACD,kBAAkBE,YAAY;IAErC,MAAMC,QAAQ,IAAID,WAAWF;IAC7B,MAAMI,aAAa,MAAMC,YAAYC,OAAO,CAACH;IAE7C,wDAAwD;IACxD,MAAMI,WAAUF,YAAYG,MAAM,CAACD,OAAO,CAACH;IAC3C,MAAMK,UAAUJ,YAAYG,MAAM,CAACC,OAAO,CAACL,YAAYM,MAAM,CAE3D,CAACC,QAAQd;YACTc,SAAOd;QAAPc,CAAAA,UAAAA,OAAM,CAACd,qBAAAA,WAAWe,MAAM,CAAC,KAAzBD,OAAM,CAACd,mBAAkB,GAAK,EAAE;QAChCc,MAAM,CAACd,WAAWe,MAAM,CAAC,CAACC,IAAI,CAAChB,WAAWC,IAAI;QAE9C,OAAOa;IACT,GAAG,CAAC;IAEJ,wEAAwE;IACxE,WAAW;IACX,MAAMG,OAAOC,IAAAA,aAAO,EAAC,IAAI,CAACC,YAAY;IACtC,KAAK,MAAMlB,QAAQV,OAAO6B,IAAI,CAACR,SAAU;QACvC,IAAI,CAACS,aAAa,CAACC,IAAAA,aAAO,EAACL,MAAMhB;IACnC;IAEA,OAAO,CAAC;IACN,EAAEf,WAAW0B,SAAS;;iCAEO,EAAEf,KAAKC,SAAS,CAACyB,MAAMC,IAAI,CAACrB,SAAS;;;MAGhE,EAAEhB,iBAAiByB,SAAS;;;;IAI9B,EAAExB,WAAWsB,UAAS;EACxB,CAAC;AACH;MAEA,WAAeR;AAKR,MAAMb,MAAM"}
@@ -22,10 +22,10 @@ _export(exports, {
22
22
  return SnapsBundleWarningsPlugin;
23
23
  }
24
24
  });
25
- const _snapsutils = require("@metamask/snaps-utils");
26
25
  const _utils = require("@metamask/utils");
27
26
  const _chalk = require("chalk");
28
27
  const _module = require("module");
28
+ const _webpack = require("webpack");
29
29
  const _eval = require("../commands/eval");
30
30
  const _utils1 = require("../utils");
31
31
  const _utils2 = require("./utils");
@@ -96,6 +96,7 @@ var _spinner = /*#__PURE__*/ new WeakMap(), /**
96
96
  * Get the error message for the given stats error.
97
97
  *
98
98
  * @param statsError - The stats error.
99
+ * @param color - The color to use for the error message.
99
100
  * @returns The error message.
100
101
  */ _getStatsErrorMessage = /*#__PURE__*/ new WeakSet();
101
102
  class SnapsStatsPlugin {
@@ -108,17 +109,22 @@ class SnapsStatsPlugin {
108
109
  if (!stats) {
109
110
  return;
110
111
  }
111
- const { modules, time, errors } = stats.toJson();
112
+ const { modules, time, errors, warnings } = stats.toJson();
112
113
  (0, _utils.assert)(modules, 'Modules must be defined in stats.');
113
114
  (0, _utils.assert)(time, 'Time must be defined in stats.');
114
115
  if (errors?.length) {
115
- const formattedErrors = errors.map(_class_private_method_get(this, _getStatsErrorMessage, getStatsErrorMessage).bind(this)).join('\n\n');
116
+ const formattedErrors = errors.map((statsError)=>_class_private_method_get(this, _getStatsErrorMessage, getStatsErrorMessage).call(this, statsError)).join('\n\n');
116
117
  (0, _utils1.error)(`Compiled ${modules.length} ${(0, _utils2.pluralize)(modules.length, 'file')} in ${time}ms with ${errors.length} ${(0, _utils2.pluralize)(errors.length, 'error')}.\n\n${formattedErrors}\n`, _class_private_field_get(this, _spinner));
117
118
  _class_private_field_get(this, _spinner)?.stop();
118
119
  process.exitCode = 1;
119
120
  return;
120
121
  }
121
- (0, _utils1.info)(`Compiled ${modules.length} ${(0, _utils2.pluralize)(modules.length, 'file')} in ${time}ms.`, _class_private_field_get(this, _spinner));
122
+ if (warnings?.length) {
123
+ const formattedWarnings = warnings.map((statsWarning)=>_class_private_method_get(this, _getStatsErrorMessage, getStatsErrorMessage).call(this, statsWarning, _chalk.yellow)).join('\n\n');
124
+ (0, _utils1.warn)(`Compiled ${modules.length} ${(0, _utils2.pluralize)(modules.length, 'file')} in ${time}ms with ${warnings.length} ${(0, _utils2.pluralize)(warnings.length, 'warning')}.\n\n${formattedWarnings}\n`, _class_private_field_get(this, _spinner));
125
+ } else {
126
+ (0, _utils1.info)(`Compiled ${modules.length} ${(0, _utils2.pluralize)(modules.length, 'file')} in ${time}ms.`, _class_private_field_get(this, _spinner));
127
+ }
122
128
  if (compiler.watchMode) {
123
129
  // The spinner may be restarted by the watch plugin, outside of the
124
130
  // `executeSteps` flow, so we stop it here just in case.
@@ -143,13 +149,13 @@ class SnapsStatsPlugin {
143
149
  _class_private_field_set(this, _spinner, spinner);
144
150
  }
145
151
  }
146
- function getStatsErrorMessage(statsError) {
152
+ function getStatsErrorMessage(statsError, color = _chalk.red) {
147
153
  const baseMessage = this.options.verbose ? (0, _utils1.getErrorMessage)(statsError) : statsError.message;
148
154
  const [first, ...rest] = baseMessage.split('\n');
149
155
  return [
150
- (0, _snapsutils.indent)((0, _chalk.red)(`• ${first}`), 2),
151
- ...rest.map((message)=>(0, _snapsutils.indent)((0, _chalk.red)(message), 4)),
152
- statsError.details && (0, _snapsutils.indent)((0, _chalk.dim)(statsError.details), 4)
156
+ color((0, _utils2.formatText)(`• ${first}`, 4, 2)),
157
+ ...rest.map((message)=>(0, _utils2.formatText)(color(message), 4)),
158
+ statsError.details && `\n${(0, _utils2.formatText)((0, _chalk.dim)(statsError.details), 6)}`
153
159
  ].filter(Boolean).join('\n');
154
160
  }
155
161
  var _spinner1 = /*#__PURE__*/ new WeakMap(), _safeEvaluate = /*#__PURE__*/ new WeakSet();
@@ -246,7 +252,7 @@ class SnapsBuiltInResolver {
246
252
  _class_private_field_set(this, _spinner2, spinner);
247
253
  }
248
254
  }
249
- var _spinner3 = /*#__PURE__*/ new WeakMap(), /**
255
+ var /**
250
256
  * Check if a built-in module is used, but not provided by Webpack's
251
257
  * `fallback` configuration.
252
258
  *
@@ -282,25 +288,18 @@ class SnapsBundleWarningsPlugin {
282
288
  constructor(options = {
283
289
  buffer: true,
284
290
  builtIns: true
285
- }, spinner){
291
+ }){
286
292
  _class_private_method_init(this, _checkBuiltIns);
287
293
  _class_private_method_init(this, _isProvidePlugin);
288
294
  _class_private_method_init(this, _checkBuffer);
289
295
  /**
290
- * The spinner to use for logging.
291
- */ _class_private_field_init(this, _spinner3, {
292
- writable: true,
293
- value: void 0
294
- });
295
- /**
296
296
  * The options for the plugin.
297
297
  */ _define_property(this, "options", void 0);
298
298
  this.options = options;
299
- _class_private_field_set(this, _spinner3, spinner);
300
299
  }
301
300
  }
302
301
  function checkBuiltIns(compiler) {
303
- compiler.hooks.afterCompile.tap(this.constructor.name, ()=>{
302
+ compiler.hooks.afterCompile.tap(this.constructor.name, (compilation)=>{
304
303
  if (!this.options.builtInResolver) {
305
304
  return;
306
305
  }
@@ -308,8 +307,10 @@ function checkBuiltIns(compiler) {
308
307
  if (unresolvedModules.size === 0) {
309
308
  return;
310
309
  }
311
- const formattedModules = new Array(...unresolvedModules).map((name)=>(0, _snapsutils.indent)(`• ${name}`, 2)).join('\n');
312
- (0, _utils1.warn)(`The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided.\n` + `The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must set ${(0, _chalk.yellow)(`polyfills`)} to ${(0, _chalk.yellow)(`true`)} or an object with the builtins to polyfill as the key and ${(0, _chalk.yellow)(`true`)} as the value.\n` + `To disable this warning, set ${(0, _chalk.yellow)('`stats.builtIns`')} to ${(0, _chalk.yellow)('`false`')} in your snap config file, or add the module to the ${(0, _chalk.yellow)('`stats.builtIns.ignore`')} array.\n\n${formattedModules}\n`, _class_private_field_get(this, _spinner3));
310
+ const formattedModules = new Array(...unresolvedModules).map((name)=>`• ${name}`).join('\n');
311
+ const webpackError = new _webpack.WebpackError(`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 ${(0, _chalk.bold)('`polyfills`')} to ${(0, _chalk.bold)('`true`')} or an object with the builtins to polyfill as the key and ${(0, _chalk.bold)('`true`')} as the value. To disable this warning, set ${(0, _chalk.bold)('`stats.builtIns`')} to ${(0, _chalk.bold)('`false`')} in your snap config file, or add the module to the ${(0, _chalk.bold)('`stats.builtIns.ignore`')} array.`);
312
+ webpackError.details = formattedModules;
313
+ compilation.warnings.push(webpackError);
313
314
  });
314
315
  }
315
316
  function isProvidePlugin(instance) {
@@ -332,7 +333,7 @@ function checkBuffer(compiler) {
332
333
  if (bufferAssets.length === 0) {
333
334
  return;
334
335
  }
335
- (0, _utils1.warn)(`The snap attempted to use the Node.js Buffer global, which is not supported in the MetaMask Snaps CLI by default.\n` + `To use the Buffer global, you must polyfill Buffer by setting ${(0, _chalk.yellow)(`buffer`)} to ${(0, _chalk.yellow)(`true`)} in the ${(0, _chalk.yellow)(`polyfills`)} config object in your snap config.\n` + `To disable this warning, set ${(0, _chalk.yellow)('`stats.buffer`')} to ${(0, _chalk.yellow)('`false`')} in your snap config file.`, _class_private_field_get(this, _spinner3));
336
+ compilation.warnings.push(new _webpack.WebpackError(`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 ${(0, _chalk.bold)('`buffer`')} to ${(0, _chalk.bold)('`true`')} in the ${(0, _chalk.bold)('`polyfills`')} config object in your snap config. To disable this warning, set ${(0, _chalk.bold)('`stats.buffer`')} to ${(0, _chalk.bold)('`false`')} in your snap config file.`));
336
337
  });
337
338
  });
338
339
  }