normalization.js 21 KB

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