10
0

DefinePlugin.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const {
  7. JAVASCRIPT_MODULE_TYPE_AUTO,
  8. JAVASCRIPT_MODULE_TYPE_ESM,
  9. JAVASCRIPT_MODULE_TYPE_DYNAMIC
  10. } = require("./ModuleTypeConstants");
  11. const RuntimeGlobals = require("./RuntimeGlobals");
  12. const WebpackError = require("./WebpackError");
  13. const ConstDependency = require("./dependencies/ConstDependency");
  14. const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
  15. const { VariableInfo } = require("./javascript/JavascriptParser");
  16. const {
  17. evaluateToString,
  18. toConstantDependency
  19. } = require("./javascript/JavascriptParserHelpers");
  20. const createHash = require("./util/createHash");
  21. /** @typedef {import("estree").Expression} Expression */
  22. /** @typedef {import("./Compiler")} Compiler */
  23. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  24. /** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
  25. /** @typedef {import("./NormalModule")} NormalModule */
  26. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  27. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  28. /** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */
  29. /** @typedef {import("./javascript/JavascriptParser").Range} Range */
  30. /** @typedef {import("./logging/Logger").Logger} Logger */
  31. /** @typedef {import("./util/createHash").Algorithm} Algorithm */
  32. /** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */
  33. /** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive|RuntimeValue>} CodeValue */
  34. /**
  35. * @typedef {object} RuntimeValueOptions
  36. * @property {string[]=} fileDependencies
  37. * @property {string[]=} contextDependencies
  38. * @property {string[]=} missingDependencies
  39. * @property {string[]=} buildDependencies
  40. * @property {string|function(): string=} version
  41. */
  42. /** @typedef {string | Set<string>} ValueCacheVersion */
  43. /** @typedef {function({ module: NormalModule, key: string, readonly version: ValueCacheVersion }): CodeValuePrimitive} GeneratorFn */
  44. class RuntimeValue {
  45. /**
  46. * @param {GeneratorFn} fn generator function
  47. * @param {true | string[] | RuntimeValueOptions=} options options
  48. */
  49. constructor(fn, options) {
  50. this.fn = fn;
  51. if (Array.isArray(options)) {
  52. options = {
  53. fileDependencies: options
  54. };
  55. }
  56. this.options = options || {};
  57. }
  58. get fileDependencies() {
  59. return this.options === true ? true : this.options.fileDependencies;
  60. }
  61. /**
  62. * @param {JavascriptParser} parser the parser
  63. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  64. * @param {string} key the defined key
  65. * @returns {CodeValuePrimitive} code
  66. */
  67. exec(parser, valueCacheVersions, key) {
  68. const buildInfo = /** @type {BuildInfo} */ (parser.state.module.buildInfo);
  69. if (this.options === true) {
  70. buildInfo.cacheable = false;
  71. } else {
  72. if (this.options.fileDependencies) {
  73. for (const dep of this.options.fileDependencies) {
  74. /** @type {NonNullable<BuildInfo["fileDependencies"]>} */
  75. (buildInfo.fileDependencies).add(dep);
  76. }
  77. }
  78. if (this.options.contextDependencies) {
  79. for (const dep of this.options.contextDependencies) {
  80. /** @type {NonNullable<BuildInfo["contextDependencies"]>} */
  81. (buildInfo.contextDependencies).add(dep);
  82. }
  83. }
  84. if (this.options.missingDependencies) {
  85. for (const dep of this.options.missingDependencies) {
  86. /** @type {NonNullable<BuildInfo["missingDependencies"]>} */
  87. (buildInfo.missingDependencies).add(dep);
  88. }
  89. }
  90. if (this.options.buildDependencies) {
  91. for (const dep of this.options.buildDependencies) {
  92. /** @type {NonNullable<BuildInfo["buildDependencies"]>} */
  93. (buildInfo.buildDependencies).add(dep);
  94. }
  95. }
  96. }
  97. return this.fn({
  98. module: parser.state.module,
  99. key,
  100. get version() {
  101. return /** @type {ValueCacheVersion} */ (
  102. valueCacheVersions.get(VALUE_DEP_PREFIX + key)
  103. );
  104. }
  105. });
  106. }
  107. getCacheVersion() {
  108. return this.options === true
  109. ? undefined
  110. : (typeof this.options.version === "function"
  111. ? this.options.version()
  112. : this.options.version) || "unset";
  113. }
  114. }
  115. /**
  116. * @param {Set<DestructuringAssignmentProperty> | undefined} properties properties
  117. * @returns {Set<string> | undefined} used keys
  118. */
  119. function getObjKeys(properties) {
  120. if (!properties) return;
  121. return new Set([...properties].map(p => p.id));
  122. }
  123. /** @typedef {Set<string> | null} ObjKeys */
  124. /** @typedef {boolean | undefined | null} AsiSafe */
  125. /**
  126. * @param {any[]|{[k: string]: any}} obj obj
  127. * @param {JavascriptParser} parser Parser
  128. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  129. * @param {string} key the defined key
  130. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  131. * @param {Logger} logger the logger object
  132. * @param {AsiSafe=} asiSafe asi safe (undefined: unknown, null: unneeded)
  133. * @param {ObjKeys=} objKeys used keys
  134. * @returns {string} code converted to string that evaluates
  135. */
  136. const stringifyObj = (
  137. obj,
  138. parser,
  139. valueCacheVersions,
  140. key,
  141. runtimeTemplate,
  142. logger,
  143. asiSafe,
  144. objKeys
  145. ) => {
  146. let code;
  147. const arr = Array.isArray(obj);
  148. if (arr) {
  149. code = `[${
  150. /** @type {any[]} */ (obj)
  151. .map(code =>
  152. toCode(
  153. code,
  154. parser,
  155. valueCacheVersions,
  156. key,
  157. runtimeTemplate,
  158. logger,
  159. null
  160. )
  161. )
  162. .join(",")
  163. }]`;
  164. } else {
  165. let keys = Object.keys(obj);
  166. if (objKeys) {
  167. keys = objKeys.size === 0 ? [] : keys.filter(k => objKeys.has(k));
  168. }
  169. code = `{${keys
  170. .map(key => {
  171. const code = /** @type {{[k: string]: any}} */ (obj)[key];
  172. return `${JSON.stringify(key)}:${toCode(
  173. code,
  174. parser,
  175. valueCacheVersions,
  176. key,
  177. runtimeTemplate,
  178. logger,
  179. null
  180. )}`;
  181. })
  182. .join(",")}}`;
  183. }
  184. switch (asiSafe) {
  185. case null:
  186. return code;
  187. case true:
  188. return arr ? code : `(${code})`;
  189. case false:
  190. return arr ? `;${code}` : `;(${code})`;
  191. default:
  192. return `/*#__PURE__*/Object(${code})`;
  193. }
  194. };
  195. /**
  196. * Convert code to a string that evaluates
  197. * @param {CodeValue} code Code to evaluate
  198. * @param {JavascriptParser} parser Parser
  199. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  200. * @param {string} key the defined key
  201. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  202. * @param {Logger} logger the logger object
  203. * @param {boolean | undefined | null=} asiSafe asi safe (undefined: unknown, null: unneeded)
  204. * @param {ObjKeys=} objKeys used keys
  205. * @returns {string} code converted to string that evaluates
  206. */
  207. const toCode = (
  208. code,
  209. parser,
  210. valueCacheVersions,
  211. key,
  212. runtimeTemplate,
  213. logger,
  214. asiSafe,
  215. objKeys
  216. ) => {
  217. const transformToCode = () => {
  218. if (code === null) {
  219. return "null";
  220. }
  221. if (code === undefined) {
  222. return "undefined";
  223. }
  224. if (Object.is(code, -0)) {
  225. return "-0";
  226. }
  227. if (code instanceof RuntimeValue) {
  228. return toCode(
  229. code.exec(parser, valueCacheVersions, key),
  230. parser,
  231. valueCacheVersions,
  232. key,
  233. runtimeTemplate,
  234. logger,
  235. asiSafe
  236. );
  237. }
  238. if (code instanceof RegExp && code.toString) {
  239. return code.toString();
  240. }
  241. if (typeof code === "function" && code.toString) {
  242. return `(${code.toString()})`;
  243. }
  244. if (typeof code === "object") {
  245. return stringifyObj(
  246. code,
  247. parser,
  248. valueCacheVersions,
  249. key,
  250. runtimeTemplate,
  251. logger,
  252. asiSafe,
  253. objKeys
  254. );
  255. }
  256. if (typeof code === "bigint") {
  257. return runtimeTemplate.supportsBigIntLiteral()
  258. ? `${code}n`
  259. : `BigInt("${code}")`;
  260. }
  261. return `${code}`;
  262. };
  263. const strCode = transformToCode();
  264. logger.debug(`Replaced "${key}" with "${strCode}"`);
  265. return strCode;
  266. };
  267. /**
  268. * @param {CodeValue} code code
  269. * @returns {string | undefined} result
  270. */
  271. const toCacheVersion = code => {
  272. if (code === null) {
  273. return "null";
  274. }
  275. if (code === undefined) {
  276. return "undefined";
  277. }
  278. if (Object.is(code, -0)) {
  279. return "-0";
  280. }
  281. if (code instanceof RuntimeValue) {
  282. return code.getCacheVersion();
  283. }
  284. if (code instanceof RegExp && code.toString) {
  285. return code.toString();
  286. }
  287. if (typeof code === "function" && code.toString) {
  288. return `(${code.toString()})`;
  289. }
  290. if (typeof code === "object") {
  291. const items = Object.keys(code).map(key => ({
  292. key,
  293. value: toCacheVersion(/** @type {Record<string, any>} */ (code)[key])
  294. }));
  295. if (items.some(({ value }) => value === undefined)) return;
  296. return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
  297. }
  298. if (typeof code === "bigint") {
  299. return `${code}n`;
  300. }
  301. return `${code}`;
  302. };
  303. const PLUGIN_NAME = "DefinePlugin";
  304. const VALUE_DEP_PREFIX = `webpack/${PLUGIN_NAME} `;
  305. const VALUE_DEP_MAIN = `webpack/${PLUGIN_NAME}_hash`;
  306. const TYPEOF_OPERATOR_REGEXP = /^typeof\s+/;
  307. const WEBPACK_REQUIRE_FUNCTION_REGEXP = new RegExp(
  308. `${RuntimeGlobals.require}\\s*(!?\\.)`
  309. );
  310. const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = new RegExp(RuntimeGlobals.require);
  311. class DefinePlugin {
  312. /**
  313. * Create a new define plugin
  314. * @param {Record<string, CodeValue>} definitions A map of global object definitions
  315. */
  316. constructor(definitions) {
  317. this.definitions = definitions;
  318. }
  319. /**
  320. * @param {GeneratorFn} fn generator function
  321. * @param {true | string[] | RuntimeValueOptions=} options options
  322. * @returns {RuntimeValue} runtime value
  323. */
  324. static runtimeValue(fn, options) {
  325. return new RuntimeValue(fn, options);
  326. }
  327. /**
  328. * Apply the plugin
  329. * @param {Compiler} compiler the compiler instance
  330. * @returns {void}
  331. */
  332. apply(compiler) {
  333. const definitions = this.definitions;
  334. compiler.hooks.compilation.tap(
  335. PLUGIN_NAME,
  336. (compilation, { normalModuleFactory }) => {
  337. const logger = compilation.getLogger("webpack.DefinePlugin");
  338. compilation.dependencyTemplates.set(
  339. ConstDependency,
  340. new ConstDependency.Template()
  341. );
  342. const { runtimeTemplate } = compilation;
  343. const mainHash = createHash(
  344. /** @type {Algorithm} */
  345. (compilation.outputOptions.hashFunction)
  346. );
  347. mainHash.update(
  348. /** @type {string} */
  349. (compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || ""
  350. );
  351. /**
  352. * Handler
  353. * @param {JavascriptParser} parser Parser
  354. * @returns {void}
  355. */
  356. const handler = parser => {
  357. const mainValue =
  358. /** @type {ValueCacheVersion} */
  359. (compilation.valueCacheVersions.get(VALUE_DEP_MAIN));
  360. parser.hooks.program.tap(PLUGIN_NAME, () => {
  361. const buildInfo = /** @type {BuildInfo} */ (
  362. parser.state.module.buildInfo
  363. );
  364. if (!buildInfo.valueDependencies)
  365. buildInfo.valueDependencies = new Map();
  366. buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
  367. });
  368. /**
  369. * @param {string} key key
  370. */
  371. const addValueDependency = key => {
  372. const buildInfo =
  373. /** @type {BuildInfo} */
  374. (parser.state.module.buildInfo);
  375. /** @type {NonNullable<BuildInfo["valueDependencies"]>} */
  376. (buildInfo.valueDependencies).set(
  377. VALUE_DEP_PREFIX + key,
  378. /** @type {ValueCacheVersion} */
  379. (compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key))
  380. );
  381. };
  382. /**
  383. * @template {Function} T
  384. * @param {string} key key
  385. * @param {T} fn fn
  386. * @returns {function(TODO): TODO} result
  387. */
  388. const withValueDependency =
  389. (key, fn) =>
  390. (...args) => {
  391. addValueDependency(key);
  392. return fn(...args);
  393. };
  394. /**
  395. * Walk definitions
  396. * @param {Record<string, CodeValue>} definitions Definitions map
  397. * @param {string} prefix Prefix string
  398. * @returns {void}
  399. */
  400. const walkDefinitions = (definitions, prefix) => {
  401. for (const key of Object.keys(definitions)) {
  402. const code = definitions[key];
  403. if (
  404. code &&
  405. typeof code === "object" &&
  406. !(code instanceof RuntimeValue) &&
  407. !(code instanceof RegExp)
  408. ) {
  409. walkDefinitions(
  410. /** @type {Record<string, CodeValue>} */ (code),
  411. `${prefix + key}.`
  412. );
  413. applyObjectDefine(prefix + key, code);
  414. continue;
  415. }
  416. applyDefineKey(prefix, key);
  417. applyDefine(prefix + key, code);
  418. }
  419. };
  420. /**
  421. * Apply define key
  422. * @param {string} prefix Prefix
  423. * @param {string} key Key
  424. * @returns {void}
  425. */
  426. const applyDefineKey = (prefix, key) => {
  427. const splittedKey = key.split(".");
  428. const firstKey = splittedKey[0];
  429. for (const [i, _] of splittedKey.slice(1).entries()) {
  430. const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
  431. parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
  432. addValueDependency(key);
  433. if (
  434. parser.scope.definitions.get(firstKey) instanceof VariableInfo
  435. ) {
  436. return false;
  437. }
  438. return true;
  439. });
  440. }
  441. };
  442. /**
  443. * Apply Code
  444. * @param {string} key Key
  445. * @param {CodeValue} code Code
  446. * @returns {void}
  447. */
  448. const applyDefine = (key, code) => {
  449. const originalKey = key;
  450. const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key);
  451. if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, "");
  452. let recurse = false;
  453. let recurseTypeof = false;
  454. if (!isTypeof) {
  455. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  456. addValueDependency(originalKey);
  457. return true;
  458. });
  459. parser.hooks.evaluateIdentifier
  460. .for(key)
  461. .tap(PLUGIN_NAME, expr => {
  462. /**
  463. * this is needed in case there is a recursion in the DefinePlugin
  464. * to prevent an endless recursion
  465. * e.g.: new DefinePlugin({
  466. * "a": "b",
  467. * "b": "a"
  468. * });
  469. */
  470. if (recurse) return;
  471. addValueDependency(originalKey);
  472. recurse = true;
  473. const res = parser.evaluate(
  474. toCode(
  475. code,
  476. parser,
  477. compilation.valueCacheVersions,
  478. key,
  479. runtimeTemplate,
  480. logger,
  481. null
  482. )
  483. );
  484. recurse = false;
  485. res.setRange(/** @type {Range} */ (expr.range));
  486. return res;
  487. });
  488. parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
  489. addValueDependency(originalKey);
  490. let strCode = toCode(
  491. code,
  492. parser,
  493. compilation.valueCacheVersions,
  494. originalKey,
  495. runtimeTemplate,
  496. logger,
  497. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  498. null
  499. );
  500. if (parser.scope.inShorthand) {
  501. strCode = `${parser.scope.inShorthand}:${strCode}`;
  502. }
  503. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  504. return toConstantDependency(parser, strCode, [
  505. RuntimeGlobals.require
  506. ])(expr);
  507. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  508. return toConstantDependency(parser, strCode, [
  509. RuntimeGlobals.requireScope
  510. ])(expr);
  511. }
  512. return toConstantDependency(parser, strCode)(expr);
  513. });
  514. }
  515. parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, expr => {
  516. /**
  517. * this is needed in case there is a recursion in the DefinePlugin
  518. * to prevent an endless recursion
  519. * e.g.: new DefinePlugin({
  520. * "typeof a": "typeof b",
  521. * "typeof b": "typeof a"
  522. * });
  523. */
  524. if (recurseTypeof) return;
  525. recurseTypeof = true;
  526. addValueDependency(originalKey);
  527. const codeCode = toCode(
  528. code,
  529. parser,
  530. compilation.valueCacheVersions,
  531. originalKey,
  532. runtimeTemplate,
  533. logger,
  534. null
  535. );
  536. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  537. const res = parser.evaluate(typeofCode);
  538. recurseTypeof = false;
  539. res.setRange(/** @type {Range} */ (expr.range));
  540. return res;
  541. });
  542. parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => {
  543. addValueDependency(originalKey);
  544. const codeCode = toCode(
  545. code,
  546. parser,
  547. compilation.valueCacheVersions,
  548. originalKey,
  549. runtimeTemplate,
  550. logger,
  551. null
  552. );
  553. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  554. const res = parser.evaluate(typeofCode);
  555. if (!res.isString()) return;
  556. return toConstantDependency(
  557. parser,
  558. JSON.stringify(res.string)
  559. ).bind(parser)(expr);
  560. });
  561. };
  562. /**
  563. * Apply Object
  564. * @param {string} key Key
  565. * @param {object} obj Object
  566. * @returns {void}
  567. */
  568. const applyObjectDefine = (key, obj) => {
  569. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  570. addValueDependency(key);
  571. return true;
  572. });
  573. parser.hooks.evaluateIdentifier.for(key).tap(PLUGIN_NAME, expr => {
  574. addValueDependency(key);
  575. return new BasicEvaluatedExpression()
  576. .setTruthy()
  577. .setSideEffects(false)
  578. .setRange(/** @type {Range} */ (expr.range));
  579. });
  580. parser.hooks.evaluateTypeof
  581. .for(key)
  582. .tap(
  583. PLUGIN_NAME,
  584. withValueDependency(key, evaluateToString("object"))
  585. );
  586. parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
  587. addValueDependency(key);
  588. let strCode = stringifyObj(
  589. obj,
  590. parser,
  591. compilation.valueCacheVersions,
  592. key,
  593. runtimeTemplate,
  594. logger,
  595. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  596. getObjKeys(parser.destructuringAssignmentPropertiesFor(expr))
  597. );
  598. if (parser.scope.inShorthand) {
  599. strCode = `${parser.scope.inShorthand}:${strCode}`;
  600. }
  601. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  602. return toConstantDependency(parser, strCode, [
  603. RuntimeGlobals.require
  604. ])(expr);
  605. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  606. return toConstantDependency(parser, strCode, [
  607. RuntimeGlobals.requireScope
  608. ])(expr);
  609. }
  610. return toConstantDependency(parser, strCode)(expr);
  611. });
  612. parser.hooks.typeof
  613. .for(key)
  614. .tap(
  615. PLUGIN_NAME,
  616. withValueDependency(
  617. key,
  618. toConstantDependency(parser, JSON.stringify("object"))
  619. )
  620. );
  621. };
  622. walkDefinitions(definitions, "");
  623. };
  624. normalModuleFactory.hooks.parser
  625. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  626. .tap(PLUGIN_NAME, handler);
  627. normalModuleFactory.hooks.parser
  628. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  629. .tap(PLUGIN_NAME, handler);
  630. normalModuleFactory.hooks.parser
  631. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  632. .tap(PLUGIN_NAME, handler);
  633. /**
  634. * Walk definitions
  635. * @param {Record<string, CodeValue>} definitions Definitions map
  636. * @param {string} prefix Prefix string
  637. * @returns {void}
  638. */
  639. const walkDefinitionsForValues = (definitions, prefix) => {
  640. for (const key of Object.keys(definitions)) {
  641. const code = definitions[key];
  642. const version = /** @type {string} */ (toCacheVersion(code));
  643. const name = VALUE_DEP_PREFIX + prefix + key;
  644. mainHash.update(`|${prefix}${key}`);
  645. const oldVersion = compilation.valueCacheVersions.get(name);
  646. if (oldVersion === undefined) {
  647. compilation.valueCacheVersions.set(name, version);
  648. } else if (oldVersion !== version) {
  649. const warning = new WebpackError(
  650. `${PLUGIN_NAME}\nConflicting values for '${prefix + key}'`
  651. );
  652. warning.details = `'${oldVersion}' !== '${version}'`;
  653. warning.hideStack = true;
  654. compilation.warnings.push(warning);
  655. }
  656. if (
  657. code &&
  658. typeof code === "object" &&
  659. !(code instanceof RuntimeValue) &&
  660. !(code instanceof RegExp)
  661. ) {
  662. walkDefinitionsForValues(
  663. /** @type {Record<string, CodeValue>} */ (code),
  664. `${prefix + key}.`
  665. );
  666. }
  667. }
  668. };
  669. walkDefinitionsForValues(definitions, "");
  670. compilation.valueCacheVersions.set(
  671. VALUE_DEP_MAIN,
  672. /** @type {string} */ (mainHash.digest("hex").slice(0, 8))
  673. );
  674. }
  675. );
  676. }
  677. }
  678. module.exports = DefinePlugin;