normalization.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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 => (options === true ? {} : options)
  171. ),
  172. css: optionalNestedConfig(experiments.css, options =>
  173. options === true ? {} : options
  174. )
  175. })),
  176. externals: config.externals,
  177. externalsPresets: cloneObject(config.externalsPresets),
  178. externalsType: config.externalsType,
  179. ignoreWarnings: config.ignoreWarnings
  180. ? config.ignoreWarnings.map(ignore => {
  181. if (typeof ignore === "function") return ignore;
  182. const i = ignore instanceof RegExp ? { message: ignore } : ignore;
  183. return (warning, { requestShortener }) => {
  184. if (!i.message && !i.module && !i.file) return false;
  185. if (i.message && !i.message.test(warning.message)) {
  186. return false;
  187. }
  188. if (
  189. i.module &&
  190. (!warning.module ||
  191. !i.module.test(
  192. warning.module.readableIdentifier(requestShortener)
  193. ))
  194. ) {
  195. return false;
  196. }
  197. if (i.file && (!warning.file || !i.file.test(warning.file))) {
  198. return false;
  199. }
  200. return true;
  201. };
  202. })
  203. : undefined,
  204. infrastructureLogging: cloneObject(config.infrastructureLogging),
  205. loader: cloneObject(config.loader),
  206. mode: config.mode,
  207. module: nestedConfig(config.module, module => ({
  208. noParse: module.noParse,
  209. unsafeCache: module.unsafeCache,
  210. parser: keyedNestedConfig(module.parser, cloneObject, {
  211. javascript: parserOptions => ({
  212. unknownContextRequest: module.unknownContextRequest,
  213. unknownContextRegExp: module.unknownContextRegExp,
  214. unknownContextRecursive: module.unknownContextRecursive,
  215. unknownContextCritical: module.unknownContextCritical,
  216. exprContextRequest: module.exprContextRequest,
  217. exprContextRegExp: module.exprContextRegExp,
  218. exprContextRecursive: module.exprContextRecursive,
  219. exprContextCritical: module.exprContextCritical,
  220. wrappedContextRegExp: module.wrappedContextRegExp,
  221. wrappedContextRecursive: module.wrappedContextRecursive,
  222. wrappedContextCritical: module.wrappedContextCritical,
  223. // TODO webpack 6 remove
  224. strictExportPresence: module.strictExportPresence,
  225. strictThisContextOnImports: module.strictThisContextOnImports,
  226. ...parserOptions
  227. })
  228. }),
  229. generator: cloneObject(module.generator),
  230. defaultRules: optionalNestedArray(module.defaultRules, r => [...r]),
  231. rules: nestedArray(module.rules, r => [...r])
  232. })),
  233. name: config.name,
  234. node: nestedConfig(
  235. config.node,
  236. node =>
  237. node && {
  238. ...node
  239. }
  240. ),
  241. optimization: nestedConfig(config.optimization, optimization => {
  242. return {
  243. ...optimization,
  244. runtimeChunk: getNormalizedOptimizationRuntimeChunk(
  245. optimization.runtimeChunk
  246. ),
  247. splitChunks: nestedConfig(
  248. optimization.splitChunks,
  249. splitChunks =>
  250. splitChunks && {
  251. ...splitChunks,
  252. defaultSizeTypes: splitChunks.defaultSizeTypes
  253. ? [...splitChunks.defaultSizeTypes]
  254. : ["..."],
  255. cacheGroups: cloneObject(splitChunks.cacheGroups)
  256. }
  257. ),
  258. emitOnErrors:
  259. optimization.noEmitOnErrors !== undefined
  260. ? handledDeprecatedNoEmitOnErrors(
  261. optimization.noEmitOnErrors,
  262. optimization.emitOnErrors
  263. )
  264. : optimization.emitOnErrors
  265. };
  266. }),
  267. output: nestedConfig(config.output, output => {
  268. const { library } = output;
  269. const libraryAsName = /** @type {LibraryName} */ (library);
  270. const libraryBase =
  271. typeof library === "object" &&
  272. library &&
  273. !Array.isArray(library) &&
  274. "type" in library
  275. ? library
  276. : libraryAsName || output.libraryTarget
  277. ? /** @type {LibraryOptions} */ ({
  278. name: libraryAsName
  279. })
  280. : undefined;
  281. /** @type {OutputNormalized} */
  282. const result = {
  283. assetModuleFilename: output.assetModuleFilename,
  284. asyncChunks: output.asyncChunks,
  285. charset: output.charset,
  286. chunkFilename: output.chunkFilename,
  287. chunkFormat: output.chunkFormat,
  288. chunkLoading: output.chunkLoading,
  289. chunkLoadingGlobal: output.chunkLoadingGlobal,
  290. chunkLoadTimeout: output.chunkLoadTimeout,
  291. cssFilename: output.cssFilename,
  292. cssChunkFilename: output.cssChunkFilename,
  293. clean: output.clean,
  294. compareBeforeEmit: output.compareBeforeEmit,
  295. crossOriginLoading: output.crossOriginLoading,
  296. devtoolFallbackModuleFilenameTemplate:
  297. output.devtoolFallbackModuleFilenameTemplate,
  298. devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate,
  299. devtoolNamespace: output.devtoolNamespace,
  300. environment: cloneObject(output.environment),
  301. enabledChunkLoadingTypes: output.enabledChunkLoadingTypes
  302. ? [...output.enabledChunkLoadingTypes]
  303. : ["..."],
  304. enabledLibraryTypes: output.enabledLibraryTypes
  305. ? [...output.enabledLibraryTypes]
  306. : ["..."],
  307. enabledWasmLoadingTypes: output.enabledWasmLoadingTypes
  308. ? [...output.enabledWasmLoadingTypes]
  309. : ["..."],
  310. filename: output.filename,
  311. globalObject: output.globalObject,
  312. hashDigest: output.hashDigest,
  313. hashDigestLength: output.hashDigestLength,
  314. hashFunction: output.hashFunction,
  315. hashSalt: output.hashSalt,
  316. hotUpdateChunkFilename: output.hotUpdateChunkFilename,
  317. hotUpdateGlobal: output.hotUpdateGlobal,
  318. hotUpdateMainFilename: output.hotUpdateMainFilename,
  319. iife: output.iife,
  320. importFunctionName: output.importFunctionName,
  321. importMetaName: output.importMetaName,
  322. scriptType: output.scriptType,
  323. library: libraryBase && {
  324. type:
  325. output.libraryTarget !== undefined
  326. ? output.libraryTarget
  327. : libraryBase.type,
  328. auxiliaryComment:
  329. output.auxiliaryComment !== undefined
  330. ? output.auxiliaryComment
  331. : libraryBase.auxiliaryComment,
  332. amdContainer:
  333. output.amdContainer !== undefined
  334. ? output.amdContainer
  335. : libraryBase.amdContainer,
  336. export:
  337. output.libraryExport !== undefined
  338. ? output.libraryExport
  339. : libraryBase.export,
  340. name: libraryBase.name,
  341. umdNamedDefine:
  342. output.umdNamedDefine !== undefined
  343. ? output.umdNamedDefine
  344. : libraryBase.umdNamedDefine
  345. },
  346. module: output.module,
  347. path: output.path,
  348. pathinfo: output.pathinfo,
  349. publicPath: output.publicPath,
  350. sourceMapFilename: output.sourceMapFilename,
  351. sourcePrefix: output.sourcePrefix,
  352. strictModuleExceptionHandling: output.strictModuleExceptionHandling,
  353. trustedTypes: optionalNestedConfig(
  354. output.trustedTypes,
  355. trustedTypes => {
  356. if (trustedTypes === true) return {};
  357. if (typeof trustedTypes === "string")
  358. return { policyName: trustedTypes };
  359. return { ...trustedTypes };
  360. }
  361. ),
  362. uniqueName: output.uniqueName,
  363. wasmLoading: output.wasmLoading,
  364. webassemblyModuleFilename: output.webassemblyModuleFilename,
  365. workerPublicPath: output.workerPublicPath,
  366. workerChunkLoading: output.workerChunkLoading,
  367. workerWasmLoading: output.workerWasmLoading
  368. };
  369. return result;
  370. }),
  371. parallelism: config.parallelism,
  372. performance: optionalNestedConfig(config.performance, performance => {
  373. if (performance === false) return false;
  374. return {
  375. ...performance
  376. };
  377. }),
  378. plugins: nestedArray(config.plugins, p => [...p]),
  379. profile: config.profile,
  380. recordsInputPath:
  381. config.recordsInputPath !== undefined
  382. ? config.recordsInputPath
  383. : config.recordsPath,
  384. recordsOutputPath:
  385. config.recordsOutputPath !== undefined
  386. ? config.recordsOutputPath
  387. : config.recordsPath,
  388. resolve: nestedConfig(config.resolve, resolve => ({
  389. ...resolve,
  390. byDependency: keyedNestedConfig(resolve.byDependency, cloneObject)
  391. })),
  392. resolveLoader: cloneObject(config.resolveLoader),
  393. snapshot: nestedConfig(config.snapshot, snapshot => ({
  394. resolveBuildDependencies: optionalNestedConfig(
  395. snapshot.resolveBuildDependencies,
  396. resolveBuildDependencies => ({
  397. timestamp: resolveBuildDependencies.timestamp,
  398. hash: resolveBuildDependencies.hash
  399. })
  400. ),
  401. buildDependencies: optionalNestedConfig(
  402. snapshot.buildDependencies,
  403. buildDependencies => ({
  404. timestamp: buildDependencies.timestamp,
  405. hash: buildDependencies.hash
  406. })
  407. ),
  408. resolve: optionalNestedConfig(snapshot.resolve, resolve => ({
  409. timestamp: resolve.timestamp,
  410. hash: resolve.hash
  411. })),
  412. module: optionalNestedConfig(snapshot.module, module => ({
  413. timestamp: module.timestamp,
  414. hash: module.hash
  415. })),
  416. immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]),
  417. managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p])
  418. })),
  419. stats: nestedConfig(config.stats, stats => {
  420. if (stats === false) {
  421. return {
  422. preset: "none"
  423. };
  424. }
  425. if (stats === true) {
  426. return {
  427. preset: "normal"
  428. };
  429. }
  430. if (typeof stats === "string") {
  431. return {
  432. preset: stats
  433. };
  434. }
  435. return {
  436. ...stats
  437. };
  438. }),
  439. target: config.target,
  440. watch: config.watch,
  441. watchOptions: cloneObject(config.watchOptions)
  442. };
  443. };
  444. /**
  445. * @param {EntryStatic} entry static entry options
  446. * @returns {EntryStaticNormalized} normalized static entry options
  447. */
  448. const getNormalizedEntryStatic = entry => {
  449. if (typeof entry === "string") {
  450. return {
  451. main: {
  452. import: [entry]
  453. }
  454. };
  455. }
  456. if (Array.isArray(entry)) {
  457. return {
  458. main: {
  459. import: entry
  460. }
  461. };
  462. }
  463. /** @type {EntryStaticNormalized} */
  464. const result = {};
  465. for (const key of Object.keys(entry)) {
  466. const value = entry[key];
  467. if (typeof value === "string") {
  468. result[key] = {
  469. import: [value]
  470. };
  471. } else if (Array.isArray(value)) {
  472. result[key] = {
  473. import: value
  474. };
  475. } else {
  476. result[key] = {
  477. import:
  478. value.import &&
  479. (Array.isArray(value.import) ? value.import : [value.import]),
  480. filename: value.filename,
  481. layer: value.layer,
  482. runtime: value.runtime,
  483. baseUri: value.baseUri,
  484. publicPath: value.publicPath,
  485. chunkLoading: value.chunkLoading,
  486. asyncChunks: value.asyncChunks,
  487. wasmLoading: value.wasmLoading,
  488. dependOn:
  489. value.dependOn &&
  490. (Array.isArray(value.dependOn) ? value.dependOn : [value.dependOn]),
  491. library: value.library
  492. };
  493. }
  494. }
  495. return result;
  496. };
  497. /**
  498. * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option
  499. * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option
  500. */
  501. const getNormalizedOptimizationRuntimeChunk = runtimeChunk => {
  502. if (runtimeChunk === undefined) return undefined;
  503. if (runtimeChunk === false) return false;
  504. if (runtimeChunk === "single") {
  505. return {
  506. name: () => "runtime"
  507. };
  508. }
  509. if (runtimeChunk === true || runtimeChunk === "multiple") {
  510. return {
  511. name: entrypoint => `runtime~${entrypoint.name}`
  512. };
  513. }
  514. const { name } = runtimeChunk;
  515. return {
  516. name: typeof name === "function" ? name : () => name
  517. };
  518. };
  519. exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions;