normalization.js 18 KB

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