normalization.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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(
  378. output.trustedTypes,
  379. (trustedTypes) => {
  380. if (trustedTypes === true) return {};
  381. if (typeof trustedTypes === "string") {
  382. return { policyName: trustedTypes };
  383. }
  384. return { ...trustedTypes };
  385. }
  386. ),
  387. uniqueName: output.uniqueName,
  388. wasmLoading: output.wasmLoading,
  389. webassemblyModuleFilename: output.webassemblyModuleFilename,
  390. workerPublicPath: output.workerPublicPath,
  391. workerChunkLoading: output.workerChunkLoading,
  392. workerWasmLoading: output.workerWasmLoading
  393. };
  394. return result;
  395. }),
  396. parallelism: config.parallelism,
  397. performance: optionalNestedConfig(config.performance, (performance) => {
  398. if (performance === false) return false;
  399. return {
  400. ...performance
  401. };
  402. }),
  403. plugins: /** @type {Plugins} */ (nestedArray(config.plugins, (p) => [...p])),
  404. profile: config.profile,
  405. recordsInputPath:
  406. config.recordsInputPath !== undefined
  407. ? config.recordsInputPath
  408. : config.recordsPath,
  409. recordsOutputPath:
  410. config.recordsOutputPath !== undefined
  411. ? config.recordsOutputPath
  412. : config.recordsPath,
  413. resolve: nestedConfig(config.resolve, (resolve) => ({
  414. ...resolve,
  415. byDependency: keyedNestedConfig(resolve.byDependency, cloneObject)
  416. })),
  417. resolveLoader: cloneObject(config.resolveLoader),
  418. snapshot: nestedConfig(config.snapshot, (snapshot) => ({
  419. resolveBuildDependencies: optionalNestedConfig(
  420. snapshot.resolveBuildDependencies,
  421. (resolveBuildDependencies) => ({
  422. timestamp: resolveBuildDependencies.timestamp,
  423. hash: resolveBuildDependencies.hash
  424. })
  425. ),
  426. buildDependencies: optionalNestedConfig(
  427. snapshot.buildDependencies,
  428. (buildDependencies) => ({
  429. timestamp: buildDependencies.timestamp,
  430. hash: buildDependencies.hash
  431. })
  432. ),
  433. resolve: optionalNestedConfig(snapshot.resolve, (resolve) => ({
  434. timestamp: resolve.timestamp,
  435. hash: resolve.hash
  436. })),
  437. module: optionalNestedConfig(snapshot.module, (module) => ({
  438. timestamp: module.timestamp,
  439. hash: module.hash
  440. })),
  441. immutablePaths: optionalNestedArray(snapshot.immutablePaths, (p) => [...p]),
  442. managedPaths: optionalNestedArray(snapshot.managedPaths, (p) => [...p]),
  443. unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, (p) => [...p])
  444. })),
  445. stats: nestedConfig(config.stats, (stats) => {
  446. if (stats === false) {
  447. return {
  448. preset: "none"
  449. };
  450. }
  451. if (stats === true) {
  452. return {
  453. preset: "normal"
  454. };
  455. }
  456. if (typeof stats === "string") {
  457. return {
  458. preset: stats
  459. };
  460. }
  461. return {
  462. ...stats
  463. };
  464. }),
  465. target: config.target,
  466. watch: config.watch,
  467. watchOptions: cloneObject(config.watchOptions)
  468. });
  469. /**
  470. * @param {EntryStatic} entry static entry options
  471. * @returns {EntryStaticNormalized} normalized static entry options
  472. */
  473. const getNormalizedEntryStatic = (entry) => {
  474. if (typeof entry === "string") {
  475. return {
  476. main: {
  477. import: [entry]
  478. }
  479. };
  480. }
  481. if (Array.isArray(entry)) {
  482. return {
  483. main: {
  484. import: entry
  485. }
  486. };
  487. }
  488. /** @type {EntryStaticNormalized} */
  489. const result = {};
  490. for (const key of Object.keys(entry)) {
  491. const value = entry[key];
  492. if (typeof value === "string") {
  493. result[key] = {
  494. import: [value]
  495. };
  496. } else if (Array.isArray(value)) {
  497. result[key] = {
  498. import: value
  499. };
  500. } else {
  501. result[key] = {
  502. import:
  503. /** @type {EntryDescriptionNormalized["import"]} */
  504. (
  505. value.import &&
  506. (Array.isArray(value.import) ? value.import : [value.import])
  507. ),
  508. filename: value.filename,
  509. layer: value.layer,
  510. runtime: value.runtime,
  511. baseUri: value.baseUri,
  512. publicPath: value.publicPath,
  513. chunkLoading: value.chunkLoading,
  514. asyncChunks: value.asyncChunks,
  515. wasmLoading: value.wasmLoading,
  516. dependOn:
  517. /** @type {EntryDescriptionNormalized["dependOn"]} */
  518. (
  519. value.dependOn &&
  520. (Array.isArray(value.dependOn)
  521. ? value.dependOn
  522. : [value.dependOn])
  523. ),
  524. library: value.library
  525. };
  526. }
  527. }
  528. return result;
  529. };
  530. /**
  531. * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
  532. * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
  533. */
  534. const getNormalizedOptimizationRuntimeChunk = (runtimeChunk) => {
  535. if (runtimeChunk === undefined) return;
  536. if (runtimeChunk === false) return false;
  537. if (runtimeChunk === "single") {
  538. return {
  539. name: () => "runtime"
  540. };
  541. }
  542. if (runtimeChunk === true || runtimeChunk === "multiple") {
  543. return {
  544. name: (entrypoint) => `runtime~${entrypoint.name}`
  545. };
  546. }
  547. const { name } = runtimeChunk;
  548. return {
  549. name:
  550. typeof name === "function"
  551. ? /** @type {Exclude<OptimizationRuntimeChunkNormalized, false>["name"]} */
  552. (name)
  553. : () => /** @type {string} */ (name)
  554. };
  555. };
  556. module.exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions;