normalization.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. /** @typedef {import("../../declarations/WebpackOptions").EntryStatic} EntryStatic */
  8. /** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */
  9. /** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
  10. /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
  11. /** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */
  12. /** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */
  13. /** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */
  14. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
  15. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */
  16. const handledDeprecatedNoEmitOnErrors = util.deprecate(
  17. (noEmitOnErrors, emitOnErrors) => {
  18. if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) {
  19. throw new Error(
  20. "Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config."
  21. );
  22. }
  23. return !noEmitOnErrors;
  24. },
  25. "optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors",
  26. "DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS"
  27. );
  28. /**
  29. * @template T
  30. * @template R
  31. * @param {T|undefined} value value or not
  32. * @param {function(T): R} fn nested handler
  33. * @returns {R} result value
  34. */
  35. const nestedConfig = (value, fn) =>
  36. value === undefined ? fn(/** @type {T} */ ({})) : fn(value);
  37. /**
  38. * @template T
  39. * @param {T|undefined} value value or not
  40. * @returns {T} result value
  41. */
  42. const cloneObject = value => {
  43. return /** @type {T} */ ({ ...value });
  44. };
  45. /**
  46. * @template T
  47. * @template R
  48. * @param {T|undefined} value value or not
  49. * @param {function(T): R} fn nested handler
  50. * @returns {R|undefined} result value
  51. */
  52. const optionalNestedConfig = (value, fn) =>
  53. value === undefined ? undefined : fn(value);
  54. /**
  55. * @template T
  56. * @template R
  57. * @param {T[]|undefined} value array or not
  58. * @param {function(T[]): R[]} fn nested handler
  59. * @returns {R[]|undefined} cloned value
  60. */
  61. const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([]));
  62. /**
  63. * @template T
  64. * @template R
  65. * @param {T[]|undefined} value array or not
  66. * @param {function(T[]): R[]} fn nested handler
  67. * @returns {R[]|undefined} cloned value
  68. */
  69. const optionalNestedArray = (value, fn) =>
  70. Array.isArray(value) ? fn(value) : undefined;
  71. /**
  72. * @template T
  73. * @template R
  74. * @param {Record<string, T>|undefined} value value or not
  75. * @param {function(T): R} fn nested handler
  76. * @param {Record<string, function(T): R>=} customKeys custom nested handler for some keys
  77. * @returns {Record<string, R>} result value
  78. */
  79. const keyedNestedConfig = (value, fn, customKeys) => {
  80. const result =
  81. value === undefined
  82. ? {}
  83. : Object.keys(value).reduce(
  84. (obj, key) => (
  85. (obj[key] = (
  86. customKeys && key in customKeys ? customKeys[key] : fn
  87. )(value[key])),
  88. obj
  89. ),
  90. /** @type {Record<string, R>} */ ({})
  91. );
  92. if (customKeys) {
  93. for (const key of Object.keys(customKeys)) {
  94. if (!(key in result)) {
  95. result[key] = customKeys[key](/** @type {T} */ ({}));
  96. }
  97. }
  98. }
  99. return result;
  100. };
  101. /**
  102. * @param {WebpackOptions} config input config
  103. * @returns {WebpackOptionsNormalized} normalized options
  104. */
  105. const getNormalizedWebpackOptions = config => {
  106. return {
  107. amd: config.amd,
  108. bail: config.bail,
  109. cache: optionalNestedConfig(config.cache, cache => {
  110. if (cache === false) return false;
  111. if (cache === true) {
  112. return {
  113. type: "memory",
  114. maxGenerations: undefined
  115. };
  116. }
  117. switch (cache.type) {
  118. case "filesystem":
  119. return {
  120. type: "filesystem",
  121. allowCollectingMemory: cache.allowCollectingMemory,
  122. maxMemoryGenerations: cache.maxMemoryGenerations,
  123. maxAge: cache.maxAge,
  124. profile: cache.profile,
  125. buildDependencies: cloneObject(cache.buildDependencies),
  126. cacheDirectory: cache.cacheDirectory,
  127. cacheLocation: cache.cacheLocation,
  128. hashAlgorithm: cache.hashAlgorithm,
  129. compression: cache.compression,
  130. idleTimeout: cache.idleTimeout,
  131. idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore,
  132. idleTimeoutAfterLargeChanges: cache.idleTimeoutAfterLargeChanges,
  133. name: cache.name,
  134. store: cache.store,
  135. version: cache.version
  136. };
  137. case undefined:
  138. case "memory":
  139. return {
  140. type: "memory",
  141. maxGenerations: cache.maxGenerations
  142. };
  143. default:
  144. // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339)
  145. throw new Error(`Not implemented cache.type ${cache.type}`);
  146. }
  147. }),
  148. context: config.context,
  149. dependencies: config.dependencies,
  150. devServer: optionalNestedConfig(config.devServer, devServer => ({
  151. ...devServer
  152. })),
  153. devtool: config.devtool,
  154. entry:
  155. config.entry === undefined
  156. ? { main: {} }
  157. : typeof config.entry === "function"
  158. ? (
  159. fn => () =>
  160. Promise.resolve().then(fn).then(getNormalizedEntryStatic)
  161. )(config.entry)
  162. : getNormalizedEntryStatic(config.entry),
  163. experiments: nestedConfig(config.experiments, experiments => ({
  164. ...experiments,
  165. buildHttp: optionalNestedConfig(experiments.buildHttp, options =>
  166. Array.isArray(options) ? { allowedUris: options } : options
  167. ),
  168. lazyCompilation: optionalNestedConfig(
  169. experiments.lazyCompilation,
  170. options =>
  171. options === true ? {} : options === false ? undefined : options
  172. ),
  173. css: optionalNestedConfig(experiments.css, options =>
  174. options === true ? {} : options === false ? undefined : options
  175. )
  176. })),
  177. externals: config.externals,
  178. externalsPresets: cloneObject(config.externalsPresets),
  179. externalsType: config.externalsType,
  180. ignoreWarnings: config.ignoreWarnings
  181. ? config.ignoreWarnings.map(ignore => {
  182. if (typeof ignore === "function") return ignore;
  183. const i = ignore instanceof RegExp ? { message: ignore } : ignore;
  184. return (warning, { requestShortener }) => {
  185. if (!i.message && !i.module && !i.file) return false;
  186. if (i.message && !i.message.test(warning.message)) {
  187. return false;
  188. }
  189. if (
  190. i.module &&
  191. (!warning.module ||
  192. !i.module.test(
  193. warning.module.readableIdentifier(requestShortener)
  194. ))
  195. ) {
  196. return false;
  197. }
  198. if (i.file && (!warning.file || !i.file.test(warning.file))) {
  199. return false;
  200. }
  201. return true;
  202. };
  203. })
  204. : undefined,
  205. infrastructureLogging: cloneObject(config.infrastructureLogging),
  206. loader: cloneObject(config.loader),
  207. mode: config.mode,
  208. module: nestedConfig(config.module, module => ({
  209. noParse: module.noParse,
  210. unsafeCache: module.unsafeCache,
  211. parser: keyedNestedConfig(module.parser, cloneObject, {
  212. javascript: parserOptions => ({
  213. unknownContextRequest: module.unknownContextRequest,
  214. unknownContextRegExp: module.unknownContextRegExp,
  215. unknownContextRecursive: module.unknownContextRecursive,
  216. unknownContextCritical: module.unknownContextCritical,
  217. exprContextRequest: module.exprContextRequest,
  218. exprContextRegExp: module.exprContextRegExp,
  219. exprContextRecursive: module.exprContextRecursive,
  220. exprContextCritical: module.exprContextCritical,
  221. wrappedContextRegExp: module.wrappedContextRegExp,
  222. wrappedContextRecursive: module.wrappedContextRecursive,
  223. wrappedContextCritical: module.wrappedContextCritical,
  224. // TODO webpack 6 remove
  225. strictExportPresence: module.strictExportPresence,
  226. strictThisContextOnImports: module.strictThisContextOnImports,
  227. ...parserOptions
  228. })
  229. }),
  230. generator: cloneObject(module.generator),
  231. defaultRules: optionalNestedArray(module.defaultRules, r => [...r]),
  232. rules: nestedArray(module.rules, r => [...r])
  233. })),
  234. name: config.name,
  235. node: nestedConfig(
  236. config.node,
  237. node =>
  238. node && {
  239. ...node
  240. }
  241. ),
  242. optimization: nestedConfig(config.optimization, optimization => {
  243. return {
  244. ...optimization,
  245. runtimeChunk: getNormalizedOptimizationRuntimeChunk(
  246. optimization.runtimeChunk
  247. ),
  248. splitChunks: nestedConfig(
  249. optimization.splitChunks,
  250. splitChunks =>
  251. splitChunks && {
  252. ...splitChunks,
  253. defaultSizeTypes: splitChunks.defaultSizeTypes
  254. ? [...splitChunks.defaultSizeTypes]
  255. : ["..."],
  256. cacheGroups: cloneObject(splitChunks.cacheGroups)
  257. }
  258. ),
  259. emitOnErrors:
  260. optimization.noEmitOnErrors !== undefined
  261. ? handledDeprecatedNoEmitOnErrors(
  262. optimization.noEmitOnErrors,
  263. optimization.emitOnErrors
  264. )
  265. : optimization.emitOnErrors
  266. };
  267. }),
  268. output: nestedConfig(config.output, output => {
  269. const { library } = output;
  270. const libraryAsName = /** @type {LibraryName} */ (library);
  271. const libraryBase =
  272. typeof library === "object" &&
  273. library &&
  274. !Array.isArray(library) &&
  275. "type" in library
  276. ? library
  277. : libraryAsName || output.libraryTarget
  278. ? /** @type {LibraryOptions} */ ({
  279. name: libraryAsName
  280. })
  281. : undefined;
  282. /** @type {OutputNormalized} */
  283. const result = {
  284. assetModuleFilename: output.assetModuleFilename,
  285. asyncChunks: output.asyncChunks,
  286. charset: output.charset,
  287. chunkFilename: output.chunkFilename,
  288. chunkFormat: output.chunkFormat,
  289. chunkLoading: output.chunkLoading,
  290. chunkLoadingGlobal: output.chunkLoadingGlobal,
  291. chunkLoadTimeout: output.chunkLoadTimeout,
  292. cssFilename: output.cssFilename,
  293. cssChunkFilename: output.cssChunkFilename,
  294. clean: output.clean,
  295. compareBeforeEmit: output.compareBeforeEmit,
  296. crossOriginLoading: output.crossOriginLoading,
  297. devtoolFallbackModuleFilenameTemplate:
  298. output.devtoolFallbackModuleFilenameTemplate,
  299. devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate,
  300. devtoolNamespace: output.devtoolNamespace,
  301. environment: cloneObject(output.environment),
  302. enabledChunkLoadingTypes: output.enabledChunkLoadingTypes
  303. ? [...output.enabledChunkLoadingTypes]
  304. : ["..."],
  305. enabledLibraryTypes: output.enabledLibraryTypes
  306. ? [...output.enabledLibraryTypes]
  307. : ["..."],
  308. enabledWasmLoadingTypes: output.enabledWasmLoadingTypes
  309. ? [...output.enabledWasmLoadingTypes]
  310. : ["..."],
  311. filename: output.filename,
  312. globalObject: output.globalObject,
  313. hashDigest: output.hashDigest,
  314. hashDigestLength: output.hashDigestLength,
  315. hashFunction: output.hashFunction,
  316. hashSalt: output.hashSalt,
  317. hotUpdateChunkFilename: output.hotUpdateChunkFilename,
  318. hotUpdateGlobal: output.hotUpdateGlobal,
  319. hotUpdateMainFilename: output.hotUpdateMainFilename,
  320. iife: output.iife,
  321. importFunctionName: output.importFunctionName,
  322. importMetaName: output.importMetaName,
  323. scriptType: output.scriptType,
  324. library: libraryBase && {
  325. type:
  326. output.libraryTarget !== undefined
  327. ? output.libraryTarget
  328. : libraryBase.type,
  329. auxiliaryComment:
  330. output.auxiliaryComment !== undefined
  331. ? output.auxiliaryComment
  332. : libraryBase.auxiliaryComment,
  333. export:
  334. output.libraryExport !== undefined
  335. ? output.libraryExport
  336. : libraryBase.export,
  337. name: libraryBase.name,
  338. umdNamedDefine:
  339. output.umdNamedDefine !== undefined
  340. ? output.umdNamedDefine
  341. : libraryBase.umdNamedDefine
  342. },
  343. module: output.module,
  344. path: output.path,
  345. pathinfo: output.pathinfo,
  346. publicPath: output.publicPath,
  347. sourceMapFilename: output.sourceMapFilename,
  348. sourcePrefix: output.sourcePrefix,
  349. strictModuleExceptionHandling: output.strictModuleExceptionHandling,
  350. trustedTypes: optionalNestedConfig(
  351. output.trustedTypes,
  352. trustedTypes => {
  353. if (trustedTypes === true) return {};
  354. if (typeof trustedTypes === "string")
  355. return { policyName: trustedTypes };
  356. return { ...trustedTypes };
  357. }
  358. ),
  359. uniqueName: output.uniqueName,
  360. wasmLoading: output.wasmLoading,
  361. webassemblyModuleFilename: output.webassemblyModuleFilename,
  362. workerChunkLoading: output.workerChunkLoading,
  363. workerWasmLoading: output.workerWasmLoading
  364. };
  365. return result;
  366. }),
  367. parallelism: config.parallelism,
  368. performance: optionalNestedConfig(config.performance, performance => {
  369. if (performance === false) return false;
  370. return {
  371. ...performance
  372. };
  373. }),
  374. plugins: nestedArray(config.plugins, p => [...p]),
  375. profile: config.profile,
  376. recordsInputPath:
  377. config.recordsInputPath !== undefined
  378. ? config.recordsInputPath
  379. : config.recordsPath,
  380. recordsOutputPath:
  381. config.recordsOutputPath !== undefined
  382. ? config.recordsOutputPath
  383. : config.recordsPath,
  384. resolve: nestedConfig(config.resolve, resolve => ({
  385. ...resolve,
  386. byDependency: keyedNestedConfig(resolve.byDependency, cloneObject)
  387. })),
  388. resolveLoader: cloneObject(config.resolveLoader),
  389. snapshot: nestedConfig(config.snapshot, snapshot => ({
  390. resolveBuildDependencies: optionalNestedConfig(
  391. snapshot.resolveBuildDependencies,
  392. resolveBuildDependencies => ({
  393. timestamp: resolveBuildDependencies.timestamp,
  394. hash: resolveBuildDependencies.hash
  395. })
  396. ),
  397. buildDependencies: optionalNestedConfig(
  398. snapshot.buildDependencies,
  399. buildDependencies => ({
  400. timestamp: buildDependencies.timestamp,
  401. hash: buildDependencies.hash
  402. })
  403. ),
  404. resolve: optionalNestedConfig(snapshot.resolve, resolve => ({
  405. timestamp: resolve.timestamp,
  406. hash: resolve.hash
  407. })),
  408. module: optionalNestedConfig(snapshot.module, module => ({
  409. timestamp: module.timestamp,
  410. hash: module.hash
  411. })),
  412. immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]),
  413. managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p])
  414. })),
  415. stats: nestedConfig(config.stats, stats => {
  416. if (stats === false) {
  417. return {
  418. preset: "none"
  419. };
  420. }
  421. if (stats === true) {
  422. return {
  423. preset: "normal"
  424. };
  425. }
  426. if (typeof stats === "string") {
  427. return {
  428. preset: stats
  429. };
  430. }
  431. return {
  432. ...stats
  433. };
  434. }),
  435. target: config.target,
  436. watch: config.watch,
  437. watchOptions: cloneObject(config.watchOptions)
  438. };
  439. };
  440. /**
  441. * @param {EntryStatic} entry static entry options
  442. * @returns {EntryStaticNormalized} normalized static entry options
  443. */
  444. const getNormalizedEntryStatic = entry => {
  445. if (typeof entry === "string") {
  446. return {
  447. main: {
  448. import: [entry]
  449. }
  450. };
  451. }
  452. if (Array.isArray(entry)) {
  453. return {
  454. main: {
  455. import: entry
  456. }
  457. };
  458. }
  459. /** @type {EntryStaticNormalized} */
  460. const result = {};
  461. for (const key of Object.keys(entry)) {
  462. const value = entry[key];
  463. if (typeof value === "string") {
  464. result[key] = {
  465. import: [value]
  466. };
  467. } else if (Array.isArray(value)) {
  468. result[key] = {
  469. import: value
  470. };
  471. } else {
  472. result[key] = {
  473. import:
  474. value.import &&
  475. (Array.isArray(value.import) ? value.import : [value.import]),
  476. filename: value.filename,
  477. layer: value.layer,
  478. runtime: value.runtime,
  479. baseUri: value.baseUri,
  480. publicPath: value.publicPath,
  481. chunkLoading: value.chunkLoading,
  482. asyncChunks: value.asyncChunks,
  483. wasmLoading: value.wasmLoading,
  484. dependOn:
  485. value.dependOn &&
  486. (Array.isArray(value.dependOn) ? value.dependOn : [value.dependOn]),
  487. library: value.library
  488. };
  489. }
  490. }
  491. return result;
  492. };
  493. /**
  494. * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
  495. * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
  496. */
  497. const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
  498. if (runtimeChunk === undefined) return undefined;
  499. if (runtimeChunk === false) return false;
  500. if (runtimeChunk === "single") {
  501. return {
  502. name: () => "runtime"
  503. };
  504. }
  505. if (runtimeChunk === true || runtimeChunk === "multiple") {
  506. return {
  507. name: entrypoint => `runtime~${entrypoint.name}`
  508. };
  509. }
  510. const { name } = runtimeChunk;
  511. return {
  512. name: typeof name === "function" ? name : () => name
  513. };
  514. };
  515. exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions;