@metamask/snaps-cli 6.6.1 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/CHANGELOG.md +39 -1
  2. package/README.md +11 -244
  3. package/dist/builders.cjs +4 -98
  4. package/dist/builders.cjs.map +1 -1
  5. package/dist/builders.d.cts +28 -7
  6. package/dist/builders.d.cts.map +1 -1
  7. package/dist/builders.d.mts +28 -7
  8. package/dist/builders.d.mts.map +1 -1
  9. package/dist/builders.mjs +4 -97
  10. package/dist/builders.mjs.map +1 -1
  11. package/dist/cli.cjs +4 -9
  12. package/dist/cli.cjs.map +1 -1
  13. package/dist/cli.d.cts.map +1 -1
  14. package/dist/cli.d.mts.map +1 -1
  15. package/dist/cli.mjs +4 -16
  16. package/dist/cli.mjs.map +1 -1
  17. package/dist/commands/build/build.cjs +33 -7
  18. package/dist/commands/build/build.cjs.map +1 -1
  19. package/dist/commands/build/build.d.cts +2 -1
  20. package/dist/commands/build/build.d.cts.map +1 -1
  21. package/dist/commands/build/build.d.mts +2 -1
  22. package/dist/commands/build/build.d.mts.map +1 -1
  23. package/dist/commands/build/build.mjs +31 -5
  24. package/dist/commands/build/build.mjs.map +1 -1
  25. package/dist/commands/build/implementation.cjs +1 -1
  26. package/dist/commands/build/implementation.cjs.map +1 -1
  27. package/dist/commands/build/implementation.d.cts +3 -2
  28. package/dist/commands/build/implementation.d.cts.map +1 -1
  29. package/dist/commands/build/implementation.d.mts +3 -2
  30. package/dist/commands/build/implementation.d.mts.map +1 -1
  31. package/dist/commands/build/implementation.mjs +1 -1
  32. package/dist/commands/build/implementation.mjs.map +1 -1
  33. package/dist/commands/build/index.cjs +3 -14
  34. package/dist/commands/build/index.cjs.map +1 -1
  35. package/dist/commands/build/index.d.cts.map +1 -1
  36. package/dist/commands/build/index.d.mts.map +1 -1
  37. package/dist/commands/build/index.mjs +3 -14
  38. package/dist/commands/build/index.mjs.map +1 -1
  39. package/dist/commands/build/utils.cjs +25 -0
  40. package/dist/commands/build/utils.cjs.map +1 -0
  41. package/dist/commands/build/utils.d.cts +9 -0
  42. package/dist/commands/build/utils.d.cts.map +1 -0
  43. package/dist/commands/build/utils.d.mts +9 -0
  44. package/dist/commands/build/utils.d.mts.map +1 -0
  45. package/dist/commands/build/utils.mjs +21 -0
  46. package/dist/commands/build/utils.mjs.map +1 -0
  47. package/dist/commands/eval/__test__/webpack/bad/snap.config.cjs +0 -1
  48. package/dist/commands/eval/__test__/webpack/bad/snap.config.cjs.map +1 -1
  49. package/dist/commands/eval/__test__/webpack/bad/snap.config.d.cts.map +1 -1
  50. package/dist/commands/eval/__test__/webpack/bad/snap.config.d.mts.map +1 -1
  51. package/dist/commands/eval/__test__/webpack/bad/snap.config.mjs +0 -1
  52. package/dist/commands/eval/__test__/webpack/bad/snap.config.mjs.map +1 -1
  53. package/dist/commands/eval/__test__/webpack/good/snap.config.cjs +0 -1
  54. package/dist/commands/eval/__test__/webpack/good/snap.config.cjs.map +1 -1
  55. package/dist/commands/eval/__test__/webpack/good/snap.config.d.cts.map +1 -1
  56. package/dist/commands/eval/__test__/webpack/good/snap.config.d.mts.map +1 -1
  57. package/dist/commands/eval/__test__/webpack/good/snap.config.mjs +0 -1
  58. package/dist/commands/eval/__test__/webpack/good/snap.config.mjs.map +1 -1
  59. package/dist/commands/eval/__test__/webpack/snap.config.cjs +0 -1
  60. package/dist/commands/eval/__test__/webpack/snap.config.cjs.map +1 -1
  61. package/dist/commands/eval/__test__/webpack/snap.config.d.cts.map +1 -1
  62. package/dist/commands/eval/__test__/webpack/snap.config.d.mts.map +1 -1
  63. package/dist/commands/eval/__test__/webpack/snap.config.mjs +0 -1
  64. package/dist/commands/eval/__test__/webpack/snap.config.mjs.map +1 -1
  65. package/dist/commands/eval/eval.cjs +1 -1
  66. package/dist/commands/eval/eval.cjs.map +1 -1
  67. package/dist/commands/eval/eval.d.cts.map +1 -1
  68. package/dist/commands/eval/eval.d.mts.map +1 -1
  69. package/dist/commands/eval/eval.mjs +1 -1
  70. package/dist/commands/eval/eval.mjs.map +1 -1
  71. package/dist/commands/eval/index.cjs +1 -4
  72. package/dist/commands/eval/index.cjs.map +1 -1
  73. package/dist/commands/eval/index.d.cts.map +1 -1
  74. package/dist/commands/eval/index.d.mts.map +1 -1
  75. package/dist/commands/eval/index.mjs +1 -4
  76. package/dist/commands/eval/index.mjs.map +1 -1
  77. package/dist/commands/manifest/index.cjs +1 -4
  78. package/dist/commands/manifest/index.cjs.map +1 -1
  79. package/dist/commands/manifest/index.d.cts.map +1 -1
  80. package/dist/commands/manifest/index.d.mts.map +1 -1
  81. package/dist/commands/manifest/index.mjs +1 -4
  82. package/dist/commands/manifest/index.mjs.map +1 -1
  83. package/dist/commands/manifest/manifest.cjs +5 -6
  84. package/dist/commands/manifest/manifest.cjs.map +1 -1
  85. package/dist/commands/manifest/manifest.d.cts.map +1 -1
  86. package/dist/commands/manifest/manifest.d.mts.map +1 -1
  87. package/dist/commands/manifest/manifest.mjs +5 -6
  88. package/dist/commands/manifest/manifest.mjs.map +1 -1
  89. package/dist/commands/serve/index.cjs +2 -2
  90. package/dist/commands/serve/index.cjs.map +1 -1
  91. package/dist/commands/serve/index.d.cts.map +1 -1
  92. package/dist/commands/serve/index.d.mts.map +1 -1
  93. package/dist/commands/serve/index.mjs +2 -2
  94. package/dist/commands/serve/index.mjs.map +1 -1
  95. package/dist/commands/watch/implementation.cjs +2 -0
  96. package/dist/commands/watch/implementation.cjs.map +1 -1
  97. package/dist/commands/watch/implementation.d.cts +2 -2
  98. package/dist/commands/watch/implementation.d.cts.map +1 -1
  99. package/dist/commands/watch/implementation.d.mts +2 -2
  100. package/dist/commands/watch/implementation.d.mts.map +1 -1
  101. package/dist/commands/watch/implementation.mjs +2 -0
  102. package/dist/commands/watch/implementation.mjs.map +1 -1
  103. package/dist/commands/watch/index.cjs +2 -17
  104. package/dist/commands/watch/index.cjs.map +1 -1
  105. package/dist/commands/watch/index.d.cts.map +1 -1
  106. package/dist/commands/watch/index.d.mts.map +1 -1
  107. package/dist/commands/watch/index.mjs +2 -17
  108. package/dist/commands/watch/index.mjs.map +1 -1
  109. package/dist/commands/watch/watch.cjs +1 -1
  110. package/dist/commands/watch/watch.cjs.map +1 -1
  111. package/dist/commands/watch/watch.d.cts.map +1 -1
  112. package/dist/commands/watch/watch.d.mts.map +1 -1
  113. package/dist/commands/watch/watch.mjs +1 -1
  114. package/dist/commands/watch/watch.mjs.map +1 -1
  115. package/dist/config.cjs +11 -155
  116. package/dist/config.cjs.map +1 -1
  117. package/dist/config.d.cts +216 -314
  118. package/dist/config.d.cts.map +1 -1
  119. package/dist/config.d.mts +216 -314
  120. package/dist/config.d.mts.map +1 -1
  121. package/dist/config.mjs +13 -155
  122. package/dist/config.mjs.map +1 -1
  123. package/dist/main.cjs +0 -1
  124. package/dist/main.cjs.map +1 -1
  125. package/dist/main.mjs +0 -1
  126. package/dist/main.mjs.map +1 -1
  127. package/dist/utils/index.cjs +0 -1
  128. package/dist/utils/index.cjs.map +1 -1
  129. package/dist/utils/index.d.cts +0 -1
  130. package/dist/utils/index.d.cts.map +1 -1
  131. package/dist/utils/index.d.mts +0 -1
  132. package/dist/utils/index.d.mts.map +1 -1
  133. package/dist/utils/index.mjs +0 -1
  134. package/dist/utils/index.mjs.map +1 -1
  135. package/dist/utils/logging.cjs +16 -2
  136. package/dist/utils/logging.cjs.map +1 -1
  137. package/dist/utils/logging.d.cts +8 -1
  138. package/dist/utils/logging.d.cts.map +1 -1
  139. package/dist/utils/logging.d.mts +8 -1
  140. package/dist/utils/logging.d.mts.map +1 -1
  141. package/dist/utils/logging.mjs +15 -2
  142. package/dist/utils/logging.mjs.map +1 -1
  143. package/dist/utils/steps.cjs +11 -6
  144. package/dist/utils/steps.cjs.map +1 -1
  145. package/dist/utils/steps.d.cts +2 -2
  146. package/dist/utils/steps.d.cts.map +1 -1
  147. package/dist/utils/steps.d.mts +2 -2
  148. package/dist/utils/steps.d.mts.map +1 -1
  149. package/dist/utils/steps.mjs +11 -6
  150. package/dist/utils/steps.mjs.map +1 -1
  151. package/dist/webpack/compiler.cjs.map +1 -1
  152. package/dist/webpack/compiler.d.cts +2 -2
  153. package/dist/webpack/compiler.d.cts.map +1 -1
  154. package/dist/webpack/compiler.d.mts +2 -2
  155. package/dist/webpack/compiler.d.mts.map +1 -1
  156. package/dist/webpack/compiler.mjs.map +1 -1
  157. package/dist/webpack/config.cjs +8 -2
  158. package/dist/webpack/config.cjs.map +1 -1
  159. package/dist/webpack/config.d.cts +6 -2
  160. package/dist/webpack/config.d.cts.map +1 -1
  161. package/dist/webpack/config.d.mts +6 -2
  162. package/dist/webpack/config.d.mts.map +1 -1
  163. package/dist/webpack/config.mjs +8 -2
  164. package/dist/webpack/config.mjs.map +1 -1
  165. package/dist/webpack/loaders/function.cjs +7 -10
  166. package/dist/webpack/loaders/function.cjs.map +1 -1
  167. package/dist/webpack/loaders/function.d.cts +1 -0
  168. package/dist/webpack/loaders/function.d.cts.map +1 -1
  169. package/dist/webpack/loaders/function.d.mts +1 -0
  170. package/dist/webpack/loaders/function.d.mts.map +1 -1
  171. package/dist/webpack/loaders/function.mjs +6 -9
  172. package/dist/webpack/loaders/function.mjs.map +1 -1
  173. package/dist/webpack/loaders/index.cjs +1 -3
  174. package/dist/webpack/loaders/index.cjs.map +1 -1
  175. package/dist/webpack/loaders/index.d.cts +0 -1
  176. package/dist/webpack/loaders/index.d.cts.map +1 -1
  177. package/dist/webpack/loaders/index.d.mts +0 -1
  178. package/dist/webpack/loaders/index.d.mts.map +1 -1
  179. package/dist/webpack/loaders/index.mjs +0 -1
  180. package/dist/webpack/loaders/index.mjs.map +1 -1
  181. package/dist/webpack/loaders/wasm.cjs +0 -2
  182. package/dist/webpack/loaders/wasm.cjs.map +1 -1
  183. package/dist/webpack/loaders/wasm.d.cts.map +1 -1
  184. package/dist/webpack/loaders/wasm.d.mts.map +1 -1
  185. package/dist/webpack/loaders/wasm.mjs +0 -2
  186. package/dist/webpack/loaders/wasm.mjs.map +1 -1
  187. package/dist/webpack/plugins.cjs +15 -20
  188. package/dist/webpack/plugins.cjs.map +1 -1
  189. package/dist/webpack/plugins.d.cts +13 -3
  190. package/dist/webpack/plugins.d.cts.map +1 -1
  191. package/dist/webpack/plugins.d.mts +13 -3
  192. package/dist/webpack/plugins.d.mts.map +1 -1
  193. package/dist/webpack/plugins.mjs +4 -9
  194. package/dist/webpack/plugins.mjs.map +1 -1
  195. package/dist/webpack/utils.cjs +5 -21
  196. package/dist/webpack/utils.cjs.map +1 -1
  197. package/dist/webpack/utils.d.cts +6 -36
  198. package/dist/webpack/utils.d.cts.map +1 -1
  199. package/dist/webpack/utils.d.mts +6 -36
  200. package/dist/webpack/utils.d.mts.map +1 -1
  201. package/dist/webpack/utils.mjs +4 -18
  202. package/dist/webpack/utils.mjs.map +1 -1
  203. package/package.json +14 -38
  204. package/dist/commands/eval/__test__/browserify/bad/snap.config.cjs +0 -10
  205. package/dist/commands/eval/__test__/browserify/bad/snap.config.cjs.map +0 -1
  206. package/dist/commands/eval/__test__/browserify/bad/snap.config.d.cts +0 -4
  207. package/dist/commands/eval/__test__/browserify/bad/snap.config.d.cts.map +0 -1
  208. package/dist/commands/eval/__test__/browserify/bad/snap.config.d.mts +0 -4
  209. package/dist/commands/eval/__test__/browserify/bad/snap.config.d.mts.map +0 -1
  210. package/dist/commands/eval/__test__/browserify/bad/snap.config.mjs +0 -8
  211. package/dist/commands/eval/__test__/browserify/bad/snap.config.mjs.map +0 -1
  212. package/dist/commands/eval/__test__/browserify/good/snap.config.cjs +0 -10
  213. package/dist/commands/eval/__test__/browserify/good/snap.config.cjs.map +0 -1
  214. package/dist/commands/eval/__test__/browserify/good/snap.config.d.cts +0 -4
  215. package/dist/commands/eval/__test__/browserify/good/snap.config.d.cts.map +0 -1
  216. package/dist/commands/eval/__test__/browserify/good/snap.config.d.mts +0 -4
  217. package/dist/commands/eval/__test__/browserify/good/snap.config.d.mts.map +0 -1
  218. package/dist/commands/eval/__test__/browserify/good/snap.config.mjs +0 -8
  219. package/dist/commands/eval/__test__/browserify/good/snap.config.mjs.map +0 -1
  220. package/dist/utils/legacy.cjs +0 -53
  221. package/dist/utils/legacy.cjs.map +0 -1
  222. package/dist/utils/legacy.d.cts +0 -28
  223. package/dist/utils/legacy.d.cts.map +0 -1
  224. package/dist/utils/legacy.d.mts +0 -28
  225. package/dist/utils/legacy.d.mts.map +0 -1
  226. package/dist/utils/legacy.mjs +0 -47
  227. package/dist/utils/legacy.mjs.map +0 -1
  228. package/dist/webpack/loaders/browserify.cjs +0 -84
  229. package/dist/webpack/loaders/browserify.cjs.map +0 -1
  230. package/dist/webpack/loaders/browserify.d.cts +0 -18
  231. package/dist/webpack/loaders/browserify.d.cts.map +0 -1
  232. package/dist/webpack/loaders/browserify.d.mts +0 -18
  233. package/dist/webpack/loaders/browserify.d.mts.map +0 -1
  234. package/dist/webpack/loaders/browserify.mjs +0 -88
  235. package/dist/webpack/loaders/browserify.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.mjs","sourceRoot":"","sources":["../../src/webpack/plugins.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;;;AAEhE,OAAO,EAAE,SAAS,EAAE,eAAe;;;AAYnC,OAAO,EAAE,QAAQ,EAAE,mCAAyB;AAC5C,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,IAAI,EAAE,2BAAiB;AAC9D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,oBAAgB;AAShD;;;GAGG;AACH,MAAM,OAAO,gBAAgB;IAW3B,YACE,UAAmC;QACjC,OAAO,EAAE,KAAK;KACf,EACD,OAAa;;QATf;;WAEG;QACM,4CAAe;QAQtB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,uBAAA,IAAI,6BAAY,OAAO,MAAA,CAAC;IAC1B,CAAC;IAED;;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AAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;iBACxC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;iBACxC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;YAE5D,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC9B,OAAO;YACT,CAAC;YAED,WAAW,CAAC,QAAQ,CAAC,IAAI,CACvB,IAAI,YAAY,CACd,mLAAmL,IAAI,CACrL,UAAU,CACX,OAAO,IAAI,CAAC,QAAQ,CAAC,WAAW,IAAI,CACnC,aAAa,CACd,oEAAoE,IAAI,CACvE,gBAAgB,CACjB,OAAO,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACpD,CACF,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { assert, hasProperty, isObject } from '@metamask/utils';\nimport { bold, dim, red, yellow } from 'chalk';\nimport { isBuiltin } from 'module';\nimport type { Ora } from 'ora';\nimport type {\n Compiler,\n ProvidePlugin,\n ResolvePluginInstance,\n Resolver,\n StatsError,\n WebpackPluginInstance,\n} from 'webpack';\nimport { WebpackError } from 'webpack';\n\nimport { evaluate } from '../commands/eval';\nimport { error, getErrorMessage, info, warn } from '../utils';\nimport { formatText, pluralize } from './utils';\n\nexport type SnapsStatsPluginOptions = {\n /**\n * Whether to log the verbose stats.\n */\n verbose?: boolean;\n};\n\n/**\n * A plugin that logs the stats after compilation. This is useful for logging\n * the number of files compiled, and the time taken to compile them.\n */\nexport class SnapsStatsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsStatsPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsStatsPluginOptions = {\n verbose: false,\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.afterDone.tap(this.constructor.name, (stats) => {\n if (!stats) {\n return;\n }\n\n const { modules, time, errors, warnings } = stats.toJson();\n\n assert(modules, 'Modules must be defined in stats.');\n assert(time, 'Time must be defined in stats.');\n\n if (errors?.length) {\n const formattedErrors = errors\n .map((statsError) => this.#getStatsErrorMessage(statsError))\n .join('\\n\\n');\n\n error(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${errors.length} ${pluralize(\n errors.length,\n 'error',\n )}.\\n\\n${formattedErrors}\\n`,\n this.#spinner,\n );\n\n this.#spinner?.stop();\n\n process.exitCode = 1;\n return;\n }\n\n if (warnings?.length) {\n const formattedWarnings = warnings\n .map((statsWarning) =>\n this.#getStatsErrorMessage(statsWarning, yellow),\n )\n .join('\\n\\n');\n\n warn(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${warnings.length} ${pluralize(\n warnings.length,\n 'warning',\n )}.\\n\\n${formattedWarnings}\\n`,\n this.#spinner,\n );\n } else {\n info(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms.`,\n this.#spinner,\n );\n }\n\n if (compiler.watchMode) {\n // The spinner may be restarted by the watch plugin, outside of the\n // `executeSteps` flow, so we stop it here just in case.\n this.#spinner?.succeed('Done!');\n }\n });\n }\n\n /**\n * Get the error message for the given stats error.\n *\n * @param statsError - The stats error.\n * @param color - The color to use for the error message.\n * @returns The error message.\n */\n #getStatsErrorMessage(statsError: StatsError, color = red) {\n const baseMessage = this.options.verbose\n ? getErrorMessage(statsError)\n : statsError.message;\n\n const [first, ...rest] = baseMessage.split('\\n');\n\n return [\n color(formatText(`• ${first}`, 4, 2)),\n ...rest.map((message) => formatText(color(message), 4)),\n statsError.details && `\\n${formatText(dim(statsError.details), 6)}`,\n ]\n .filter(Boolean)\n .join('\\n');\n }\n}\n\n/**\n * The options for the {@link SnapsWatchPlugin}.\n */\nexport type SnapsWatchPluginOptions = {\n /**\n * The bundle path. This is the file that will be evaluated, if the `evaluate`\n * option is set.\n */\n bundle?: string;\n\n /**\n * Whether to evaluate the bundle. This only applies if the `bundle` option is\n * set.\n */\n evaluate?: boolean;\n\n /**\n * The extra files to watch.\n */\n files?: string[];\n};\n\n/**\n * A plugin that adds extra files to watch. This is useful for watching files\n * that are not imported by the entry point, such as the `snap.manifest.json`\n * file.\n */\nexport class SnapsWatchPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsWatchPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(options: SnapsWatchPluginOptions, spinner?: Ora) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.invalid.tap(this.constructor.name, (file) => {\n this.#spinner?.start();\n info(`Changes detected in ${yellow(file)}, recompiling.`, this.#spinner);\n });\n\n compiler.hooks.afterEmit.tapPromise(\n this.constructor.name,\n async ({ fileDependencies }) => {\n this.options.files?.forEach(\n fileDependencies.add.bind(fileDependencies),\n );\n\n if (this.options.bundle && this.options.evaluate) {\n await this.#safeEvaluate(this.options.bundle);\n }\n },\n );\n }\n\n /**\n * Safely evaluate the bundle at the given path. If an error occurs, it will\n * be logged to the console, rather than throwing an error.\n *\n * This function should never throw an error.\n *\n * @param bundlePath - The path to the bundle.\n */\n async #safeEvaluate(bundlePath: string) {\n try {\n await evaluate(bundlePath);\n info(`Snap bundle evaluated successfully.`, this.#spinner);\n } catch (evaluateError) {\n error(evaluateError.message, this.#spinner);\n }\n }\n}\n\n/**\n * The options for the {@link SnapsBuiltInResolver}.\n */\nexport type SnapsBuiltInResolverOptions = {\n /**\n * The built-in modules to ignore.\n */\n ignore?: string[];\n};\n\n/**\n * A plugin that logs a message when a built-in module is not resolved. The\n * MetaMask Snaps CLI does not support built-in modules by default, and this\n * plugin is used to warn the user when they try to import a built-in module,\n * when no fallback is configured.\n */\nexport class SnapsBuiltInResolver implements ResolvePluginInstance {\n /**\n * The built-in modules that have been imported, but not resolved.\n */\n readonly unresolvedModules = new Set<string>();\n\n /**\n * The name of the resolver hook to tap into.\n */\n readonly #source = 'described-resolve';\n\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBuiltInResolverOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsBuiltInResolverOptions = {\n ignore: [],\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack resolver.\n *\n * @param resolver - The Webpack resolver.\n */\n apply(resolver: Resolver) {\n resolver\n .getHook(this.#source)\n .tapAsync(\n this.constructor.name,\n ({ module: isModule, request }, _, callback) => {\n if (!isModule || !request) {\n return callback();\n }\n\n const baseRequest = request.split('/')[0];\n if (\n isBuiltin(baseRequest) &&\n !this.options.ignore?.includes(baseRequest)\n ) {\n const fallback = resolver.options.fallback.find(\n ({ name }) => name === baseRequest,\n );\n\n if (fallback && !fallback.alias) {\n this.unresolvedModules.add(baseRequest);\n }\n }\n\n return callback();\n },\n );\n }\n}\n\n/**\n * The options for the {@link SnapsBundleWarningsPlugin}.\n */\nexport type SnapsBundleWarningsPluginOptions = {\n /**\n * The {@link SnapsBuiltInResolver} instance to use for detecting built-in\n * modules.\n */\n builtInResolver?: SnapsBuiltInResolver | false;\n\n /**\n * Whether to show warnings if built-in modules are used, but not provided by\n * Webpack's `fallback` configuration.\n */\n builtIns?: boolean;\n\n /**\n * Whether to show warnings if the `Buffer` global is used, but not provided\n * by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n};\n\n/**\n * A plugin that logs a message when:\n *\n * - A built-in module is not resolved. The MetaMask Snaps CLI does not support\n * built-in modules by default, and this plugin is used to warn the user when\n * they try to import a built-in module, when no fallback is configured.\n * - A snap uses the `Buffer` global. The MetaMask Snaps CLI does not support\n * the `Buffer` global by default, and this plugin is used to warn the user when\n * they try to use the `Buffer` global.\n *\n * We use both a resolver and a plugin, because the resolver is used to detect\n * when a built-in module is imported, and the plugin is used to log a single\n * message when the compilation is complete. We can't do everything in a single\n * plugin, because the resolver doesn't have access to the compilation, and the\n * plugin doesn't have access to the resolver.\n */\n\nexport class SnapsBundleWarningsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBundleWarningsPluginOptions;\n\n constructor(\n options: SnapsBundleWarningsPluginOptions = {\n buffer: true,\n builtIns: true,\n },\n ) {\n this.options = options;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n if (this.options.builtIns) {\n this.#checkBuiltIns(compiler);\n }\n\n if (this.options.buffer) {\n this.#checkBuffer(compiler);\n }\n }\n\n /**\n * Check if a built-in module is used, but not provided by Webpack's\n * `fallback` configuration.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuiltIns(compiler: Compiler) {\n compiler.hooks.afterCompile.tap(this.constructor.name, (compilation) => {\n if (!this.options.builtInResolver) {\n return;\n }\n\n const { unresolvedModules } = this.options.builtInResolver;\n if (unresolvedModules.size === 0) {\n return;\n }\n\n const formattedModules = new Array(...unresolvedModules)\n .map((name) => `• ${name}`)\n .join('\\n');\n\n const webpackError = new WebpackError(\n `The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided. The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must set ${bold(\n '`polyfills`',\n )} to ${bold(\n '`true`',\n )} or an object with the builtins to polyfill as the key and ${bold(\n '`true`',\n )} as the value. To disable this warning, set ${bold(\n '`stats.builtIns`',\n )} to ${bold(\n '`false`',\n )} in your snap config file, or add the module to the ${bold(\n '`stats.builtIns.ignore`',\n )} array.`,\n );\n\n webpackError.details = formattedModules;\n compilation.warnings.push(webpackError);\n });\n }\n\n /**\n * Check if the given instance is a `ProvidePlugin`. This is not guaranteed to\n * be accurate, but it's good enough for our purposes. If we were to use\n * `instanceof` instead, it might not work if multiple versions of Webpack are\n * installed.\n *\n * @param instance - The instance to check.\n * @returns Whether the instance is a `ProvidePlugin`, i.e., whether it's an\n * object with the name `ProvidePlugin` and a `definitions` property.\n */\n #isProvidePlugin(instance: unknown): instance is ProvidePlugin {\n return (\n isObject(instance) &&\n instance.constructor.name === 'ProvidePlugin' &&\n hasProperty(instance, 'definitions')\n );\n }\n\n /**\n * Check if the `Buffer` global is used, but not provided by Webpack's\n * `DefinePlugin`.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuffer(compiler: Compiler) {\n const plugin = compiler.options.plugins?.find((instance) =>\n this.#isProvidePlugin(instance),\n ) as ProvidePlugin | undefined;\n\n // If the `ProvidePlugin` is configured to provide `Buffer`, then we don't\n // need to warn the user.\n if (plugin) {\n const { definitions } = plugin;\n if (definitions.Buffer) {\n return;\n }\n }\n\n compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {\n compilation.hooks.afterProcessAssets.tap(\n this.constructor.name,\n (assets) => {\n // Check if assets use `Buffer`.\n const bufferAssets = Object.entries(assets)\n .filter(([name]) => name.endsWith('.js'))\n .filter(([, asset]) => asset.source().includes('Buffer'));\n\n if (bufferAssets.length === 0) {\n return;\n }\n\n compilation.warnings.push(\n new WebpackError(\n `The snap attempted to use the Node.js Buffer global, which is not supported in the MetaMask Snaps CLI by default. To use the Buffer global, you must polyfill Buffer by setting ${bold(\n '`buffer`',\n )} to ${bold('`true`')} in the ${bold(\n '`polyfills`',\n )} config object in your snap config. To disable this warning, set ${bold(\n '`stats.buffer`',\n )} to ${bold('`false`')} in your snap config file.`,\n ),\n );\n },\n );\n });\n }\n}\n"]}
1
+ {"version":3,"file":"plugins.m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B,IAAI,EAAkB,QAAQ,CAAC,CACH,CAAC;IAE/B,0EAA0E;IAC1E,yBAAyB;IACzB,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;QAC/B,IAAI,WAAW,CAAC,MAAM,EAAE,CAAC;YACvB,OAAO;QACT,CAAC;IACH,CAAC;IAED,QAAQ,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE;QACpE,WAAW,CAAC,KAAK,CAAC,kBAAkB,CAAC,GAAG,CACtC,IAAI,CAAC,WAAW,CAAC,IAAI,EACrB,CAAC,MAAM,EAAE,EAAE;YACT,gCAAgC;YAChC,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;iBACxC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;iBACxC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;YAE5D,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC9B,OAAO;YACT,CAAC;YAED,WAAW,CAAC,QAAQ,CAAC,IAAI,CACvB,IAAI,YAAY,CACd,mLAAmL,IAAI,CACrL,UAAU,CACX,OAAO,IAAI,CAAC,QAAQ,CAAC,WAAW,IAAI,CACnC,aAAa,CACd,oEAAoE,IAAI,CACvE,gBAAgB,CACjB,OAAO,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACpD,CACF,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { assert, hasProperty, isObject } from '@metamask/utils';\nimport { bold, dim, red, yellow } from 'chalk';\nimport { isBuiltin } from 'module';\nimport type { Ora } from 'ora';\nimport type {\n Compiler,\n ProvidePlugin,\n Resolver,\n StatsError,\n WebpackPluginInstance,\n} from 'webpack';\nimport { WebpackError } from 'webpack';\n\nimport { formatText, pluralize } from './utils';\nimport { evaluate } from '../commands/eval';\nimport { error, getErrorMessage, info, warn } from '../utils';\n\nexport type SnapsStatsPluginOptions = {\n /**\n * Whether to log the verbose stats.\n */\n verbose?: boolean;\n};\n\n/**\n * A plugin that logs the stats after compilation. This is useful for logging\n * the number of files compiled, and the time taken to compile them.\n */\nexport class SnapsStatsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsStatsPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(\n options: SnapsStatsPluginOptions = {\n verbose: false,\n },\n spinner?: Ora,\n ) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.afterDone.tap(this.constructor.name, (stats) => {\n if (!stats) {\n return;\n }\n\n const { modules, time, errors, warnings } = stats.toJson();\n\n assert(modules, 'Modules must be defined in stats.');\n assert(time, 'Time must be defined in stats.');\n\n if (errors?.length) {\n const formattedErrors = errors\n .map((statsError) => this.#getStatsErrorMessage(statsError))\n .join('\\n\\n');\n\n error(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${errors.length} ${pluralize(\n errors.length,\n 'error',\n )}.\\n\\n${formattedErrors}\\n`,\n this.#spinner,\n );\n\n this.#spinner?.stop();\n\n process.exitCode = 1;\n return;\n }\n\n if (warnings?.length) {\n const formattedWarnings = warnings\n .map((statsWarning) =>\n this.#getStatsErrorMessage(statsWarning, yellow),\n )\n .join('\\n\\n');\n\n warn(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms with ${warnings.length} ${pluralize(\n warnings.length,\n 'warning',\n )}.\\n\\n${formattedWarnings}\\n`,\n this.#spinner,\n );\n } else {\n info(\n `Compiled ${modules.length} ${pluralize(\n modules.length,\n 'file',\n )} in ${time}ms.`,\n this.#spinner,\n );\n }\n\n if (compiler.watchMode) {\n // The spinner may be restarted by the watch plugin, outside of the\n // `executeSteps` flow, so we stop it here just in case.\n this.#spinner?.succeed('Done!');\n }\n });\n }\n\n /**\n * Get the error message for the given stats error.\n *\n * @param statsError - The stats error.\n * @param color - The color to use for the error message.\n * @returns The error message.\n */\n #getStatsErrorMessage(statsError: StatsError, color = red) {\n const baseMessage = this.options.verbose\n ? getErrorMessage(statsError)\n : statsError.message;\n\n const [first, ...rest] = baseMessage.split('\\n');\n\n return [\n color(formatText(`• ${first}`, 4, 2)),\n ...rest.map((message) => formatText(color(message), 4)),\n statsError.details && `\\n${formatText(dim(statsError.details), 6)}`,\n ]\n .filter(Boolean)\n .join('\\n');\n }\n}\n\n/**\n * The options for the {@link SnapsWatchPlugin}.\n */\nexport type SnapsWatchPluginOptions = {\n /**\n * The bundle path. This is the file that will be evaluated, if the `evaluate`\n * option is set.\n */\n bundle?: string;\n\n /**\n * Whether to evaluate the bundle. This only applies if the `bundle` option is\n * set.\n */\n evaluate?: boolean;\n\n /**\n * The extra files to watch.\n */\n files?: string[];\n};\n\n/**\n * A plugin that adds extra files to watch. This is useful for watching files\n * that are not imported by the entry point, such as the `snap.manifest.json`\n * file.\n */\nexport class SnapsWatchPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsWatchPluginOptions;\n\n /**\n * The spinner to use for logging.\n */\n readonly #spinner?: Ora;\n\n constructor(options: SnapsWatchPluginOptions, spinner?: Ora) {\n this.options = options;\n this.#spinner = spinner;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n compiler.hooks.invalid.tap(this.constructor.name, (file) => {\n this.#spinner?.start();\n info(`Changes detected in ${yellow(file)}, recompiling.`, this.#spinner);\n });\n\n compiler.hooks.afterEmit.tapPromise(\n this.constructor.name,\n async ({ fileDependencies }) => {\n this.options.files?.forEach(\n fileDependencies.add.bind(fileDependencies),\n );\n\n if (this.options.bundle && this.options.evaluate) {\n await this.#safeEvaluate(this.options.bundle);\n }\n },\n );\n }\n\n /**\n * Safely evaluate the bundle at the given path. If an error occurs, it will\n * be logged to the console, rather than throwing an error.\n *\n * This function should never throw an error.\n *\n * @param bundlePath - The path to the bundle.\n */\n async #safeEvaluate(bundlePath: string) {\n try {\n await evaluate(bundlePath);\n info(`Snap bundle evaluated successfully.`, this.#spinner);\n } catch (evaluateError) {\n error(evaluateError.message, this.#spinner);\n }\n }\n}\n\n/**\n * The options for the {@link SnapsBuiltInResolver}.\n */\nexport type SnapsBuiltInResolverOptions = {\n /**\n * The built-in modules to ignore.\n */\n ignore?: string[];\n};\n\n/**\n * A Webpack resolve plugin.\n *\n * Copied from Webpack's own types, because the `ResolvePluginInstance` type is\n * a union, and can't be used as a type for a class.\n */\ntype ResolvePlugin = {\n apply: (resolver: Resolver) => void;\n};\n\n/**\n * A plugin that logs a message when a built-in module is not resolved. The\n * MetaMask Snaps CLI does not support built-in modules by default, and this\n * plugin is used to warn the user when they try to import a built-in module,\n * when no fallback is configured.\n */\nexport class SnapsBuiltInResolver implements ResolvePlugin {\n /**\n * The built-in modules that have been imported, but not resolved.\n */\n readonly unresolvedModules = new Set<string>();\n\n /**\n * The name of the resolver hook to tap into.\n */\n readonly #source = 'described-resolve';\n\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBuiltInResolverOptions;\n\n constructor(\n options: SnapsBuiltInResolverOptions = {\n ignore: [],\n },\n ) {\n this.options = options;\n }\n\n /**\n * Apply the plugin to the Webpack resolver.\n *\n * @param resolver - The Webpack resolver.\n */\n apply(resolver: Resolver) {\n resolver\n .getHook(this.#source)\n .tapAsync(\n this.constructor.name,\n ({ module: isModule, request }, _, callback) => {\n if (!isModule || !request) {\n return callback();\n }\n\n const baseRequest = request.split('/')[0];\n if (\n isBuiltin(baseRequest) &&\n !this.options.ignore?.includes(baseRequest)\n ) {\n const fallback = resolver.options.fallback.find(\n ({ name }) => name === baseRequest,\n );\n\n if (fallback && !fallback.alias) {\n this.unresolvedModules.add(baseRequest);\n }\n }\n\n return callback();\n },\n );\n }\n}\n\n/**\n * The options for the {@link SnapsBundleWarningsPlugin}.\n */\nexport type SnapsBundleWarningsPluginOptions = {\n /**\n * The {@link SnapsBuiltInResolver} instance to use for detecting built-in\n * modules.\n */\n builtInResolver?: SnapsBuiltInResolver | false;\n\n /**\n * Whether to show warnings if built-in modules are used, but not provided by\n * Webpack's `fallback` configuration.\n */\n builtIns?: boolean;\n\n /**\n * Whether to show warnings if the `Buffer` global is used, but not provided\n * by Webpack's `DefinePlugin`.\n */\n buffer?: boolean;\n};\n\n/**\n * A plugin that logs a message when:\n *\n * - A built-in module is not resolved. The MetaMask Snaps CLI does not support\n * built-in modules by default, and this plugin is used to warn the user when\n * they try to import a built-in module, when no fallback is configured.\n * - A snap uses the `Buffer` global. The MetaMask Snaps CLI does not support\n * the `Buffer` global by default, and this plugin is used to warn the user when\n * they try to use the `Buffer` global.\n *\n * We use both a resolver and a plugin, because the resolver is used to detect\n * when a built-in module is imported, and the plugin is used to log a single\n * message when the compilation is complete. We can't do everything in a single\n * plugin, because the resolver doesn't have access to the compilation, and the\n * plugin doesn't have access to the resolver.\n */\n\nexport class SnapsBundleWarningsPlugin implements WebpackPluginInstance {\n /**\n * The options for the plugin.\n */\n readonly options: SnapsBundleWarningsPluginOptions;\n\n constructor(\n options: SnapsBundleWarningsPluginOptions = {\n buffer: true,\n builtIns: true,\n },\n ) {\n this.options = options;\n }\n\n /**\n * Apply the plugin to the Webpack compiler.\n *\n * @param compiler - The Webpack compiler.\n */\n apply(compiler: Compiler) {\n if (this.options.builtIns) {\n this.#checkBuiltIns(compiler);\n }\n\n if (this.options.buffer) {\n this.#checkBuffer(compiler);\n }\n }\n\n /**\n * Check if a built-in module is used, but not provided by Webpack's\n * `fallback` configuration.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuiltIns(compiler: Compiler) {\n compiler.hooks.afterCompile.tap(this.constructor.name, (compilation) => {\n if (!this.options.builtInResolver) {\n return;\n }\n\n const { unresolvedModules } = this.options.builtInResolver;\n if (unresolvedModules.size === 0) {\n return;\n }\n\n const formattedModules = new Array(...unresolvedModules)\n .map((name) => `• ${name}`)\n .join('\\n');\n\n const webpackError = new WebpackError(\n `The snap attempted to use one or more Node.js builtins, but no browser fallback has been provided. The MetaMask Snaps CLI does not support Node.js builtins by default. If you want to use this module, you must set ${bold(\n '`polyfills`',\n )} to ${bold(\n '`true`',\n )} or an object with the builtins to polyfill as the key and ${bold(\n '`true`',\n )} as the value. To disable this warning, set ${bold(\n '`stats.builtIns`',\n )} to ${bold(\n '`false`',\n )} in your snap config file, or add the module to the ${bold(\n '`stats.builtIns.ignore`',\n )} array.`,\n );\n\n webpackError.details = formattedModules;\n compilation.warnings.push(webpackError);\n });\n }\n\n /**\n * Check if the given instance is a `ProvidePlugin`. This is not guaranteed to\n * be accurate, but it's good enough for our purposes. If we were to use\n * `instanceof` instead, it might not work if multiple versions of Webpack are\n * installed.\n *\n * @param instance - The instance to check.\n * @returns Whether the instance is a `ProvidePlugin`, i.e., whether it's an\n * object with the name `ProvidePlugin` and a `definitions` property.\n */\n #isProvidePlugin(instance: unknown): instance is ProvidePlugin {\n return (\n isObject(instance) &&\n instance.constructor.name === 'ProvidePlugin' &&\n hasProperty(instance, 'definitions')\n );\n }\n\n /**\n * Check if the `Buffer` global is used, but not provided by Webpack's\n * `DefinePlugin`.\n *\n * @param compiler - The Webpack compiler.\n */\n #checkBuffer(compiler: Compiler) {\n const plugin = compiler.options.plugins?.find((instance) =>\n this.#isProvidePlugin(instance),\n ) as ProvidePlugin | undefined;\n\n // If the `ProvidePlugin` is configured to provide `Buffer`, then we don't\n // need to warn the user.\n if (plugin) {\n const { definitions } = plugin;\n if (definitions.Buffer) {\n return;\n }\n }\n\n compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {\n compilation.hooks.afterProcessAssets.tap(\n this.constructor.name,\n (assets) => {\n // Check if assets use `Buffer`.\n const bufferAssets = Object.entries(assets)\n .filter(([name]) => name.endsWith('.js'))\n .filter(([, asset]) => asset.source().includes('Buffer'));\n\n if (bufferAssets.length === 0) {\n return;\n }\n\n compilation.warnings.push(\n new WebpackError(\n `The snap attempted to use the Node.js Buffer global, which is not supported in the MetaMask Snaps CLI by default. To use the Buffer global, you must polyfill Buffer by setting ${bold(\n '`buffer`',\n )} to ${bold('`true`')} in the ${bold(\n '`polyfills`',\n )} config object in your snap config. To disable this warning, set ${bold(\n '`stats.buffer`',\n )} to ${bold('`false`')} in your snap config file.`,\n ),\n );\n },\n );\n });\n }\n}\n"]}
@@ -10,10 +10,7 @@ const fs_1 = require("fs");
10
10
  const module_1 = require("module");
11
11
  const path_1 = require("path");
12
12
  const strip_ansi_1 = __importDefault(require("strip-ansi/index.js"));
13
- const loaders_1 = require("./loaders/index.cjs");
14
- exports.BROWSERSLIST_FILE = (0, path_1.resolve)((0, path_1.dirname)(
15
- // eslint-disable-next-line n/no-extraneous-require
16
- require.resolve('@metamask/snaps-cli/package.json')), '.browserslistrc');
13
+ exports.BROWSERSLIST_FILE = (0, path_1.resolve)((0, path_1.dirname)(require.resolve('@metamask/snaps-cli/package.json')), '.browserslistrc');
17
14
  exports.WEBPACK_FALLBACKS = {
18
15
  assert: require.resolve('assert/'),
19
16
  buffer: require.resolve('buffer/'),
@@ -50,28 +47,15 @@ exports.WEBPACK_FALLBACKS = {
50
47
  * Get the default loader for JavaScript and TypeScript files, based on the
51
48
  * config object.
52
49
  *
53
- * - If the `legacy` option is set, we use the custom `browserify` loader. This
54
- * uses the legacy Browserify config to transpile the code.
55
- * - Otherwise, we use the `swc-loader`. This is a Webpack loader that uses the
56
- * `SWC` compiler, which is a much faster alternative to Babel and TypeScript's
57
- * own compiler.
50
+ * We use the `swc-loader`, which is a Webpack loader that uses the `SWC`
51
+ * compiler, a much faster alternative to Babel and TypeScript's own compiler.
58
52
  *
59
53
  * @param config - The processed snap Webpack config.
60
- * @param config.legacy - The legacy config object, if any.
61
54
  * @param config.sourceMap - Whether to generate source maps.
62
55
  * @see https://swc.rs/docs/usage/swc-loader
63
56
  * @returns The default loader.
64
57
  */
65
- async function getDefaultLoader({ legacy, sourceMap, }) {
66
- if (legacy) {
67
- /**
68
- * If the snap uses the legacy config, we use the custom `browserify`
69
- * loader. This uses the legacy Browserify config to transpile the code.
70
- * This is necessary for backwards compatibility with the
71
- * `bundlerCustomizer` function.
72
- */
73
- return (0, loaders_1.getFunctionLoader)(loaders_1.browserify, legacy);
74
- }
58
+ async function getDefaultLoader({ sourceMap }) {
75
59
  const targets = await getBrowserslistTargets();
76
60
  return {
77
61
  /**
@@ -179,7 +163,7 @@ function getDevTool(sourceMap) {
179
163
  if (sourceMap === 'inline') {
180
164
  return 'inline-source-map';
181
165
  }
182
- if (sourceMap === true) {
166
+ if (sourceMap) {
183
167
  return 'source-map';
184
168
  }
185
169
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/webpack/utils.ts"],"names":[],"mappings":";;;;;;AAAA,2CAAgD;AAChD,iCAA4B;AAC5B,2BAAoC;AACpC,mCAAwC;AAExC,+BAAwC;AACxC,qEAAmC;AAInC,iDAA0D;AAE7C,QAAA,iBAAiB,GAAG,IAAA,cAAO,EACtC,IAAA,cAAO;AACL,mDAAmD;AACnD,OAAO,CAAC,OAAO,CAAC,kCAAkC,CAAC,CACpD,EACD,iBAAiB,CAClB,CAAC;AAEW,QAAA,iBAAiB,GAAG;IAC/B,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;IAClC,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;IAClC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC;IAC9C,SAAS,EAAE,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AAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAE/B,+DAA+D;IAC/D,OAAO,KAAK;SACT,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QACnB,MAAM,UAAU,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC;QACxD,OAAO,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAC9C,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC;AAdD,gCAcC;AAED;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,QAAgB,EAAE,KAAiB;IAC7D,MAAM,OAAO,GAAG,QAAQ,QAAQ,WAAW,IAAA,qBAAa,EAAC,KAAK,CAAC,EAAE,CAAC;IAClE,OAAO,wDAAwD,OAAO,YAAY,CAAC;AACrF,CAAC;AAHD,kCAGC","sourcesContent":["import { bytesToBase64 } from '@metamask/utils';\nimport { dim } from 'chalk';\nimport { promises as fs } from 'fs';\nimport { builtinModules } from 'module';\nimport type { Ora } from 'ora';\nimport { dirname, resolve } from 'path';\nimport stripAnsi from 'strip-ansi';\nimport type { Configuration } from 'webpack';\n\nimport type { ProcessedWebpackConfig } from '../config';\nimport { browserify, getFunctionLoader } from './loaders';\n\nexport const BROWSERSLIST_FILE = resolve(\n dirname(\n // eslint-disable-next-line n/no-extraneous-require\n require.resolve('@metamask/snaps-cli/package.json'),\n ),\n '.browserslistrc',\n);\n\nexport const WEBPACK_FALLBACKS = {\n assert: require.resolve('assert/'),\n buffer: require.resolve('buffer/'),\n console: require.resolve('console-browserify'),\n constants: require.resolve('constants-browserify'),\n crypto: require.resolve('crypto-browserify'),\n domain: require.resolve('domain-browser'),\n events: require.resolve('events/'),\n http: require.resolve('stream-http'),\n https: require.resolve('https-browserify'),\n os: require.resolve('os-browserify/browser'),\n path: require.resolve('path-browserify'),\n punycode: require.resolve('punycode/'),\n process: require.resolve('process/browser'),\n querystring: require.resolve('querystring-es3'),\n stream: require.resolve('stream-browserify'),\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex: require.resolve('readable-stream/lib/_stream_duplex'),\n _stream_passthrough: require.resolve(\n 'readable-stream/lib/_stream_passthrough',\n ),\n _stream_readable: require.resolve('readable-stream/lib/_stream_readable'),\n _stream_transform: require.resolve('readable-stream/lib/_stream_transform'),\n _stream_writable: require.resolve('readable-stream/lib/_stream_writable'),\n string_decoder: require.resolve('string_decoder/'),\n /* eslint-enable @typescript-eslint/naming-convention */\n sys: require.resolve('util/'),\n timers: require.resolve('timers-browserify'),\n tty: require.resolve('tty-browserify'),\n url: require.resolve('url/'),\n util: require.resolve('util/'),\n vm: require.resolve('vm-browserify'),\n zlib: require.resolve('browserify-zlib'),\n};\n\n/**\n * Get the default loader for JavaScript and TypeScript files, based on the\n * config object.\n *\n * - If the `legacy` option is set, we use the custom `browserify` loader. This\n * uses the legacy Browserify config to transpile the code.\n * - Otherwise, we use the `swc-loader`. This is a Webpack loader that uses the\n * `SWC` compiler, which is a much faster alternative to Babel and TypeScript's\n * own compiler.\n *\n * @param config - The processed snap Webpack config.\n * @param config.legacy - The legacy config object, if any.\n * @param config.sourceMap - Whether to generate source maps.\n * @see https://swc.rs/docs/usage/swc-loader\n * @returns The default loader.\n */\nexport async function getDefaultLoader({\n legacy,\n sourceMap,\n}: ProcessedWebpackConfig) {\n if (legacy) {\n /**\n * If the snap uses the legacy config, we use the custom `browserify`\n * loader. This uses the legacy Browserify config to transpile the code.\n * This is necessary for backwards compatibility with the\n * `bundlerCustomizer` function.\n */\n return getFunctionLoader(browserify, legacy);\n }\n\n const targets = await getBrowserslistTargets();\n return {\n /**\n * We use the `swc-loader` to transpile TypeScript and JavaScript files.\n * This is a Webpack loader that uses the `SWC` compiler, which is a much\n * faster alternative to Babel and TypeScript's own compiler.\n */\n loader: require.resolve('swc-loader'),\n\n /**\n * The options for the `swc-loader`. These can be overridden in the\n * `.swcrc` file.\n *\n * @see https://swc.rs/docs/configuration/swcrc\n */\n options: {\n sync: false,\n\n /**\n * This tells SWC to generate source maps. We set it to the\n * `sourceMap` value from the config object.\n *\n * This must be enabled if source maps are enabled in the config.\n */\n sourceMaps: Boolean(getDevTool(sourceMap)),\n\n jsc: {\n parser: {\n /**\n * This tells the parser to parse TypeScript files. If you\n * don't need to support TypeScript, you can set this to\n * `ecmascript` instead, but there's no harm in leaving it\n * as `typescript`.\n *\n * @see https://swc.rs/docs/configuration/compilation#jscparser\n */\n syntax: 'typescript',\n\n /**\n * This tells the parser to transpile JSX.\n *\n * @see https://swc.rs/docs/configuration/compilation#jscparser\n * @see https://swc.rs/docs/configuration/compilation#jscparserjsx\n */\n tsx: true,\n },\n\n transform: {\n react: {\n /**\n * This tells SWC to use the JSX runtime, instead of the\n * `createElement` function.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n runtime: 'automatic',\n\n /**\n * This tells SWC to import the JSX runtime from the\n * `@metamask/snaps-sdk` package, instead of the default React\n * package.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n importSource: '@metamask/snaps-sdk',\n\n /**\n * This tells SWC to use `Object.assign` and `Object.create` for\n * JSX spread attributes, instead of the default behavior.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n useBuiltins: true,\n },\n },\n },\n\n /**\n * The module configuration. This tells SWC how to output the\n * transpiled code.\n *\n * @see https://swc.rs/docs/configuration/modules\n */\n module: {\n /**\n * This tells SWC to output ES6 modules. This will allow Webpack to\n * optimize the output code better. Snaps don't support ES6 however, so\n * the output code will be transpiled to CommonJS by Webpack later in\n * the build process.\n *\n * @see https://swc.rs/docs/configuration/modules#es6\n */\n type: 'es6',\n },\n\n env: {\n targets: targets.join(', '),\n },\n },\n };\n}\n\n/**\n * Get the Webpack devtool configuration based on the given snap config.\n *\n * - If `sourceMap` is `inline`, return `inline-source-map`.\n * - If `sourceMap` is `true`, return `source-map`.\n * - Otherwise, return `false`.\n *\n * @param sourceMap - The `sourceMap` value from the snap config.\n * @returns The Webpack devtool configuration.\n */\nexport function getDevTool(\n sourceMap: ProcessedWebpackConfig['sourceMap'],\n): Configuration['devtool'] {\n if (sourceMap === 'inline') {\n return 'inline-source-map';\n }\n\n if (sourceMap === true) {\n return 'source-map';\n }\n\n return false;\n}\n\n/**\n * Get a function that can be used as handler function for Webpack's\n * `ProgressPlugin`.\n *\n * @param spinner - The spinner to update.\n * @param spinnerText - The initial spinner text. This will be prepended to the\n * percentage.\n * @returns A function that can be used as handler function for Webpack's\n * `ProgressPlugin`.\n */\n// Note: This is extracted for testing purposes.\nexport function getProgressHandler(spinner?: Ora, spinnerText?: string) {\n return (percentage: number) => {\n if (spinner && spinnerText) {\n spinner.text = `${spinnerText} ${dim(\n `(${Math.round(percentage * 100)}%)`,\n )}`;\n }\n };\n}\n\n/**\n * Get the targets from the `.browserslistrc` file.\n *\n * @returns The browser targets as an array of strings.\n */\nexport async function getBrowserslistTargets() {\n const contents = await fs.readFile(BROWSERSLIST_FILE, 'utf8');\n return contents\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line && !line.startsWith('#'));\n}\n\n/**\n * Get a singular or plural string based on the given count. This is useful for\n * generating messages like \"1 error\" or \"2 errors\". By default, the plural\n * string is the singular string with an \"s\" appended to it.\n *\n * This assumes that the text is in English, and likely won't work for some\n * other languages.\n *\n * @param count - The count.\n * @param singular - The singular string.\n * @param plural - The plural string.\n * @returns The singular or plural string.\n * @example\n * ```typescript\n * pluralize(1, 'error'); // => 'error'\n * pluralize(2, 'error'); // => 'errors'\n * pluralize(1, 'error', 'problem'); // => 'error'\n * pluralize(2, 'error', 'problems'); // => 'problems'\n * ```\n */\nexport function pluralize(\n count: number,\n singular: string,\n plural = `${singular}s`,\n) {\n return count === 1 ? singular : plural;\n}\n\n/**\n * Get an object that can be used as fallback config for Webpack's\n * `fallback` config.\n *\n * @param polyfills - The polyfill object from the snap config.\n * @returns The webpack fallback config.\n */\nexport function getFallbacks(polyfills: ProcessedWebpackConfig['polyfills']): {\n [index: string]: string | false;\n} {\n if (polyfills === true) {\n return Object.fromEntries(\n builtinModules.map((name) => [\n name,\n WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS] ?? false,\n ]),\n );\n }\n\n if (polyfills === false) {\n return Object.fromEntries(builtinModules.map((name) => [name, false]));\n }\n\n return Object.fromEntries(\n builtinModules.map((name) => [\n name,\n polyfills[name as keyof ProcessedWebpackConfig['polyfills']]\n ? WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS]\n : false,\n ]),\n );\n}\n\n/**\n * Get an object that can be used as environment variables for Webpack's\n * `DefinePlugin`.\n *\n * @param environment - The environment object from the Snap config.\n * @param defaults - The default environment variables.\n * @returns The Webpack environment variables.\n */\nexport function getEnvironmentVariables(\n environment: Record<string, unknown>,\n defaults = {\n NODE_DEBUG: 'false',\n NODE_ENV: 'production',\n DEBUG: 'false',\n },\n) {\n return Object.fromEntries(\n Object.entries({\n ...defaults,\n ...environment,\n }).map(([key, value]) => [`process.env.${key}`, JSON.stringify(value)]),\n );\n}\n\n/**\n * Format the given line to fit within the terminal width.\n *\n * @param line - The line to format.\n * @param indent - The indentation to use.\n * @param initialIndent - The initial indentation to use, i.e., the indentation\n * for the first line.\n * @returns The formatted line.\n */\nfunction formatLine(line: string, indent: number, initialIndent: number) {\n const terminalWidth = process.stdout.columns;\n if (!terminalWidth) {\n return `${' '.repeat(initialIndent)}${line}`;\n }\n\n return line.split(' ').reduce(\n ({ formattedText, currentLineLength }, word, index) => {\n // `chalk` adds ANSI escape codes to the text, which are not visible\n // characters. We need to strip them to get the visible length of the\n // text.\n const visibleWord = stripAnsi(word);\n\n // Determine if a space should be added before the word.\n const spaceBeforeWord = index > 0 ? ' ' : '';\n const wordLengthWithSpace = visibleWord.length + spaceBeforeWord.length;\n\n // If the word would exceed the terminal width, start a new line.\n if (currentLineLength + wordLengthWithSpace > terminalWidth) {\n return {\n formattedText: `${formattedText}\\n${' '.repeat(indent)}${word}`,\n currentLineLength: indent + visibleWord.length,\n };\n }\n\n // Otherwise, add the word to the current line.\n return {\n formattedText: formattedText + spaceBeforeWord + word,\n currentLineLength: currentLineLength + wordLengthWithSpace,\n };\n },\n {\n formattedText: ' '.repeat(initialIndent),\n currentLineLength: initialIndent,\n },\n ).formattedText;\n}\n\n/**\n * Format the given text to fit within the terminal width.\n *\n * @param text - The text to format.\n * @param indent - The indentation to use.\n * @param initialIndent - The initial indentation to use, i.e., the indentation\n * for the first line.\n * @returns The formatted text.\n */\nexport function formatText(\n text: string,\n indent: number,\n initialIndent = indent,\n) {\n const lines = text.split('\\n');\n\n // Apply formatting to each line separately and then join them.\n return lines\n .map((line, index) => {\n const lineIndent = index === 0 ? initialIndent : indent;\n return formatLine(line, indent, lineIndent);\n })\n .join('\\n');\n}\n\n/**\n * Get an SVG from the given bytes and mime type.\n *\n * @param mimeType - The mime type of the image.\n * @param bytes - The image bytes.\n * @returns The SVG.\n */\nexport function getImageSVG(mimeType: string, bytes: Uint8Array) {\n const dataUrl = `data:${mimeType};base64,${bytesToBase64(bytes)}`;\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><image href=\"${dataUrl}\" /></svg>`;\n}\n"]}
1
+ {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/webpack/utils.ts"],"names":[],"mappings":";;;;;;AAAA,2CAAgD;AAChD,iCAA4B;AAC5B,2BAAoC;AACpC,mCAAwC;AAExC,+BAAwC;AACxC,qEAAmC;AAKtB,QAAA,iBAAiB,GAAG,IAAA,cAAO,EACtC,IAAA,cAAO,EAAC,OAAO,CAAC,OAAO,CAAC,kCAAkC,CAAC,CAAC,EAC5D,iBAAiB,CAClB,CAAC;AAEW,QAAA,iBAAiB,GAAG;IAC/B,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;IAClC,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC;IAClC,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O,KAAK;SACT,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QACnB,MAAM,UAAU,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC;QACxD,OAAO,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAC9C,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC;AAdD,gCAcC;AAED;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,QAAgB,EAAE,KAAiB;IAC7D,MAAM,OAAO,GAAG,QAAQ,QAAQ,WAAW,IAAA,qBAAa,EAAC,KAAK,CAAC,EAAE,CAAC;IAClE,OAAO,wDAAwD,OAAO,YAAY,CAAC;AACrF,CAAC;AAHD,kCAGC","sourcesContent":["import { bytesToBase64 } from '@metamask/utils';\nimport { dim } from 'chalk';\nimport { promises as fs } from 'fs';\nimport { builtinModules } from 'module';\nimport type { Ora } from 'ora';\nimport { dirname, resolve } from 'path';\nimport stripAnsi from 'strip-ansi';\nimport type { Configuration } from 'webpack';\n\nimport type { ProcessedConfig } from '../config';\n\nexport const BROWSERSLIST_FILE = resolve(\n dirname(require.resolve('@metamask/snaps-cli/package.json')),\n '.browserslistrc',\n);\n\nexport const WEBPACK_FALLBACKS = {\n assert: require.resolve('assert/'),\n buffer: require.resolve('buffer/'),\n console: require.resolve('console-browserify'),\n constants: require.resolve('constants-browserify'),\n crypto: require.resolve('crypto-browserify'),\n domain: require.resolve('domain-browser'),\n events: require.resolve('events/'),\n http: require.resolve('stream-http'),\n https: require.resolve('https-browserify'),\n os: require.resolve('os-browserify/browser'),\n path: require.resolve('path-browserify'),\n punycode: require.resolve('punycode/'),\n process: require.resolve('process/browser'),\n querystring: require.resolve('querystring-es3'),\n stream: require.resolve('stream-browserify'),\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex: require.resolve('readable-stream/lib/_stream_duplex'),\n _stream_passthrough: require.resolve(\n 'readable-stream/lib/_stream_passthrough',\n ),\n _stream_readable: require.resolve('readable-stream/lib/_stream_readable'),\n _stream_transform: require.resolve('readable-stream/lib/_stream_transform'),\n _stream_writable: require.resolve('readable-stream/lib/_stream_writable'),\n string_decoder: require.resolve('string_decoder/'),\n /* eslint-enable @typescript-eslint/naming-convention */\n sys: require.resolve('util/'),\n timers: require.resolve('timers-browserify'),\n tty: require.resolve('tty-browserify'),\n url: require.resolve('url/'),\n util: require.resolve('util/'),\n vm: require.resolve('vm-browserify'),\n zlib: require.resolve('browserify-zlib'),\n};\n\n/**\n * Get the default loader for JavaScript and TypeScript files, based on the\n * config object.\n *\n * We use the `swc-loader`, which is a Webpack loader that uses the `SWC`\n * compiler, a much faster alternative to Babel and TypeScript's own compiler.\n *\n * @param config - The processed snap Webpack config.\n * @param config.sourceMap - Whether to generate source maps.\n * @see https://swc.rs/docs/usage/swc-loader\n * @returns The default loader.\n */\nexport async function getDefaultLoader({ sourceMap }: ProcessedConfig) {\n const targets = await getBrowserslistTargets();\n return {\n /**\n * We use the `swc-loader` to transpile TypeScript and JavaScript files.\n * This is a Webpack loader that uses the `SWC` compiler, which is a much\n * faster alternative to Babel and TypeScript's own compiler.\n */\n loader: require.resolve('swc-loader'),\n\n /**\n * The options for the `swc-loader`. These can be overridden in the\n * `.swcrc` file.\n *\n * @see https://swc.rs/docs/configuration/swcrc\n */\n options: {\n sync: false,\n\n /**\n * This tells SWC to generate source maps. We set it to the\n * `sourceMap` value from the config object.\n *\n * This must be enabled if source maps are enabled in the config.\n */\n sourceMaps: Boolean(getDevTool(sourceMap)),\n\n jsc: {\n parser: {\n /**\n * This tells the parser to parse TypeScript files. If you\n * don't need to support TypeScript, you can set this to\n * `ecmascript` instead, but there's no harm in leaving it\n * as `typescript`.\n *\n * @see https://swc.rs/docs/configuration/compilation#jscparser\n */\n syntax: 'typescript',\n\n /**\n * This tells the parser to transpile JSX.\n *\n * @see https://swc.rs/docs/configuration/compilation#jscparser\n * @see https://swc.rs/docs/configuration/compilation#jscparserjsx\n */\n tsx: true,\n },\n\n transform: {\n react: {\n /**\n * This tells SWC to use the JSX runtime, instead of the\n * `createElement` function.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n runtime: 'automatic',\n\n /**\n * This tells SWC to import the JSX runtime from the\n * `@metamask/snaps-sdk` package, instead of the default React\n * package.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n importSource: '@metamask/snaps-sdk',\n\n /**\n * This tells SWC to use `Object.assign` and `Object.create` for\n * JSX spread attributes, instead of the default behavior.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n useBuiltins: true,\n },\n },\n },\n\n /**\n * The module configuration. This tells SWC how to output the\n * transpiled code.\n *\n * @see https://swc.rs/docs/configuration/modules\n */\n module: {\n /**\n * This tells SWC to output ES6 modules. This will allow Webpack to\n * optimize the output code better. Snaps don't support ES6 however, so\n * the output code will be transpiled to CommonJS by Webpack later in\n * the build process.\n *\n * @see https://swc.rs/docs/configuration/modules#es6\n */\n type: 'es6',\n },\n\n env: {\n targets: targets.join(', '),\n },\n },\n };\n}\n\n/**\n * Get the Webpack devtool configuration based on the given snap config.\n *\n * - If `sourceMap` is `inline`, return `inline-source-map`.\n * - If `sourceMap` is `true`, return `source-map`.\n * - Otherwise, return `false`.\n *\n * @param sourceMap - The `sourceMap` value from the snap config.\n * @returns The Webpack devtool configuration.\n */\nexport function getDevTool(\n sourceMap: ProcessedConfig['sourceMap'],\n): Configuration['devtool'] {\n if (sourceMap === 'inline') {\n return 'inline-source-map';\n }\n\n if (sourceMap) {\n return 'source-map';\n }\n\n return false;\n}\n\n/**\n * Get a function that can be used as handler function for Webpack's\n * `ProgressPlugin`.\n *\n * @param spinner - The spinner to update.\n * @param spinnerText - The initial spinner text. This will be prepended to the\n * percentage.\n * @returns A function that can be used as handler function for Webpack's\n * `ProgressPlugin`.\n */\n// Note: This is extracted for testing purposes.\nexport function getProgressHandler(spinner?: Ora, spinnerText?: string) {\n return (percentage: number) => {\n if (spinner && spinnerText) {\n spinner.text = `${spinnerText} ${dim(\n `(${Math.round(percentage * 100)}%)`,\n )}`;\n }\n };\n}\n\n/**\n * Get the targets from the `.browserslistrc` file.\n *\n * @returns The browser targets as an array of strings.\n */\nexport async function getBrowserslistTargets() {\n const contents = await fs.readFile(BROWSERSLIST_FILE, 'utf8');\n return contents\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line && !line.startsWith('#'));\n}\n\n/**\n * Get a singular or plural string based on the given count. This is useful for\n * generating messages like \"1 error\" or \"2 errors\". By default, the plural\n * string is the singular string with an \"s\" appended to it.\n *\n * This assumes that the text is in English, and likely won't work for some\n * other languages.\n *\n * @param count - The count.\n * @param singular - The singular string.\n * @param plural - The plural string.\n * @returns The singular or plural string.\n * @example\n * ```typescript\n * pluralize(1, 'error'); // => 'error'\n * pluralize(2, 'error'); // => 'errors'\n * pluralize(1, 'error', 'problem'); // => 'error'\n * pluralize(2, 'error', 'problems'); // => 'problems'\n * ```\n */\nexport function pluralize(\n count: number,\n singular: string,\n plural = `${singular}s`,\n) {\n return count === 1 ? singular : plural;\n}\n\n/**\n * Get an object that can be used as fallback config for Webpack's\n * `fallback` config.\n *\n * @param polyfills - The polyfill object from the snap config.\n * @returns The webpack fallback config.\n */\nexport function getFallbacks(polyfills: ProcessedConfig['polyfills']): {\n [index: string]: string | false;\n} {\n if (polyfills === true) {\n return Object.fromEntries(\n builtinModules.map((name) => [\n name,\n WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS] ?? false,\n ]),\n );\n }\n\n if (polyfills === false) {\n return Object.fromEntries(builtinModules.map((name) => [name, false]));\n }\n\n return Object.fromEntries(\n builtinModules.map((name) => [\n name,\n polyfills[name as keyof ProcessedConfig['polyfills']]\n ? WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS]\n : false,\n ]),\n );\n}\n\n/**\n * Get an object that can be used as environment variables for Webpack's\n * `DefinePlugin`.\n *\n * @param environment - The environment object from the Snap config.\n * @param defaults - The default environment variables.\n * @returns The Webpack environment variables.\n */\nexport function getEnvironmentVariables(\n environment: Record<string, unknown>,\n defaults = {\n NODE_DEBUG: 'false',\n NODE_ENV: 'production',\n DEBUG: 'false',\n },\n) {\n return Object.fromEntries(\n Object.entries({\n ...defaults,\n ...environment,\n }).map(([key, value]) => [`process.env.${key}`, JSON.stringify(value)]),\n );\n}\n\n/**\n * Format the given line to fit within the terminal width.\n *\n * @param line - The line to format.\n * @param indent - The indentation to use.\n * @param initialIndent - The initial indentation to use, i.e., the indentation\n * for the first line.\n * @returns The formatted line.\n */\nfunction formatLine(line: string, indent: number, initialIndent: number) {\n const terminalWidth = process.stdout.columns;\n if (!terminalWidth) {\n return `${' '.repeat(initialIndent)}${line}`;\n }\n\n return line.split(' ').reduce(\n ({ formattedText, currentLineLength }, word, index) => {\n // `chalk` adds ANSI escape codes to the text, which are not visible\n // characters. We need to strip them to get the visible length of the\n // text.\n const visibleWord = stripAnsi(word);\n\n // Determine if a space should be added before the word.\n const spaceBeforeWord = index > 0 ? ' ' : '';\n const wordLengthWithSpace = visibleWord.length + spaceBeforeWord.length;\n\n // If the word would exceed the terminal width, start a new line.\n if (currentLineLength + wordLengthWithSpace > terminalWidth) {\n return {\n formattedText: `${formattedText}\\n${' '.repeat(indent)}${word}`,\n currentLineLength: indent + visibleWord.length,\n };\n }\n\n // Otherwise, add the word to the current line.\n return {\n formattedText: formattedText + spaceBeforeWord + word,\n currentLineLength: currentLineLength + wordLengthWithSpace,\n };\n },\n {\n formattedText: ' '.repeat(initialIndent),\n currentLineLength: initialIndent,\n },\n ).formattedText;\n}\n\n/**\n * Format the given text to fit within the terminal width.\n *\n * @param text - The text to format.\n * @param indent - The indentation to use.\n * @param initialIndent - The initial indentation to use, i.e., the indentation\n * for the first line.\n * @returns The formatted text.\n */\nexport function formatText(\n text: string,\n indent: number,\n initialIndent = indent,\n) {\n const lines = text.split('\\n');\n\n // Apply formatting to each line separately and then join them.\n return lines\n .map((line, index) => {\n const lineIndent = index === 0 ? initialIndent : indent;\n return formatLine(line, indent, lineIndent);\n })\n .join('\\n');\n}\n\n/**\n * Get an SVG from the given bytes and mime type.\n *\n * @param mimeType - The mime type of the image.\n * @param bytes - The image bytes.\n * @returns The SVG.\n */\nexport function getImageSVG(mimeType: string, bytes: Uint8Array) {\n const dataUrl = `data:${mimeType};base64,${bytesToBase64(bytes)}`;\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><image href=\"${dataUrl}\" /></svg>`;\n}\n"]}
@@ -1,7 +1,6 @@
1
- /// <reference types="browserify" />
2
1
  import type { Ora } from "ora/index.js";
3
2
  import type { Configuration } from "webpack";
4
- import type { ProcessedWebpackConfig } from "../config.cjs";
3
+ import type { ProcessedConfig } from "../config.cjs";
5
4
  export declare const BROWSERSLIST_FILE: string;
6
5
  export declare const WEBPACK_FALLBACKS: {
7
6
  assert: string;
@@ -37,44 +36,15 @@ export declare const WEBPACK_FALLBACKS: {
37
36
  * Get the default loader for JavaScript and TypeScript files, based on the
38
37
  * config object.
39
38
  *
40
- * - If the `legacy` option is set, we use the custom `browserify` loader. This
41
- * uses the legacy Browserify config to transpile the code.
42
- * - Otherwise, we use the `swc-loader`. This is a Webpack loader that uses the
43
- * `SWC` compiler, which is a much faster alternative to Babel and TypeScript's
44
- * own compiler.
39
+ * We use the `swc-loader`, which is a Webpack loader that uses the `SWC`
40
+ * compiler, a much faster alternative to Babel and TypeScript's own compiler.
45
41
  *
46
42
  * @param config - The processed snap Webpack config.
47
- * @param config.legacy - The legacy config object, if any.
48
43
  * @param config.sourceMap - Whether to generate source maps.
49
44
  * @see https://swc.rs/docs/usage/swc-loader
50
45
  * @returns The default loader.
51
46
  */
52
- export declare function getDefaultLoader({ legacy, sourceMap, }: ProcessedWebpackConfig): Promise<{
53
- loader: string;
54
- options: {
55
- fn: import("webpack").LoaderDefinitionFunction<{
56
- transpilationMode: import("../builders.cjs").TranspilationModes.LocalAndDeps;
57
- depsToTranspile: string[];
58
- writeManifest: boolean;
59
- bundlerCustomizer?: ((bundler: import("browserify").BrowserifyObject) => void) | undefined;
60
- } | {
61
- transpilationMode: import("../builders.cjs").TranspilationModes.LocalOnly | import("../builders.cjs").TranspilationModes.None;
62
- depsToTranspile: unknown[];
63
- writeManifest: boolean;
64
- bundlerCustomizer?: ((bundler: import("browserify").BrowserifyObject) => void) | undefined;
65
- }, {}>;
66
- } & ({
67
- transpilationMode: import("../builders.cjs").TranspilationModes.LocalAndDeps;
68
- depsToTranspile: string[];
69
- writeManifest: boolean;
70
- bundlerCustomizer?: ((bundler: import("browserify").BrowserifyObject) => void) | undefined;
71
- } | {
72
- transpilationMode: import("../builders.cjs").TranspilationModes.LocalOnly | import("../builders.cjs").TranspilationModes.None;
73
- depsToTranspile: unknown[];
74
- writeManifest: boolean;
75
- bundlerCustomizer?: ((bundler: import("browserify").BrowserifyObject) => void) | undefined;
76
- });
77
- } | {
47
+ export declare function getDefaultLoader({ sourceMap }: ProcessedConfig): Promise<{
78
48
  /**
79
49
  * We use the `swc-loader` to transpile TypeScript and JavaScript files.
80
50
  * This is a Webpack loader that uses the `SWC` compiler, which is a much
@@ -174,7 +144,7 @@ export declare function getDefaultLoader({ legacy, sourceMap, }: ProcessedWebpac
174
144
  * @param sourceMap - The `sourceMap` value from the snap config.
175
145
  * @returns The Webpack devtool configuration.
176
146
  */
177
- export declare function getDevTool(sourceMap: ProcessedWebpackConfig['sourceMap']): Configuration['devtool'];
147
+ export declare function getDevTool(sourceMap: ProcessedConfig['sourceMap']): Configuration['devtool'];
178
148
  /**
179
149
  * Get a function that can be used as handler function for Webpack's
180
150
  * `ProgressPlugin`.
@@ -220,7 +190,7 @@ export declare function pluralize(count: number, singular: string, plural?: stri
220
190
  * @param polyfills - The polyfill object from the snap config.
221
191
  * @returns The webpack fallback config.
222
192
  */
223
- export declare function getFallbacks(polyfills: ProcessedWebpackConfig['polyfills']): {
193
+ export declare function getFallbacks(polyfills: ProcessedConfig['polyfills']): {
224
194
  [index: string]: string | false;
225
195
  };
226
196
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/webpack/utils.ts"],"names":[],"mappings":";AAIA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;AAG/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB;AAE7C,OAAO,KAAK,EAAE,sBAAsB,EAAE,sBAAkB;AAGxD,eAAO,MAAM,iBAAiB,QAM7B,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiC7B,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,MAAM,EACN,SAAS,GACV,EAAE,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;IAarB;;;;OAIG;;IAGH;;;;;OAKG;;;QAID;;;;;WAKG;;;;gBAKC;;;;;;;mBAOG;;gBAGH;;;;;mBAKG;;;;;oBAMD;;;;;uBAKG;;oBAGH;;;;;;uBAMG;;oBAGH;;;;;uBAKG;;;;;QAMT;;;;;WAKG;;YAED;;;;;;;eAOG;;;;;;;GASV;AAED;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CACxB,SAAS,EAAE,sBAAsB,CAAC,WAAW,CAAC,GAC7C,aAAa,CAAC,SAAS,CAAC,CAU1B;AAED;;;;;;;;;GASG;AAEH,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,MAAM,gBAChD,MAAM,UAO3B;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,sBAM3C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,MAAM,SAAiB,UAGxB;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,sBAAsB,CAAC,WAA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G,EAAE,WAAW,CAAC,EAAE,MAAM,gBAChD,MAAM,UAO3B;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,sBAM3C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,MAAM,SAAiB,UAGxB;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,eAAe,CAAC,WAAW,CAAC,GAAG;IACrE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC;CACjC,CAsBA;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACrC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACpC,QAAQ;;;;CAIP;;EAQF;AAiDD;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CACxB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,aAAa,SAAS,UAWvB;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,UAG9D"}
@@ -1,7 +1,6 @@
1
- /// <reference types="browserify" />
2
1
  import type { Ora } from "ora/index.js";
3
2
  import type { Configuration } from "webpack";
4
- import type { ProcessedWebpackConfig } from "../config.mjs";
3
+ import type { ProcessedConfig } from "../config.mjs";
5
4
  export declare const BROWSERSLIST_FILE: string;
6
5
  export declare const WEBPACK_FALLBACKS: {
7
6
  assert: string;
@@ -37,44 +36,15 @@ export declare const WEBPACK_FALLBACKS: {
37
36
  * Get the default loader for JavaScript and TypeScript files, based on the
38
37
  * config object.
39
38
  *
40
- * - If the `legacy` option is set, we use the custom `browserify` loader. This
41
- * uses the legacy Browserify config to transpile the code.
42
- * - Otherwise, we use the `swc-loader`. This is a Webpack loader that uses the
43
- * `SWC` compiler, which is a much faster alternative to Babel and TypeScript's
44
- * own compiler.
39
+ * We use the `swc-loader`, which is a Webpack loader that uses the `SWC`
40
+ * compiler, a much faster alternative to Babel and TypeScript's own compiler.
45
41
  *
46
42
  * @param config - The processed snap Webpack config.
47
- * @param config.legacy - The legacy config object, if any.
48
43
  * @param config.sourceMap - Whether to generate source maps.
49
44
  * @see https://swc.rs/docs/usage/swc-loader
50
45
  * @returns The default loader.
51
46
  */
52
- export declare function getDefaultLoader({ legacy, sourceMap, }: ProcessedWebpackConfig): Promise<{
53
- loader: string;
54
- options: {
55
- fn: import("webpack").LoaderDefinitionFunction<{
56
- transpilationMode: import("../builders.mjs").TranspilationModes.LocalAndDeps;
57
- depsToTranspile: string[];
58
- writeManifest: boolean;
59
- bundlerCustomizer?: ((bundler: import("browserify").BrowserifyObject) => void) | undefined;
60
- } | {
61
- transpilationMode: import("../builders.mjs").TranspilationModes.LocalOnly | import("../builders.mjs").TranspilationModes.None;
62
- depsToTranspile: unknown[];
63
- writeManifest: boolean;
64
- bundlerCustomizer?: ((bundler: import("browserify").BrowserifyObject) => void) | undefined;
65
- }, {}>;
66
- } & ({
67
- transpilationMode: import("../builders.mjs").TranspilationModes.LocalAndDeps;
68
- depsToTranspile: string[];
69
- writeManifest: boolean;
70
- bundlerCustomizer?: ((bundler: import("browserify").BrowserifyObject) => void) | undefined;
71
- } | {
72
- transpilationMode: import("../builders.mjs").TranspilationModes.LocalOnly | import("../builders.mjs").TranspilationModes.None;
73
- depsToTranspile: unknown[];
74
- writeManifest: boolean;
75
- bundlerCustomizer?: ((bundler: import("browserify").BrowserifyObject) => void) | undefined;
76
- });
77
- } | {
47
+ export declare function getDefaultLoader({ sourceMap }: ProcessedConfig): Promise<{
78
48
  /**
79
49
  * We use the `swc-loader` to transpile TypeScript and JavaScript files.
80
50
  * This is a Webpack loader that uses the `SWC` compiler, which is a much
@@ -174,7 +144,7 @@ export declare function getDefaultLoader({ legacy, sourceMap, }: ProcessedWebpac
174
144
  * @param sourceMap - The `sourceMap` value from the snap config.
175
145
  * @returns The Webpack devtool configuration.
176
146
  */
177
- export declare function getDevTool(sourceMap: ProcessedWebpackConfig['sourceMap']): Configuration['devtool'];
147
+ export declare function getDevTool(sourceMap: ProcessedConfig['sourceMap']): Configuration['devtool'];
178
148
  /**
179
149
  * Get a function that can be used as handler function for Webpack's
180
150
  * `ProgressPlugin`.
@@ -220,7 +190,7 @@ export declare function pluralize(count: number, singular: string, plural?: stri
220
190
  * @param polyfills - The polyfill object from the snap config.
221
191
  * @returns The webpack fallback config.
222
192
  */
223
- export declare function getFallbacks(polyfills: ProcessedWebpackConfig['polyfills']): {
193
+ export declare function getFallbacks(polyfills: ProcessedConfig['polyfills']): {
224
194
  [index: string]: string | false;
225
195
  };
226
196
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../src/webpack/utils.ts"],"names":[],"mappings":";AAIA,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAY;AAG/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB;AAE7C,OAAO,KAAK,EAAE,sBAAsB,EAAE,sBAAkB;AAGxD,eAAO,MAAM,iBAAiB,QAM7B,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiC7B,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,MAAM,EACN,SAAS,GACV,EAAE,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;IAarB;;;;OAIG;;IAGH;;;;;OAKG;;;QAID;;;;;WAKG;;;;gBAKC;;;;;;;mBAOG;;gBAGH;;;;;mBAKG;;;;;oBAMD;;;;;uBAKG;;oBAGH;;;;;;uBAMG;;oBAGH;;;;;uBAKG;;;;;QAMT;;;;;WAKG;;YAED;;;;;;;eAOG;;;;;;;GASV;AAED;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CACxB,SAAS,EAAE,sBAAsB,CAAC,WAAW,CAAC,GAC7C,aAAa,CAAC,SAAS,CAAC,CAU1B;AAED;;;;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WAKG;;;;gBAKC;;;;;;;mBAOG;;gBAGH;;;;;mBAKG;;;;;oBAMD;;;;;uBAKG;;oBAGH;;;;;;uBAMG;;oBAGH;;;;;uBAKG;;;;;QAMT;;;;;WAKG;;YAED;;;;;;;eAOG;;;;;;;GASV;AAED;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CACxB,SAAS,EAAE,eAAe,CAAC,WAAW,CAAC,GACtC,aAAa,CAAC,SAAS,CAAC,CAU1B;AAED;;;;;;;;;GASG;AAEH,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,MAAM,gBAChD,MAAM,UAO3B;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,sBAM3C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,MAAM,SAAiB,UAGxB;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,eAAe,CAAC,WAAW,CAAC,GAAG;IACrE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC;CACjC,CAsBA;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACrC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACpC,QAAQ;;;;CAIP;;EAQF;AAiDD;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CACxB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,aAAa,SAAS,UAWvB;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,UAG9D"}
@@ -14,7 +14,6 @@ import { builtinModules } from "module";
14
14
  import { dirname, resolve } from "path";
15
15
  import $stripAnsi from "strip-ansi/index.js";
16
16
  const stripAnsi = $importDefault($stripAnsi);
17
- import { browserify, getFunctionLoader } from "./loaders/index.mjs";
18
17
  export const BROWSERSLIST_FILE = resolve(dirname($require.resolve('@metamask/snaps-cli/package.json')), '.browserslistrc');
19
18
  export const WEBPACK_FALLBACKS = {
20
19
  assert: $require.resolve('assert/'),
@@ -52,28 +51,15 @@ export const WEBPACK_FALLBACKS = {
52
51
  * Get the default loader for JavaScript and TypeScript files, based on the
53
52
  * config object.
54
53
  *
55
- * - If the `legacy` option is set, we use the custom `browserify` loader. This
56
- * uses the legacy Browserify config to transpile the code.
57
- * - Otherwise, we use the `swc-loader`. This is a Webpack loader that uses the
58
- * `SWC` compiler, which is a much faster alternative to Babel and TypeScript's
59
- * own compiler.
54
+ * We use the `swc-loader`, which is a Webpack loader that uses the `SWC`
55
+ * compiler, a much faster alternative to Babel and TypeScript's own compiler.
60
56
  *
61
57
  * @param config - The processed snap Webpack config.
62
- * @param config.legacy - The legacy config object, if any.
63
58
  * @param config.sourceMap - Whether to generate source maps.
64
59
  * @see https://swc.rs/docs/usage/swc-loader
65
60
  * @returns The default loader.
66
61
  */
67
- export async function getDefaultLoader({ legacy, sourceMap, }) {
68
- if (legacy) {
69
- /**
70
- * If the snap uses the legacy config, we use the custom `browserify`
71
- * loader. This uses the legacy Browserify config to transpile the code.
72
- * This is necessary for backwards compatibility with the
73
- * `bundlerCustomizer` function.
74
- */
75
- return getFunctionLoader(browserify, legacy);
76
- }
62
+ export async function getDefaultLoader({ sourceMap }) {
77
63
  const targets = await getBrowserslistTargets();
78
64
  return {
79
65
  /**
@@ -180,7 +166,7 @@ export function getDevTool(sourceMap) {
180
166
  if (sourceMap === 'inline') {
181
167
  return 'inline-source-map';
182
168
  }
183
- if (sourceMap === true) {
169
+ if (sourceMap) {
184
170
  return 'source-map';
185
171
  }
186
172
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/webpack/utils.ts"],"names":[],"mappings":";;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,wBAAwB;;;AAEhD,OAAO,EAAE,QAAQ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,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC;QACxD,OAAO,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAC9C,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,QAAgB,EAAE,KAAiB;IAC7D,MAAM,OAAO,GAAG,QAAQ,QAAQ,WAAW,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;IAClE,OAAO,wDAAwD,OAAO,YAAY,CAAC;AACrF,CAAC","sourcesContent":["import { bytesToBase64 } from '@metamask/utils';\nimport { dim } from 'chalk';\nimport { promises as fs } from 'fs';\nimport { builtinModules } from 'module';\nimport type { Ora } from 'ora';\nimport { dirname, resolve } from 'path';\nimport stripAnsi from 'strip-ansi';\nimport type { Configuration } from 'webpack';\n\nimport type { ProcessedWebpackConfig } from '../config';\nimport { browserify, getFunctionLoader } from './loaders';\n\nexport const BROWSERSLIST_FILE = resolve(\n dirname(\n // eslint-disable-next-line n/no-extraneous-require\n require.resolve('@metamask/snaps-cli/package.json'),\n ),\n '.browserslistrc',\n);\n\nexport const WEBPACK_FALLBACKS = {\n assert: require.resolve('assert/'),\n buffer: require.resolve('buffer/'),\n console: require.resolve('console-browserify'),\n constants: require.resolve('constants-browserify'),\n crypto: require.resolve('crypto-browserify'),\n domain: require.resolve('domain-browser'),\n events: require.resolve('events/'),\n http: require.resolve('stream-http'),\n https: require.resolve('https-browserify'),\n os: require.resolve('os-browserify/browser'),\n path: require.resolve('path-browserify'),\n punycode: require.resolve('punycode/'),\n process: require.resolve('process/browser'),\n querystring: require.resolve('querystring-es3'),\n stream: require.resolve('stream-browserify'),\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex: require.resolve('readable-stream/lib/_stream_duplex'),\n _stream_passthrough: require.resolve(\n 'readable-stream/lib/_stream_passthrough',\n ),\n _stream_readable: require.resolve('readable-stream/lib/_stream_readable'),\n _stream_transform: require.resolve('readable-stream/lib/_stream_transform'),\n _stream_writable: require.resolve('readable-stream/lib/_stream_writable'),\n string_decoder: require.resolve('string_decoder/'),\n /* eslint-enable @typescript-eslint/naming-convention */\n sys: require.resolve('util/'),\n timers: require.resolve('timers-browserify'),\n tty: require.resolve('tty-browserify'),\n url: require.resolve('url/'),\n util: require.resolve('util/'),\n vm: require.resolve('vm-browserify'),\n zlib: require.resolve('browserify-zlib'),\n};\n\n/**\n * Get the default loader for JavaScript and TypeScript files, based on the\n * config object.\n *\n * - If the `legacy` option is set, we use the custom `browserify` loader. This\n * uses the legacy Browserify config to transpile the code.\n * - Otherwise, we use the `swc-loader`. This is a Webpack loader that uses the\n * `SWC` compiler, which is a much faster alternative to Babel and TypeScript's\n * own compiler.\n *\n * @param config - The processed snap Webpack config.\n * @param config.legacy - The legacy config object, if any.\n * @param config.sourceMap - Whether to generate source maps.\n * @see https://swc.rs/docs/usage/swc-loader\n * @returns The default loader.\n */\nexport async function getDefaultLoader({\n legacy,\n sourceMap,\n}: ProcessedWebpackConfig) {\n if (legacy) {\n /**\n * If the snap uses the legacy config, we use the custom `browserify`\n * loader. This uses the legacy Browserify config to transpile the code.\n * This is necessary for backwards compatibility with the\n * `bundlerCustomizer` function.\n */\n return getFunctionLoader(browserify, legacy);\n }\n\n const targets = await getBrowserslistTargets();\n return {\n /**\n * We use the `swc-loader` to transpile TypeScript and JavaScript files.\n * This is a Webpack loader that uses the `SWC` compiler, which is a much\n * faster alternative to Babel and TypeScript's own compiler.\n */\n loader: require.resolve('swc-loader'),\n\n /**\n * The options for the `swc-loader`. These can be overridden in the\n * `.swcrc` file.\n *\n * @see https://swc.rs/docs/configuration/swcrc\n */\n options: {\n sync: false,\n\n /**\n * This tells SWC to generate source maps. We set it to the\n * `sourceMap` value from the config object.\n *\n * This must be enabled if source maps are enabled in the config.\n */\n sourceMaps: Boolean(getDevTool(sourceMap)),\n\n jsc: {\n parser: {\n /**\n * This tells the parser to parse TypeScript files. If you\n * don't need to support TypeScript, you can set this to\n * `ecmascript` instead, but there's no harm in leaving it\n * as `typescript`.\n *\n * @see https://swc.rs/docs/configuration/compilation#jscparser\n */\n syntax: 'typescript',\n\n /**\n * This tells the parser to transpile JSX.\n *\n * @see https://swc.rs/docs/configuration/compilation#jscparser\n * @see https://swc.rs/docs/configuration/compilation#jscparserjsx\n */\n tsx: true,\n },\n\n transform: {\n react: {\n /**\n * This tells SWC to use the JSX runtime, instead of the\n * `createElement` function.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n runtime: 'automatic',\n\n /**\n * This tells SWC to import the JSX runtime from the\n * `@metamask/snaps-sdk` package, instead of the default React\n * package.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n importSource: '@metamask/snaps-sdk',\n\n /**\n * This tells SWC to use `Object.assign` and `Object.create` for\n * JSX spread attributes, instead of the default behavior.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n useBuiltins: true,\n },\n },\n },\n\n /**\n * The module configuration. This tells SWC how to output the\n * transpiled code.\n *\n * @see https://swc.rs/docs/configuration/modules\n */\n module: {\n /**\n * This tells SWC to output ES6 modules. This will allow Webpack to\n * optimize the output code better. Snaps don't support ES6 however, so\n * the output code will be transpiled to CommonJS by Webpack later in\n * the build process.\n *\n * @see https://swc.rs/docs/configuration/modules#es6\n */\n type: 'es6',\n },\n\n env: {\n targets: targets.join(', '),\n },\n },\n };\n}\n\n/**\n * Get the Webpack devtool configuration based on the given snap config.\n *\n * - If `sourceMap` is `inline`, return `inline-source-map`.\n * - If `sourceMap` is `true`, return `source-map`.\n * - Otherwise, return `false`.\n *\n * @param sourceMap - The `sourceMap` value from the snap config.\n * @returns The Webpack devtool configuration.\n */\nexport function getDevTool(\n sourceMap: ProcessedWebpackConfig['sourceMap'],\n): Configuration['devtool'] {\n if (sourceMap === 'inline') {\n return 'inline-source-map';\n }\n\n if (sourceMap === true) {\n return 'source-map';\n }\n\n return false;\n}\n\n/**\n * Get a function that can be used as handler function for Webpack's\n * `ProgressPlugin`.\n *\n * @param spinner - The spinner to update.\n * @param spinnerText - The initial spinner text. This will be prepended to the\n * percentage.\n * @returns A function that can be used as handler function for Webpack's\n * `ProgressPlugin`.\n */\n// Note: This is extracted for testing purposes.\nexport function getProgressHandler(spinner?: Ora, spinnerText?: string) {\n return (percentage: number) => {\n if (spinner && spinnerText) {\n spinner.text = `${spinnerText} ${dim(\n `(${Math.round(percentage * 100)}%)`,\n )}`;\n }\n };\n}\n\n/**\n * Get the targets from the `.browserslistrc` file.\n *\n * @returns The browser targets as an array of strings.\n */\nexport async function getBrowserslistTargets() {\n const contents = await fs.readFile(BROWSERSLIST_FILE, 'utf8');\n return contents\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line && !line.startsWith('#'));\n}\n\n/**\n * Get a singular or plural string based on the given count. This is useful for\n * generating messages like \"1 error\" or \"2 errors\". By default, the plural\n * string is the singular string with an \"s\" appended to it.\n *\n * This assumes that the text is in English, and likely won't work for some\n * other languages.\n *\n * @param count - The count.\n * @param singular - The singular string.\n * @param plural - The plural string.\n * @returns The singular or plural string.\n * @example\n * ```typescript\n * pluralize(1, 'error'); // => 'error'\n * pluralize(2, 'error'); // => 'errors'\n * pluralize(1, 'error', 'problem'); // => 'error'\n * pluralize(2, 'error', 'problems'); // => 'problems'\n * ```\n */\nexport function pluralize(\n count: number,\n singular: string,\n plural = `${singular}s`,\n) {\n return count === 1 ? singular : plural;\n}\n\n/**\n * Get an object that can be used as fallback config for Webpack's\n * `fallback` config.\n *\n * @param polyfills - The polyfill object from the snap config.\n * @returns The webpack fallback config.\n */\nexport function getFallbacks(polyfills: ProcessedWebpackConfig['polyfills']): {\n [index: string]: string | false;\n} {\n if (polyfills === true) {\n return Object.fromEntries(\n builtinModules.map((name) => [\n name,\n WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS] ?? false,\n ]),\n );\n }\n\n if (polyfills === false) {\n return Object.fromEntries(builtinModules.map((name) => [name, false]));\n }\n\n return Object.fromEntries(\n builtinModules.map((name) => [\n name,\n polyfills[name as keyof ProcessedWebpackConfig['polyfills']]\n ? WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS]\n : false,\n ]),\n );\n}\n\n/**\n * Get an object that can be used as environment variables for Webpack's\n * `DefinePlugin`.\n *\n * @param environment - The environment object from the Snap config.\n * @param defaults - The default environment variables.\n * @returns The Webpack environment variables.\n */\nexport function getEnvironmentVariables(\n environment: Record<string, unknown>,\n defaults = {\n NODE_DEBUG: 'false',\n NODE_ENV: 'production',\n DEBUG: 'false',\n },\n) {\n return Object.fromEntries(\n Object.entries({\n ...defaults,\n ...environment,\n }).map(([key, value]) => [`process.env.${key}`, JSON.stringify(value)]),\n );\n}\n\n/**\n * Format the given line to fit within the terminal width.\n *\n * @param line - The line to format.\n * @param indent - The indentation to use.\n * @param initialIndent - The initial indentation to use, i.e., the indentation\n * for the first line.\n * @returns The formatted line.\n */\nfunction formatLine(line: string, indent: number, initialIndent: number) {\n const terminalWidth = process.stdout.columns;\n if (!terminalWidth) {\n return `${' '.repeat(initialIndent)}${line}`;\n }\n\n return line.split(' ').reduce(\n ({ formattedText, currentLineLength }, word, index) => {\n // `chalk` adds ANSI escape codes to the text, which are not visible\n // characters. We need to strip them to get the visible length of the\n // text.\n const visibleWord = stripAnsi(word);\n\n // Determine if a space should be added before the word.\n const spaceBeforeWord = index > 0 ? ' ' : '';\n const wordLengthWithSpace = visibleWord.length + spaceBeforeWord.length;\n\n // If the word would exceed the terminal width, start a new line.\n if (currentLineLength + wordLengthWithSpace > terminalWidth) {\n return {\n formattedText: `${formattedText}\\n${' '.repeat(indent)}${word}`,\n currentLineLength: indent + visibleWord.length,\n };\n }\n\n // Otherwise, add the word to the current line.\n return {\n formattedText: formattedText + spaceBeforeWord + word,\n currentLineLength: currentLineLength + wordLengthWithSpace,\n };\n },\n {\n formattedText: ' '.repeat(initialIndent),\n currentLineLength: initialIndent,\n },\n ).formattedText;\n}\n\n/**\n * Format the given text to fit within the terminal width.\n *\n * @param text - The text to format.\n * @param indent - The indentation to use.\n * @param initialIndent - The initial indentation to use, i.e., the indentation\n * for the first line.\n * @returns The formatted text.\n */\nexport function formatText(\n text: string,\n indent: number,\n initialIndent = indent,\n) {\n const lines = text.split('\\n');\n\n // Apply formatting to each line separately and then join them.\n return lines\n .map((line, index) => {\n const lineIndent = index === 0 ? initialIndent : indent;\n return formatLine(line, indent, lineIndent);\n })\n .join('\\n');\n}\n\n/**\n * Get an SVG from the given bytes and mime type.\n *\n * @param mimeType - The mime type of the image.\n * @param bytes - The image bytes.\n * @returns The SVG.\n */\nexport function getImageSVG(mimeType: string, bytes: Uint8Array) {\n const dataUrl = `data:${mimeType};base64,${bytesToBase64(bytes)}`;\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><image href=\"${dataUrl}\" /></svg>`;\n}\n"]}
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/webpack/utils.ts"],"names":[],"mappings":";;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,wBAAwB;;;AAEhD,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,WAAW;AACpC,OAAO,EAAE,cAAc,EAAE,eAAe;AAExC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa;AACxC,OAAO,UAAS,4BAAmB;;AAKnC,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAO,CACtC,OAAO,kBAAiB,kCAAkC,EAAE,EAC5D,iBAAiB,CAClB,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,MAAM,mBAAkB,SAAS,CAAC;IAClC,MAAM,mBAAkB,SAAS,CAAC;IAClC,OAAO,mBAAkB,oBAAoB,CAAC;IAC9C,SAAS,mBAAkB,sBAAsB,CAAC;IAClD,MAAM,mBAAkB,mBAAmB,CAAC;IAC5C,MAAM,mBAAkB,gBAAgB,CAAC;IACzC,MAA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CAA+C;QAC/C,OAAO;YACL,aAAa,EAAE,aAAa,GAAG,eAAe,GAAG,IAAI;YACrD,iBAAiB,EAAE,iBAAiB,GAAG,mBAAmB;SAC3D,CAAC;IACJ,CAAC,EACD;QACE,aAAa,EAAE,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC;QACxC,iBAAiB,EAAE,aAAa;KACjC,CACF,CAAC,aAAa,CAAC;AAClB,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,UAAU,CACxB,IAAY,EACZ,MAAc,EACd,aAAa,GAAG,MAAM;IAEtB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAE/B,+DAA+D;IAC/D,OAAO,KAAK;SACT,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QACnB,MAAM,UAAU,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC;QACxD,OAAO,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAC9C,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,QAAgB,EAAE,KAAiB;IAC7D,MAAM,OAAO,GAAG,QAAQ,QAAQ,WAAW,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;IAClE,OAAO,wDAAwD,OAAO,YAAY,CAAC;AACrF,CAAC","sourcesContent":["import { bytesToBase64 } from '@metamask/utils';\nimport { dim } from 'chalk';\nimport { promises as fs } from 'fs';\nimport { builtinModules } from 'module';\nimport type { Ora } from 'ora';\nimport { dirname, resolve } from 'path';\nimport stripAnsi from 'strip-ansi';\nimport type { Configuration } from 'webpack';\n\nimport type { ProcessedConfig } from '../config';\n\nexport const BROWSERSLIST_FILE = resolve(\n dirname(require.resolve('@metamask/snaps-cli/package.json')),\n '.browserslistrc',\n);\n\nexport const WEBPACK_FALLBACKS = {\n assert: require.resolve('assert/'),\n buffer: require.resolve('buffer/'),\n console: require.resolve('console-browserify'),\n constants: require.resolve('constants-browserify'),\n crypto: require.resolve('crypto-browserify'),\n domain: require.resolve('domain-browser'),\n events: require.resolve('events/'),\n http: require.resolve('stream-http'),\n https: require.resolve('https-browserify'),\n os: require.resolve('os-browserify/browser'),\n path: require.resolve('path-browserify'),\n punycode: require.resolve('punycode/'),\n process: require.resolve('process/browser'),\n querystring: require.resolve('querystring-es3'),\n stream: require.resolve('stream-browserify'),\n /* eslint-disable @typescript-eslint/naming-convention */\n _stream_duplex: require.resolve('readable-stream/lib/_stream_duplex'),\n _stream_passthrough: require.resolve(\n 'readable-stream/lib/_stream_passthrough',\n ),\n _stream_readable: require.resolve('readable-stream/lib/_stream_readable'),\n _stream_transform: require.resolve('readable-stream/lib/_stream_transform'),\n _stream_writable: require.resolve('readable-stream/lib/_stream_writable'),\n string_decoder: require.resolve('string_decoder/'),\n /* eslint-enable @typescript-eslint/naming-convention */\n sys: require.resolve('util/'),\n timers: require.resolve('timers-browserify'),\n tty: require.resolve('tty-browserify'),\n url: require.resolve('url/'),\n util: require.resolve('util/'),\n vm: require.resolve('vm-browserify'),\n zlib: require.resolve('browserify-zlib'),\n};\n\n/**\n * Get the default loader for JavaScript and TypeScript files, based on the\n * config object.\n *\n * We use the `swc-loader`, which is a Webpack loader that uses the `SWC`\n * compiler, a much faster alternative to Babel and TypeScript's own compiler.\n *\n * @param config - The processed snap Webpack config.\n * @param config.sourceMap - Whether to generate source maps.\n * @see https://swc.rs/docs/usage/swc-loader\n * @returns The default loader.\n */\nexport async function getDefaultLoader({ sourceMap }: ProcessedConfig) {\n const targets = await getBrowserslistTargets();\n return {\n /**\n * We use the `swc-loader` to transpile TypeScript and JavaScript files.\n * This is a Webpack loader that uses the `SWC` compiler, which is a much\n * faster alternative to Babel and TypeScript's own compiler.\n */\n loader: require.resolve('swc-loader'),\n\n /**\n * The options for the `swc-loader`. These can be overridden in the\n * `.swcrc` file.\n *\n * @see https://swc.rs/docs/configuration/swcrc\n */\n options: {\n sync: false,\n\n /**\n * This tells SWC to generate source maps. We set it to the\n * `sourceMap` value from the config object.\n *\n * This must be enabled if source maps are enabled in the config.\n */\n sourceMaps: Boolean(getDevTool(sourceMap)),\n\n jsc: {\n parser: {\n /**\n * This tells the parser to parse TypeScript files. If you\n * don't need to support TypeScript, you can set this to\n * `ecmascript` instead, but there's no harm in leaving it\n * as `typescript`.\n *\n * @see https://swc.rs/docs/configuration/compilation#jscparser\n */\n syntax: 'typescript',\n\n /**\n * This tells the parser to transpile JSX.\n *\n * @see https://swc.rs/docs/configuration/compilation#jscparser\n * @see https://swc.rs/docs/configuration/compilation#jscparserjsx\n */\n tsx: true,\n },\n\n transform: {\n react: {\n /**\n * This tells SWC to use the JSX runtime, instead of the\n * `createElement` function.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n runtime: 'automatic',\n\n /**\n * This tells SWC to import the JSX runtime from the\n * `@metamask/snaps-sdk` package, instead of the default React\n * package.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n importSource: '@metamask/snaps-sdk',\n\n /**\n * This tells SWC to use `Object.assign` and `Object.create` for\n * JSX spread attributes, instead of the default behavior.\n *\n * @see https://swc.rs/docs/configuration/compilation#jsctransformreact\n */\n useBuiltins: true,\n },\n },\n },\n\n /**\n * The module configuration. This tells SWC how to output the\n * transpiled code.\n *\n * @see https://swc.rs/docs/configuration/modules\n */\n module: {\n /**\n * This tells SWC to output ES6 modules. This will allow Webpack to\n * optimize the output code better. Snaps don't support ES6 however, so\n * the output code will be transpiled to CommonJS by Webpack later in\n * the build process.\n *\n * @see https://swc.rs/docs/configuration/modules#es6\n */\n type: 'es6',\n },\n\n env: {\n targets: targets.join(', '),\n },\n },\n };\n}\n\n/**\n * Get the Webpack devtool configuration based on the given snap config.\n *\n * - If `sourceMap` is `inline`, return `inline-source-map`.\n * - If `sourceMap` is `true`, return `source-map`.\n * - Otherwise, return `false`.\n *\n * @param sourceMap - The `sourceMap` value from the snap config.\n * @returns The Webpack devtool configuration.\n */\nexport function getDevTool(\n sourceMap: ProcessedConfig['sourceMap'],\n): Configuration['devtool'] {\n if (sourceMap === 'inline') {\n return 'inline-source-map';\n }\n\n if (sourceMap) {\n return 'source-map';\n }\n\n return false;\n}\n\n/**\n * Get a function that can be used as handler function for Webpack's\n * `ProgressPlugin`.\n *\n * @param spinner - The spinner to update.\n * @param spinnerText - The initial spinner text. This will be prepended to the\n * percentage.\n * @returns A function that can be used as handler function for Webpack's\n * `ProgressPlugin`.\n */\n// Note: This is extracted for testing purposes.\nexport function getProgressHandler(spinner?: Ora, spinnerText?: string) {\n return (percentage: number) => {\n if (spinner && spinnerText) {\n spinner.text = `${spinnerText} ${dim(\n `(${Math.round(percentage * 100)}%)`,\n )}`;\n }\n };\n}\n\n/**\n * Get the targets from the `.browserslistrc` file.\n *\n * @returns The browser targets as an array of strings.\n */\nexport async function getBrowserslistTargets() {\n const contents = await fs.readFile(BROWSERSLIST_FILE, 'utf8');\n return contents\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line && !line.startsWith('#'));\n}\n\n/**\n * Get a singular or plural string based on the given count. This is useful for\n * generating messages like \"1 error\" or \"2 errors\". By default, the plural\n * string is the singular string with an \"s\" appended to it.\n *\n * This assumes that the text is in English, and likely won't work for some\n * other languages.\n *\n * @param count - The count.\n * @param singular - The singular string.\n * @param plural - The plural string.\n * @returns The singular or plural string.\n * @example\n * ```typescript\n * pluralize(1, 'error'); // => 'error'\n * pluralize(2, 'error'); // => 'errors'\n * pluralize(1, 'error', 'problem'); // => 'error'\n * pluralize(2, 'error', 'problems'); // => 'problems'\n * ```\n */\nexport function pluralize(\n count: number,\n singular: string,\n plural = `${singular}s`,\n) {\n return count === 1 ? singular : plural;\n}\n\n/**\n * Get an object that can be used as fallback config for Webpack's\n * `fallback` config.\n *\n * @param polyfills - The polyfill object from the snap config.\n * @returns The webpack fallback config.\n */\nexport function getFallbacks(polyfills: ProcessedConfig['polyfills']): {\n [index: string]: string | false;\n} {\n if (polyfills === true) {\n return Object.fromEntries(\n builtinModules.map((name) => [\n name,\n WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS] ?? false,\n ]),\n );\n }\n\n if (polyfills === false) {\n return Object.fromEntries(builtinModules.map((name) => [name, false]));\n }\n\n return Object.fromEntries(\n builtinModules.map((name) => [\n name,\n polyfills[name as keyof ProcessedConfig['polyfills']]\n ? WEBPACK_FALLBACKS[name as keyof typeof WEBPACK_FALLBACKS]\n : false,\n ]),\n );\n}\n\n/**\n * Get an object that can be used as environment variables for Webpack's\n * `DefinePlugin`.\n *\n * @param environment - The environment object from the Snap config.\n * @param defaults - The default environment variables.\n * @returns The Webpack environment variables.\n */\nexport function getEnvironmentVariables(\n environment: Record<string, unknown>,\n defaults = {\n NODE_DEBUG: 'false',\n NODE_ENV: 'production',\n DEBUG: 'false',\n },\n) {\n return Object.fromEntries(\n Object.entries({\n ...defaults,\n ...environment,\n }).map(([key, value]) => [`process.env.${key}`, JSON.stringify(value)]),\n );\n}\n\n/**\n * Format the given line to fit within the terminal width.\n *\n * @param line - The line to format.\n * @param indent - The indentation to use.\n * @param initialIndent - The initial indentation to use, i.e., the indentation\n * for the first line.\n * @returns The formatted line.\n */\nfunction formatLine(line: string, indent: number, initialIndent: number) {\n const terminalWidth = process.stdout.columns;\n if (!terminalWidth) {\n return `${' '.repeat(initialIndent)}${line}`;\n }\n\n return line.split(' ').reduce(\n ({ formattedText, currentLineLength }, word, index) => {\n // `chalk` adds ANSI escape codes to the text, which are not visible\n // characters. We need to strip them to get the visible length of the\n // text.\n const visibleWord = stripAnsi(word);\n\n // Determine if a space should be added before the word.\n const spaceBeforeWord = index > 0 ? ' ' : '';\n const wordLengthWithSpace = visibleWord.length + spaceBeforeWord.length;\n\n // If the word would exceed the terminal width, start a new line.\n if (currentLineLength + wordLengthWithSpace > terminalWidth) {\n return {\n formattedText: `${formattedText}\\n${' '.repeat(indent)}${word}`,\n currentLineLength: indent + visibleWord.length,\n };\n }\n\n // Otherwise, add the word to the current line.\n return {\n formattedText: formattedText + spaceBeforeWord + word,\n currentLineLength: currentLineLength + wordLengthWithSpace,\n };\n },\n {\n formattedText: ' '.repeat(initialIndent),\n currentLineLength: initialIndent,\n },\n ).formattedText;\n}\n\n/**\n * Format the given text to fit within the terminal width.\n *\n * @param text - The text to format.\n * @param indent - The indentation to use.\n * @param initialIndent - The initial indentation to use, i.e., the indentation\n * for the first line.\n * @returns The formatted text.\n */\nexport function formatText(\n text: string,\n indent: number,\n initialIndent = indent,\n) {\n const lines = text.split('\\n');\n\n // Apply formatting to each line separately and then join them.\n return lines\n .map((line, index) => {\n const lineIndent = index === 0 ? initialIndent : indent;\n return formatLine(line, indent, lineIndent);\n })\n .join('\\n');\n}\n\n/**\n * Get an SVG from the given bytes and mime type.\n *\n * @param mimeType - The mime type of the image.\n * @param bytes - The image bytes.\n * @returns The SVG.\n */\nexport function getImageSVG(mimeType: string, bytes: Uint8Array) {\n const dataUrl = `data:${mimeType};base64,${bytesToBase64(bytes)}`;\n return `<svg xmlns=\"http://www.w3.org/2000/svg\"><image href=\"${dataUrl}\" /></svg>`;\n}\n"]}