提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4107 lines
117 KiB

  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const nodeModule = require("module");
  7. const { isAbsolute } = require("path");
  8. const { create: createResolver } = require("enhanced-resolve");
  9. const asyncLib = require("neo-async");
  10. const { DEFAULTS } = require("./config/defaults");
  11. const AsyncQueue = require("./util/AsyncQueue");
  12. const StackedCacheMap = require("./util/StackedCacheMap");
  13. const createHash = require("./util/createHash");
  14. const { dirname, join, lstatReadlinkAbsolute, relative } = require("./util/fs");
  15. const makeSerializable = require("./util/makeSerializable");
  16. const memoize = require("./util/memoize");
  17. const processAsyncTree = require("./util/processAsyncTree");
  18. /** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
  19. /** @typedef {import("enhanced-resolve").ResolveFunctionAsync} ResolveFunctionAsync */
  20. /** @typedef {import("./WebpackError")} WebpackError */
  21. /** @typedef {import("./logging/Logger").Logger} Logger */
  22. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  23. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  24. /** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
  25. /** @typedef {import("./util/fs").IStats} IStats */
  26. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  27. /**
  28. * @template T
  29. * @typedef {import("./util/AsyncQueue").Callback<T>} ProcessorCallback
  30. */
  31. /**
  32. * @template T, R
  33. * @typedef {import("./util/AsyncQueue").Processor<T, R>} Processor
  34. */
  35. const supportsEsm = Number(process.versions.modules) >= 83;
  36. /** @type {Set<string>} */
  37. const builtinModules = new Set(nodeModule.builtinModules);
  38. let FS_ACCURACY = 2000;
  39. const EMPTY_SET = new Set();
  40. const RBDT_RESOLVE_INITIAL = 0;
  41. const RBDT_RESOLVE_FILE = 1;
  42. const RBDT_RESOLVE_DIRECTORY = 2;
  43. const RBDT_RESOLVE_CJS_FILE = 3;
  44. const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4;
  45. const RBDT_RESOLVE_ESM_FILE = 5;
  46. const RBDT_DIRECTORY = 6;
  47. const RBDT_FILE = 7;
  48. const RBDT_DIRECTORY_DEPENDENCIES = 8;
  49. const RBDT_FILE_DEPENDENCIES = 9;
  50. /** @typedef {RBDT_RESOLVE_INITIAL | RBDT_RESOLVE_FILE | RBDT_RESOLVE_DIRECTORY | RBDT_RESOLVE_CJS_FILE | RBDT_RESOLVE_CJS_FILE_AS_CHILD | RBDT_RESOLVE_ESM_FILE | RBDT_DIRECTORY | RBDT_FILE | RBDT_DIRECTORY_DEPENDENCIES | RBDT_FILE_DEPENDENCIES} JobType */
  51. const INVALID = Symbol("invalid");
  52. /**
  53. * @typedef {object} FileSystemInfoEntry
  54. * @property {number} safeTime
  55. * @property {number=} timestamp
  56. */
  57. /**
  58. * @typedef {object} ResolvedContextFileSystemInfoEntry
  59. * @property {number} safeTime
  60. * @property {string=} timestampHash
  61. */
  62. /** @typedef {Set<string>} Symlinks */
  63. /**
  64. * @typedef {object} ContextFileSystemInfoEntry
  65. * @property {number} safeTime
  66. * @property {string=} timestampHash
  67. * @property {ResolvedContextFileSystemInfoEntry=} resolved
  68. * @property {Symlinks=} symlinks
  69. */
  70. /**
  71. * @typedef {object} TimestampAndHash
  72. * @property {number} safeTime
  73. * @property {number=} timestamp
  74. * @property {string} hash
  75. */
  76. /**
  77. * @typedef {object} ResolvedContextTimestampAndHash
  78. * @property {number} safeTime
  79. * @property {string=} timestampHash
  80. * @property {string} hash
  81. */
  82. /**
  83. * @typedef {object} ContextTimestampAndHash
  84. * @property {number} safeTime
  85. * @property {string=} timestampHash
  86. * @property {string} hash
  87. * @property {ResolvedContextTimestampAndHash=} resolved
  88. * @property {Symlinks=} symlinks
  89. */
  90. /**
  91. * @typedef {object} ContextHash
  92. * @property {string} hash
  93. * @property {string=} resolved
  94. * @property {Symlinks=} symlinks
  95. */
  96. /** @typedef {Set<string>} SnapshotContent */
  97. /**
  98. * @typedef {object} SnapshotOptimizationEntry
  99. * @property {Snapshot} snapshot
  100. * @property {number} shared
  101. * @property {SnapshotContent | undefined} snapshotContent
  102. * @property {Set<SnapshotOptimizationEntry> | undefined} children
  103. */
  104. /** @typedef {Map<string, string | false | undefined>} ResolveResults */
  105. /** @typedef {Set<string>} Files */
  106. /** @typedef {Set<string>} Directories */
  107. /** @typedef {Set<string>} Missing */
  108. /**
  109. * @typedef {object} ResolveDependencies
  110. * @property {Files} files list of files
  111. * @property {Directories} directories list of directories
  112. * @property {Missing} missing list of missing entries
  113. */
  114. /**
  115. * @typedef {object} ResolveBuildDependenciesResult
  116. * @property {Files} files list of files
  117. * @property {Directories} directories list of directories
  118. * @property {Missing} missing list of missing entries
  119. * @property {ResolveResults} resolveResults stored resolve results
  120. * @property {ResolveDependencies} resolveDependencies dependencies of the resolving
  121. */
  122. /**
  123. * @typedef {object} SnapshotOptions
  124. * @property {boolean=} hash should use hash to snapshot
  125. * @property {boolean=} timestamp should use timestamp to snapshot
  126. */
  127. const DONE_ITERATOR_RESULT = new Set().keys().next();
  128. // cspell:word tshs
  129. // Tsh = Timestamp + Hash
  130. // Tshs = Timestamp + Hash combinations
  131. class SnapshotIterator {
  132. /**
  133. * @param {() => IteratorResult<string>} next next
  134. */
  135. constructor(next) {
  136. this.next = next;
  137. }
  138. }
  139. /**
  140. * @template T
  141. * @typedef {(snapshot: Snapshot) => T[]} GetMapsFunction
  142. */
  143. /**
  144. * @template T
  145. */
  146. class SnapshotIterable {
  147. /**
  148. * @param {Snapshot} snapshot snapshot
  149. * @param {GetMapsFunction<T>} getMaps get maps function
  150. */
  151. constructor(snapshot, getMaps) {
  152. this.snapshot = snapshot;
  153. this.getMaps = getMaps;
  154. }
  155. [Symbol.iterator]() {
  156. let state = 0;
  157. /** @type {IterableIterator<string>} */
  158. let it;
  159. /** @type {GetMapsFunction<T>} */
  160. let getMaps;
  161. /** @type {T[]} */
  162. let maps;
  163. /** @type {Snapshot} */
  164. let snapshot;
  165. /** @type {Snapshot[] | undefined} */
  166. let queue;
  167. return new SnapshotIterator(() => {
  168. for (;;) {
  169. switch (state) {
  170. case 0:
  171. snapshot = this.snapshot;
  172. getMaps = this.getMaps;
  173. maps = getMaps(snapshot);
  174. state = 1;
  175. /* falls through */
  176. case 1:
  177. if (maps.length > 0) {
  178. const map = maps.pop();
  179. if (map !== undefined) {
  180. it =
  181. /** @type {Set<EXPECTED_ANY> | Map<string, EXPECTED_ANY>} */
  182. (map).keys();
  183. state = 2;
  184. } else {
  185. break;
  186. }
  187. } else {
  188. state = 3;
  189. break;
  190. }
  191. /* falls through */
  192. case 2: {
  193. const result = it.next();
  194. if (!result.done) return result;
  195. state = 1;
  196. break;
  197. }
  198. case 3: {
  199. const children = snapshot.children;
  200. if (children !== undefined) {
  201. if (children.size === 1) {
  202. // shortcut for a single child
  203. // avoids allocation of queue
  204. for (const child of children) snapshot = child;
  205. maps = getMaps(snapshot);
  206. state = 1;
  207. break;
  208. }
  209. if (queue === undefined) queue = [];
  210. for (const child of children) {
  211. queue.push(child);
  212. }
  213. }
  214. if (queue !== undefined && queue.length > 0) {
  215. snapshot = /** @type {Snapshot} */ (queue.pop());
  216. maps = getMaps(snapshot);
  217. state = 1;
  218. break;
  219. } else {
  220. state = 4;
  221. }
  222. }
  223. /* falls through */
  224. case 4:
  225. return DONE_ITERATOR_RESULT;
  226. }
  227. }
  228. });
  229. }
  230. }
  231. /** @typedef {Map<string, FileSystemInfoEntry | null>} FileTimestamps */
  232. /** @typedef {Map<string, string | null>} FileHashes */
  233. /** @typedef {Map<string, TimestampAndHash | string | null>} FileTshs */
  234. /** @typedef {Map<string, ResolvedContextFileSystemInfoEntry | null>} ContextTimestamps */
  235. /** @typedef {Map<string, string | null>} ContextHashes */
  236. /** @typedef {Map<string, ResolvedContextTimestampAndHash | null>} ContextTshs */
  237. /** @typedef {Map<string, boolean>} MissingExistence */
  238. /** @typedef {Map<string, string>} ManagedItemInfo */
  239. /** @typedef {Set<string>} ManagedFiles */
  240. /** @typedef {Set<string>} ManagedContexts */
  241. /** @typedef {Set<string>} ManagedMissing */
  242. /** @typedef {Set<Snapshot>} Children */
  243. class Snapshot {
  244. constructor() {
  245. this._flags = 0;
  246. /** @type {Iterable<string> | undefined} */
  247. this._cachedFileIterable = undefined;
  248. /** @type {Iterable<string> | undefined} */
  249. this._cachedContextIterable = undefined;
  250. /** @type {Iterable<string> | undefined} */
  251. this._cachedMissingIterable = undefined;
  252. /** @type {number | undefined} */
  253. this.startTime = undefined;
  254. /** @type {FileTimestamps | undefined} */
  255. this.fileTimestamps = undefined;
  256. /** @type {FileHashes | undefined} */
  257. this.fileHashes = undefined;
  258. /** @type {FileTshs | undefined} */
  259. this.fileTshs = undefined;
  260. /** @type {ContextTimestamps | undefined} */
  261. this.contextTimestamps = undefined;
  262. /** @type {ContextHashes | undefined} */
  263. this.contextHashes = undefined;
  264. /** @type {ContextTshs | undefined} */
  265. this.contextTshs = undefined;
  266. /** @type {MissingExistence | undefined} */
  267. this.missingExistence = undefined;
  268. /** @type {ManagedItemInfo | undefined} */
  269. this.managedItemInfo = undefined;
  270. /** @type {ManagedFiles | undefined} */
  271. this.managedFiles = undefined;
  272. /** @type {ManagedContexts | undefined} */
  273. this.managedContexts = undefined;
  274. /** @type {ManagedMissing | undefined} */
  275. this.managedMissing = undefined;
  276. /** @type {Children | undefined} */
  277. this.children = undefined;
  278. }
  279. hasStartTime() {
  280. return (this._flags & 1) !== 0;
  281. }
  282. /**
  283. * @param {number} value start value
  284. */
  285. setStartTime(value) {
  286. this._flags |= 1;
  287. this.startTime = value;
  288. }
  289. /**
  290. * @param {number | undefined} value value
  291. * @param {Snapshot} snapshot snapshot
  292. */
  293. setMergedStartTime(value, snapshot) {
  294. if (value) {
  295. if (snapshot.hasStartTime()) {
  296. this.setStartTime(
  297. Math.min(
  298. value,
  299. /** @type {NonNullable<Snapshot["startTime"]>} */
  300. (snapshot.startTime)
  301. )
  302. );
  303. } else {
  304. this.setStartTime(value);
  305. }
  306. } else if (snapshot.hasStartTime()) {
  307. this.setStartTime(
  308. /** @type {NonNullable<Snapshot["startTime"]>} */
  309. (snapshot.startTime)
  310. );
  311. }
  312. }
  313. hasFileTimestamps() {
  314. return (this._flags & 2) !== 0;
  315. }
  316. /**
  317. * @param {FileTimestamps} value file timestamps
  318. */
  319. setFileTimestamps(value) {
  320. this._flags |= 2;
  321. this.fileTimestamps = value;
  322. }
  323. hasFileHashes() {
  324. return (this._flags & 4) !== 0;
  325. }
  326. /**
  327. * @param {FileHashes} value file hashes
  328. */
  329. setFileHashes(value) {
  330. this._flags |= 4;
  331. this.fileHashes = value;
  332. }
  333. hasFileTshs() {
  334. return (this._flags & 8) !== 0;
  335. }
  336. /**
  337. * @param {FileTshs} value file tshs
  338. */
  339. setFileTshs(value) {
  340. this._flags |= 8;
  341. this.fileTshs = value;
  342. }
  343. hasContextTimestamps() {
  344. return (this._flags & 0x10) !== 0;
  345. }
  346. /**
  347. * @param {ContextTimestamps} value context timestamps
  348. */
  349. setContextTimestamps(value) {
  350. this._flags |= 0x10;
  351. this.contextTimestamps = value;
  352. }
  353. hasContextHashes() {
  354. return (this._flags & 0x20) !== 0;
  355. }
  356. /**
  357. * @param {ContextHashes} value context hashes
  358. */
  359. setContextHashes(value) {
  360. this._flags |= 0x20;
  361. this.contextHashes = value;
  362. }
  363. hasContextTshs() {
  364. return (this._flags & 0x40) !== 0;
  365. }
  366. /**
  367. * @param {ContextTshs} value context tshs
  368. */
  369. setContextTshs(value) {
  370. this._flags |= 0x40;
  371. this.contextTshs = value;
  372. }
  373. hasMissingExistence() {
  374. return (this._flags & 0x80) !== 0;
  375. }
  376. /**
  377. * @param {MissingExistence} value context tshs
  378. */
  379. setMissingExistence(value) {
  380. this._flags |= 0x80;
  381. this.missingExistence = value;
  382. }
  383. hasManagedItemInfo() {
  384. return (this._flags & 0x100) !== 0;
  385. }
  386. /**
  387. * @param {ManagedItemInfo} value managed item info
  388. */
  389. setManagedItemInfo(value) {
  390. this._flags |= 0x100;
  391. this.managedItemInfo = value;
  392. }
  393. hasManagedFiles() {
  394. return (this._flags & 0x200) !== 0;
  395. }
  396. /**
  397. * @param {ManagedFiles} value managed files
  398. */
  399. setManagedFiles(value) {
  400. this._flags |= 0x200;
  401. this.managedFiles = value;
  402. }
  403. hasManagedContexts() {
  404. return (this._flags & 0x400) !== 0;
  405. }
  406. /**
  407. * @param {ManagedContexts} value managed contexts
  408. */
  409. setManagedContexts(value) {
  410. this._flags |= 0x400;
  411. this.managedContexts = value;
  412. }
  413. hasManagedMissing() {
  414. return (this._flags & 0x800) !== 0;
  415. }
  416. /**
  417. * @param {ManagedMissing} value managed missing
  418. */
  419. setManagedMissing(value) {
  420. this._flags |= 0x800;
  421. this.managedMissing = value;
  422. }
  423. hasChildren() {
  424. return (this._flags & 0x1000) !== 0;
  425. }
  426. /**
  427. * @param {Children} value children
  428. */
  429. setChildren(value) {
  430. this._flags |= 0x1000;
  431. this.children = value;
  432. }
  433. /**
  434. * @param {Snapshot} child children
  435. */
  436. addChild(child) {
  437. if (!this.hasChildren()) {
  438. this.setChildren(new Set());
  439. }
  440. /** @type {Children} */
  441. (this.children).add(child);
  442. }
  443. /**
  444. * @param {ObjectSerializerContext} context context
  445. */
  446. serialize({ write }) {
  447. write(this._flags);
  448. if (this.hasStartTime()) write(this.startTime);
  449. if (this.hasFileTimestamps()) write(this.fileTimestamps);
  450. if (this.hasFileHashes()) write(this.fileHashes);
  451. if (this.hasFileTshs()) write(this.fileTshs);
  452. if (this.hasContextTimestamps()) write(this.contextTimestamps);
  453. if (this.hasContextHashes()) write(this.contextHashes);
  454. if (this.hasContextTshs()) write(this.contextTshs);
  455. if (this.hasMissingExistence()) write(this.missingExistence);
  456. if (this.hasManagedItemInfo()) write(this.managedItemInfo);
  457. if (this.hasManagedFiles()) write(this.managedFiles);
  458. if (this.hasManagedContexts()) write(this.managedContexts);
  459. if (this.hasManagedMissing()) write(this.managedMissing);
  460. if (this.hasChildren()) write(this.children);
  461. }
  462. /**
  463. * @param {ObjectDeserializerContext} context context
  464. */
  465. deserialize({ read }) {
  466. this._flags = read();
  467. if (this.hasStartTime()) this.startTime = read();
  468. if (this.hasFileTimestamps()) this.fileTimestamps = read();
  469. if (this.hasFileHashes()) this.fileHashes = read();
  470. if (this.hasFileTshs()) this.fileTshs = read();
  471. if (this.hasContextTimestamps()) this.contextTimestamps = read();
  472. if (this.hasContextHashes()) this.contextHashes = read();
  473. if (this.hasContextTshs()) this.contextTshs = read();
  474. if (this.hasMissingExistence()) this.missingExistence = read();
  475. if (this.hasManagedItemInfo()) this.managedItemInfo = read();
  476. if (this.hasManagedFiles()) this.managedFiles = read();
  477. if (this.hasManagedContexts()) this.managedContexts = read();
  478. if (this.hasManagedMissing()) this.managedMissing = read();
  479. if (this.hasChildren()) this.children = read();
  480. }
  481. /**
  482. * @template T
  483. * @param {GetMapsFunction<T>} getMaps first
  484. * @returns {SnapshotIterable<T>} iterable
  485. */
  486. _createIterable(getMaps) {
  487. return new SnapshotIterable(this, getMaps);
  488. }
  489. /**
  490. * @returns {Iterable<string>} iterable
  491. */
  492. getFileIterable() {
  493. if (this._cachedFileIterable === undefined) {
  494. this._cachedFileIterable = this._createIterable((s) => [
  495. s.fileTimestamps,
  496. s.fileHashes,
  497. s.fileTshs,
  498. s.managedFiles
  499. ]);
  500. }
  501. return this._cachedFileIterable;
  502. }
  503. /**
  504. * @returns {Iterable<string>} iterable
  505. */
  506. getContextIterable() {
  507. if (this._cachedContextIterable === undefined) {
  508. this._cachedContextIterable = this._createIterable((s) => [
  509. s.contextTimestamps,
  510. s.contextHashes,
  511. s.contextTshs,
  512. s.managedContexts
  513. ]);
  514. }
  515. return this._cachedContextIterable;
  516. }
  517. /**
  518. * @returns {Iterable<string>} iterable
  519. */
  520. getMissingIterable() {
  521. if (this._cachedMissingIterable === undefined) {
  522. this._cachedMissingIterable = this._createIterable((s) => [
  523. s.missingExistence,
  524. s.managedMissing
  525. ]);
  526. }
  527. return this._cachedMissingIterable;
  528. }
  529. }
  530. makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot");
  531. const MIN_COMMON_SNAPSHOT_SIZE = 3;
  532. /**
  533. * @template U, T
  534. * @typedef {U extends true ? Set<string> : Map<string, T>} SnapshotOptimizationValue
  535. */
  536. /**
  537. * @template T
  538. * @template {boolean} [U=false]
  539. */
  540. class SnapshotOptimization {
  541. /**
  542. * @param {(snapshot: Snapshot) => boolean} has has value
  543. * @param {(snapshot: Snapshot) => SnapshotOptimizationValue<U, T> | undefined} get get value
  544. * @param {(snapshot: Snapshot, value: SnapshotOptimizationValue<U, T>) => void} set set value
  545. * @param {boolean=} useStartTime use the start time of snapshots
  546. * @param {U=} isSet value is an Set instead of a Map
  547. */
  548. constructor(
  549. has,
  550. get,
  551. set,
  552. useStartTime = true,
  553. isSet = /** @type {U} */ (false)
  554. ) {
  555. this._has = has;
  556. this._get = get;
  557. this._set = set;
  558. this._useStartTime = useStartTime;
  559. /** @type {U} */
  560. this._isSet = isSet;
  561. /** @type {Map<string, SnapshotOptimizationEntry>} */
  562. this._map = new Map();
  563. this._statItemsShared = 0;
  564. this._statItemsUnshared = 0;
  565. this._statSharedSnapshots = 0;
  566. this._statReusedSharedSnapshots = 0;
  567. }
  568. getStatisticMessage() {
  569. const total = this._statItemsShared + this._statItemsUnshared;
  570. if (total === 0) return;
  571. return `${
  572. this._statItemsShared && Math.round((this._statItemsShared * 100) / total)
  573. }% (${this._statItemsShared}/${total}) entries shared via ${
  574. this._statSharedSnapshots
  575. } shared snapshots (${
  576. this._statReusedSharedSnapshots + this._statSharedSnapshots
  577. } times referenced)`;
  578. }
  579. clear() {
  580. this._map.clear();
  581. this._statItemsShared = 0;
  582. this._statItemsUnshared = 0;
  583. this._statSharedSnapshots = 0;
  584. this._statReusedSharedSnapshots = 0;
  585. }
  586. /**
  587. * @param {Snapshot} newSnapshot snapshot
  588. * @param {Set<string>} capturedFiles files to snapshot/share
  589. * @returns {void}
  590. */
  591. optimize(newSnapshot, capturedFiles) {
  592. if (capturedFiles.size === 0) {
  593. return;
  594. }
  595. /**
  596. * @param {SnapshotOptimizationEntry} entry optimization entry
  597. * @returns {void}
  598. */
  599. const increaseSharedAndStoreOptimizationEntry = (entry) => {
  600. if (entry.children !== undefined) {
  601. for (const child of entry.children) {
  602. increaseSharedAndStoreOptimizationEntry(child);
  603. }
  604. }
  605. entry.shared++;
  606. storeOptimizationEntry(entry);
  607. };
  608. /**
  609. * @param {SnapshotOptimizationEntry} entry optimization entry
  610. * @returns {void}
  611. */
  612. const storeOptimizationEntry = (entry) => {
  613. for (const path of /** @type {SnapshotContent} */ (
  614. entry.snapshotContent
  615. )) {
  616. const old =
  617. /** @type {SnapshotOptimizationEntry} */
  618. (this._map.get(path));
  619. if (old.shared < entry.shared) {
  620. this._map.set(path, entry);
  621. }
  622. capturedFiles.delete(path);
  623. }
  624. };
  625. /** @type {SnapshotOptimizationEntry | undefined} */
  626. let newOptimizationEntry;
  627. const capturedFilesSize = capturedFiles.size;
  628. /** @type {Set<SnapshotOptimizationEntry> | undefined} */
  629. const optimizationEntries = new Set();
  630. for (const path of capturedFiles) {
  631. const optimizationEntry = this._map.get(path);
  632. if (optimizationEntry === undefined) {
  633. if (newOptimizationEntry === undefined) {
  634. newOptimizationEntry = {
  635. snapshot: newSnapshot,
  636. shared: 0,
  637. snapshotContent: undefined,
  638. children: undefined
  639. };
  640. }
  641. this._map.set(path, newOptimizationEntry);
  642. } else {
  643. optimizationEntries.add(optimizationEntry);
  644. }
  645. }
  646. optimizationEntriesLabel: for (const optimizationEntry of optimizationEntries) {
  647. const snapshot = optimizationEntry.snapshot;
  648. if (optimizationEntry.shared > 0) {
  649. // It's a shared snapshot
  650. // We can't change it, so we can only use it when all files match
  651. // and startTime is compatible
  652. if (
  653. this._useStartTime &&
  654. newSnapshot.startTime &&
  655. (!snapshot.startTime || snapshot.startTime > newSnapshot.startTime)
  656. ) {
  657. continue;
  658. }
  659. /** @type {Set<string>} */
  660. const nonSharedFiles = new Set();
  661. const snapshotContent =
  662. /** @type {NonNullable<SnapshotOptimizationEntry["snapshotContent"]>} */
  663. (optimizationEntry.snapshotContent);
  664. const snapshotEntries =
  665. /** @type {SnapshotOptimizationValue<U, T>} */
  666. (this._get(snapshot));
  667. for (const path of snapshotContent) {
  668. if (!capturedFiles.has(path)) {
  669. if (!snapshotEntries.has(path)) {
  670. // File is not shared and can't be removed from the snapshot
  671. // because it's in a child of the snapshot
  672. continue optimizationEntriesLabel;
  673. }
  674. nonSharedFiles.add(path);
  675. }
  676. }
  677. if (nonSharedFiles.size === 0) {
  678. // The complete snapshot is shared
  679. // add it as child
  680. newSnapshot.addChild(snapshot);
  681. increaseSharedAndStoreOptimizationEntry(optimizationEntry);
  682. this._statReusedSharedSnapshots++;
  683. } else {
  684. // Only a part of the snapshot is shared
  685. const sharedCount = snapshotContent.size - nonSharedFiles.size;
  686. if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) {
  687. // Common part it too small
  688. continue;
  689. }
  690. // Extract common timestamps from both snapshots
  691. let commonMap;
  692. if (this._isSet) {
  693. commonMap = new Set();
  694. for (const path of /** @type {Set<string>} */ (snapshotEntries)) {
  695. if (nonSharedFiles.has(path)) continue;
  696. commonMap.add(path);
  697. snapshotEntries.delete(path);
  698. }
  699. } else {
  700. commonMap = new Map();
  701. const map = /** @type {Map<string, T>} */ (snapshotEntries);
  702. for (const [path, value] of map) {
  703. if (nonSharedFiles.has(path)) continue;
  704. commonMap.set(path, value);
  705. snapshotEntries.delete(path);
  706. }
  707. }
  708. // Create and attach snapshot
  709. const commonSnapshot = new Snapshot();
  710. if (this._useStartTime) {
  711. commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot);
  712. }
  713. this._set(
  714. commonSnapshot,
  715. /** @type {SnapshotOptimizationValue<U, T>} */ (commonMap)
  716. );
  717. newSnapshot.addChild(commonSnapshot);
  718. snapshot.addChild(commonSnapshot);
  719. // Create optimization entry
  720. const newEntry = {
  721. snapshot: commonSnapshot,
  722. shared: optimizationEntry.shared + 1,
  723. snapshotContent: new Set(commonMap.keys()),
  724. children: undefined
  725. };
  726. if (optimizationEntry.children === undefined) {
  727. optimizationEntry.children = new Set();
  728. }
  729. optimizationEntry.children.add(newEntry);
  730. storeOptimizationEntry(newEntry);
  731. this._statSharedSnapshots++;
  732. }
  733. } else {
  734. // It's a unshared snapshot
  735. // We can extract a common shared snapshot
  736. // with all common files
  737. const snapshotEntries = this._get(snapshot);
  738. if (snapshotEntries === undefined) {
  739. // Incomplete snapshot, that can't be used
  740. continue;
  741. }
  742. let commonMap;
  743. if (this._isSet) {
  744. commonMap = new Set();
  745. const set = /** @type {Set<string>} */ (snapshotEntries);
  746. if (capturedFiles.size < set.size) {
  747. for (const path of capturedFiles) {
  748. if (set.has(path)) commonMap.add(path);
  749. }
  750. } else {
  751. for (const path of set) {
  752. if (capturedFiles.has(path)) commonMap.add(path);
  753. }
  754. }
  755. } else {
  756. commonMap = new Map();
  757. const map = /** @type {Map<string, T>} */ (snapshotEntries);
  758. for (const path of capturedFiles) {
  759. const ts = map.get(path);
  760. if (ts === undefined) continue;
  761. commonMap.set(path, ts);
  762. }
  763. }
  764. if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) {
  765. // Common part it too small
  766. continue;
  767. }
  768. // Create and attach snapshot
  769. const commonSnapshot = new Snapshot();
  770. if (this._useStartTime) {
  771. commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot);
  772. }
  773. this._set(
  774. commonSnapshot,
  775. /** @type {SnapshotOptimizationValue<U, T>} */
  776. (commonMap)
  777. );
  778. newSnapshot.addChild(commonSnapshot);
  779. snapshot.addChild(commonSnapshot);
  780. // Remove files from snapshot
  781. for (const path of commonMap.keys()) snapshotEntries.delete(path);
  782. const sharedCount = commonMap.size;
  783. this._statItemsUnshared -= sharedCount;
  784. this._statItemsShared += sharedCount;
  785. // Create optimization entry
  786. storeOptimizationEntry({
  787. snapshot: commonSnapshot,
  788. shared: 2,
  789. snapshotContent: new Set(commonMap.keys()),
  790. children: undefined
  791. });
  792. this._statSharedSnapshots++;
  793. }
  794. }
  795. const unshared = capturedFiles.size;
  796. this._statItemsUnshared += unshared;
  797. this._statItemsShared += capturedFilesSize - unshared;
  798. }
  799. }
  800. /**
  801. * @param {string} str input
  802. * @returns {string} result
  803. */
  804. const parseString = (str) => {
  805. if (str[0] === "'" || str[0] === "`") {
  806. str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`;
  807. }
  808. return JSON.parse(str);
  809. };
  810. /* istanbul ignore next */
  811. /**
  812. * @param {number} mtime mtime
  813. */
  814. const applyMtime = (mtime) => {
  815. if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1;
  816. else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10;
  817. else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100;
  818. else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000;
  819. };
  820. /**
  821. * @template T
  822. * @template K
  823. * @param {Map<T, K> | undefined} a source map
  824. * @param {Map<T, K> | undefined} b joining map
  825. * @returns {Map<T, K>} joined map
  826. */
  827. const mergeMaps = (a, b) => {
  828. if (!b || b.size === 0) return /** @type {Map<T, K>} */ (a);
  829. if (!a || a.size === 0) return /** @type {Map<T, K>} */ (b);
  830. /** @type {Map<T, K>} */
  831. const map = new Map(a);
  832. for (const [key, value] of b) {
  833. map.set(key, value);
  834. }
  835. return map;
  836. };
  837. /**
  838. * @template T
  839. * @param {Set<T> | undefined} a source map
  840. * @param {Set<T> | undefined} b joining map
  841. * @returns {Set<T>} joined map
  842. */
  843. const mergeSets = (a, b) => {
  844. if (!b || b.size === 0) return /** @type {Set<T>} */ (a);
  845. if (!a || a.size === 0) return /** @type {Set<T>} */ (b);
  846. /** @type {Set<T>} */
  847. const map = new Set(a);
  848. for (const item of b) {
  849. map.add(item);
  850. }
  851. return map;
  852. };
  853. /**
  854. * Finding file or directory to manage
  855. * @param {string} managedPath path that is managing by {@link FileSystemInfo}
  856. * @param {string} path path to file or directory
  857. * @returns {string|null} managed item
  858. * @example
  859. * getManagedItem(
  860. * '/Users/user/my-project/node_modules/',
  861. * '/Users/user/my-project/node_modules/package/index.js'
  862. * ) === '/Users/user/my-project/node_modules/package'
  863. * getManagedItem(
  864. * '/Users/user/my-project/node_modules/',
  865. * '/Users/user/my-project/node_modules/package1/node_modules/package2'
  866. * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2'
  867. * getManagedItem(
  868. * '/Users/user/my-project/node_modules/',
  869. * '/Users/user/my-project/node_modules/.bin/script.js'
  870. * ) === null // hidden files are disallowed as managed items
  871. * getManagedItem(
  872. * '/Users/user/my-project/node_modules/',
  873. * '/Users/user/my-project/node_modules/package'
  874. * ) === '/Users/user/my-project/node_modules/package'
  875. */
  876. const getManagedItem = (managedPath, path) => {
  877. let i = managedPath.length;
  878. let slashes = 1;
  879. let startingPosition = true;
  880. loop: while (i < path.length) {
  881. switch (path.charCodeAt(i)) {
  882. case 47: // slash
  883. case 92: // backslash
  884. if (--slashes === 0) break loop;
  885. startingPosition = true;
  886. break;
  887. case 46: // .
  888. // hidden files are disallowed as managed items
  889. // it's probably .yarn-integrity or .cache
  890. if (startingPosition) return null;
  891. break;
  892. case 64: // @
  893. if (!startingPosition) return null;
  894. slashes++;
  895. break;
  896. default:
  897. startingPosition = false;
  898. break;
  899. }
  900. i++;
  901. }
  902. if (i === path.length) slashes--;
  903. // return null when path is incomplete
  904. if (slashes !== 0) return null;
  905. // if (path.slice(i + 1, i + 13) === "node_modules")
  906. if (
  907. path.length >= i + 13 &&
  908. path.charCodeAt(i + 1) === 110 &&
  909. path.charCodeAt(i + 2) === 111 &&
  910. path.charCodeAt(i + 3) === 100 &&
  911. path.charCodeAt(i + 4) === 101 &&
  912. path.charCodeAt(i + 5) === 95 &&
  913. path.charCodeAt(i + 6) === 109 &&
  914. path.charCodeAt(i + 7) === 111 &&
  915. path.charCodeAt(i + 8) === 100 &&
  916. path.charCodeAt(i + 9) === 117 &&
  917. path.charCodeAt(i + 10) === 108 &&
  918. path.charCodeAt(i + 11) === 101 &&
  919. path.charCodeAt(i + 12) === 115
  920. ) {
  921. // if this is the end of the path
  922. if (path.length === i + 13) {
  923. // return the node_modules directory
  924. // it's special
  925. return path;
  926. }
  927. const c = path.charCodeAt(i + 13);
  928. // if next symbol is slash or backslash
  929. if (c === 47 || c === 92) {
  930. // Managed subpath
  931. return getManagedItem(path.slice(0, i + 14), path);
  932. }
  933. }
  934. return path.slice(0, i);
  935. };
  936. /**
  937. * @template {ContextFileSystemInfoEntry | ContextTimestampAndHash} T
  938. * @param {T | null} entry entry
  939. * @returns {T["resolved"] | null | undefined} the resolved entry
  940. */
  941. const getResolvedTimestamp = (entry) => {
  942. if (entry === null) return null;
  943. if (entry.resolved !== undefined) return entry.resolved;
  944. return entry.symlinks === undefined ? entry : undefined;
  945. };
  946. /**
  947. * @param {ContextHash | null} entry entry
  948. * @returns {string | null | undefined} the resolved entry
  949. */
  950. const getResolvedHash = (entry) => {
  951. if (entry === null) return null;
  952. if (entry.resolved !== undefined) return entry.resolved;
  953. return entry.symlinks === undefined ? entry.hash : undefined;
  954. };
  955. /**
  956. * @template T
  957. * @param {Set<T>} source source
  958. * @param {Set<T>} target target
  959. */
  960. const addAll = (source, target) => {
  961. for (const key of source) target.add(key);
  962. };
  963. const getEsModuleLexer = memoize(() => require("es-module-lexer"));
  964. /** @typedef {Set<string>} LoggedPaths */
  965. /** @typedef {FileSystemInfoEntry | "ignore" | null} FileTimestamp */
  966. /** @typedef {ContextFileSystemInfoEntry | "ignore" | null} ContextTimestamp */
  967. /** @typedef {ResolvedContextFileSystemInfoEntry | "ignore" | null} ResolvedContextTimestamp */
  968. /** @typedef {(err?: WebpackError | null, result?: boolean) => void} CheckSnapshotValidCallback */
  969. /**
  970. * Used to access information about the filesystem in a cached way
  971. */
  972. class FileSystemInfo {
  973. /**
  974. * @param {InputFileSystem} fs file system
  975. * @param {object} options options
  976. * @param {Iterable<string | RegExp>=} options.unmanagedPaths paths that are not managed by a package manager and the contents are subject to change
  977. * @param {Iterable<string | RegExp>=} options.managedPaths paths that are only managed by a package manager
  978. * @param {Iterable<string | RegExp>=} options.immutablePaths paths that are immutable
  979. * @param {Logger=} options.logger logger used to log invalid snapshots
  980. * @param {HashFunction=} options.hashFunction the hash function to use
  981. */
  982. constructor(
  983. fs,
  984. {
  985. unmanagedPaths = [],
  986. managedPaths = [],
  987. immutablePaths = [],
  988. logger,
  989. hashFunction = DEFAULTS.HASH_FUNCTION
  990. } = {}
  991. ) {
  992. this.fs = fs;
  993. this.logger = logger;
  994. this._remainingLogs = logger ? 40 : 0;
  995. /** @type {LoggedPaths | undefined} */
  996. this._loggedPaths = logger ? new Set() : undefined;
  997. this._hashFunction = hashFunction;
  998. /** @type {WeakMap<Snapshot, boolean | CheckSnapshotValidCallback[]>} */
  999. this._snapshotCache = new WeakMap();
  1000. this._fileTimestampsOptimization = new SnapshotOptimization(
  1001. (s) => s.hasFileTimestamps(),
  1002. (s) => s.fileTimestamps,
  1003. (s, v) => s.setFileTimestamps(v)
  1004. );
  1005. this._fileHashesOptimization = new SnapshotOptimization(
  1006. (s) => s.hasFileHashes(),
  1007. (s) => s.fileHashes,
  1008. (s, v) => s.setFileHashes(v),
  1009. false
  1010. );
  1011. this._fileTshsOptimization = new SnapshotOptimization(
  1012. (s) => s.hasFileTshs(),
  1013. (s) => s.fileTshs,
  1014. (s, v) => s.setFileTshs(v)
  1015. );
  1016. this._contextTimestampsOptimization = new SnapshotOptimization(
  1017. (s) => s.hasContextTimestamps(),
  1018. (s) => s.contextTimestamps,
  1019. (s, v) => s.setContextTimestamps(v)
  1020. );
  1021. this._contextHashesOptimization = new SnapshotOptimization(
  1022. (s) => s.hasContextHashes(),
  1023. (s) => s.contextHashes,
  1024. (s, v) => s.setContextHashes(v),
  1025. false
  1026. );
  1027. this._contextTshsOptimization = new SnapshotOptimization(
  1028. (s) => s.hasContextTshs(),
  1029. (s) => s.contextTshs,
  1030. (s, v) => s.setContextTshs(v)
  1031. );
  1032. this._missingExistenceOptimization = new SnapshotOptimization(
  1033. (s) => s.hasMissingExistence(),
  1034. (s) => s.missingExistence,
  1035. (s, v) => s.setMissingExistence(v),
  1036. false
  1037. );
  1038. this._managedItemInfoOptimization = new SnapshotOptimization(
  1039. (s) => s.hasManagedItemInfo(),
  1040. (s) => s.managedItemInfo,
  1041. (s, v) => s.setManagedItemInfo(v),
  1042. false
  1043. );
  1044. this._managedFilesOptimization = new SnapshotOptimization(
  1045. (s) => s.hasManagedFiles(),
  1046. (s) => s.managedFiles,
  1047. (s, v) => s.setManagedFiles(v),
  1048. false,
  1049. true
  1050. );
  1051. this._managedContextsOptimization = new SnapshotOptimization(
  1052. (s) => s.hasManagedContexts(),
  1053. (s) => s.managedContexts,
  1054. (s, v) => s.setManagedContexts(v),
  1055. false,
  1056. true
  1057. );
  1058. this._managedMissingOptimization = new SnapshotOptimization(
  1059. (s) => s.hasManagedMissing(),
  1060. (s) => s.managedMissing,
  1061. (s, v) => s.setManagedMissing(v),
  1062. false,
  1063. true
  1064. );
  1065. /** @type {StackedCacheMap<string, FileTimestamp>} */
  1066. this._fileTimestamps = new StackedCacheMap();
  1067. /** @type {Map<string, string | null>} */
  1068. this._fileHashes = new Map();
  1069. /** @type {Map<string, TimestampAndHash | string>} */
  1070. this._fileTshs = new Map();
  1071. /** @type {StackedCacheMap<string, ContextTimestamp>} */
  1072. this._contextTimestamps = new StackedCacheMap();
  1073. /** @type {Map<string, ContextHash>} */
  1074. this._contextHashes = new Map();
  1075. /** @type {Map<string, ContextTimestampAndHash>} */
  1076. this._contextTshs = new Map();
  1077. /** @type {Map<string, string>} */
  1078. this._managedItems = new Map();
  1079. /** @type {AsyncQueue<string, string, FileSystemInfoEntry>} */
  1080. this.fileTimestampQueue = new AsyncQueue({
  1081. name: "file timestamp",
  1082. parallelism: 30,
  1083. processor: this._readFileTimestamp.bind(this)
  1084. });
  1085. /** @type {AsyncQueue<string, string, string>} */
  1086. this.fileHashQueue = new AsyncQueue({
  1087. name: "file hash",
  1088. parallelism: 10,
  1089. processor: this._readFileHash.bind(this)
  1090. });
  1091. /** @type {AsyncQueue<string, string, ContextFileSystemInfoEntry>} */
  1092. this.contextTimestampQueue = new AsyncQueue({
  1093. name: "context timestamp",
  1094. parallelism: 2,
  1095. processor: this._readContextTimestamp.bind(this)
  1096. });
  1097. /** @type {AsyncQueue<string, string, ContextHash>} */
  1098. this.contextHashQueue = new AsyncQueue({
  1099. name: "context hash",
  1100. parallelism: 2,
  1101. processor: this._readContextHash.bind(this)
  1102. });
  1103. /** @type {AsyncQueue<string, string, ContextTimestampAndHash>} */
  1104. this.contextTshQueue = new AsyncQueue({
  1105. name: "context hash and timestamp",
  1106. parallelism: 2,
  1107. processor: this._readContextTimestampAndHash.bind(this)
  1108. });
  1109. /** @type {AsyncQueue<string, string, string>} */
  1110. this.managedItemQueue = new AsyncQueue({
  1111. name: "managed item info",
  1112. parallelism: 10,
  1113. processor: this._getManagedItemInfo.bind(this)
  1114. });
  1115. /** @type {AsyncQueue<string, string, Set<string>>} */
  1116. this.managedItemDirectoryQueue = new AsyncQueue({
  1117. name: "managed item directory info",
  1118. parallelism: 10,
  1119. processor: this._getManagedItemDirectoryInfo.bind(this)
  1120. });
  1121. const _unmanagedPaths = [...unmanagedPaths];
  1122. /** @type {string[]} */
  1123. this.unmanagedPathsWithSlash = _unmanagedPaths
  1124. .filter((p) => typeof p === "string")
  1125. .map((p) => join(fs, p, "_").slice(0, -1));
  1126. /** @type {RegExp[]} */
  1127. this.unmanagedPathsRegExps = _unmanagedPaths.filter(
  1128. (p) => typeof p !== "string"
  1129. );
  1130. this.managedPaths = [...managedPaths];
  1131. /** @type {string[]} */
  1132. this.managedPathsWithSlash = this.managedPaths
  1133. .filter((p) => typeof p === "string")
  1134. .map((p) => join(fs, p, "_").slice(0, -1));
  1135. /** @type {RegExp[]} */
  1136. this.managedPathsRegExps = this.managedPaths.filter(
  1137. (p) => typeof p !== "string"
  1138. );
  1139. this.immutablePaths = [...immutablePaths];
  1140. /** @type {string[]} */
  1141. this.immutablePathsWithSlash = this.immutablePaths
  1142. .filter((p) => typeof p === "string")
  1143. .map((p) => join(fs, p, "_").slice(0, -1));
  1144. /** @type {RegExp[]} */
  1145. this.immutablePathsRegExps = this.immutablePaths.filter(
  1146. (p) => typeof p !== "string"
  1147. );
  1148. this._cachedDeprecatedFileTimestamps = undefined;
  1149. this._cachedDeprecatedContextTimestamps = undefined;
  1150. this._warnAboutExperimentalEsmTracking = false;
  1151. this._statCreatedSnapshots = 0;
  1152. this._statTestedSnapshotsCached = 0;
  1153. this._statTestedSnapshotsNotCached = 0;
  1154. this._statTestedChildrenCached = 0;
  1155. this._statTestedChildrenNotCached = 0;
  1156. this._statTestedEntries = 0;
  1157. }
  1158. logStatistics() {
  1159. const logger = /** @type {Logger} */ (this.logger);
  1160. /**
  1161. * @param {string} header header
  1162. * @param {string | undefined} message message
  1163. */
  1164. const logWhenMessage = (header, message) => {
  1165. if (message) {
  1166. logger.log(`${header}: ${message}`);
  1167. }
  1168. };
  1169. logger.log(`${this._statCreatedSnapshots} new snapshots created`);
  1170. logger.log(
  1171. `${
  1172. this._statTestedSnapshotsNotCached &&
  1173. Math.round(
  1174. (this._statTestedSnapshotsNotCached * 100) /
  1175. (this._statTestedSnapshotsCached +
  1176. this._statTestedSnapshotsNotCached)
  1177. )
  1178. }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${
  1179. this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached
  1180. })`
  1181. );
  1182. logger.log(
  1183. `${
  1184. this._statTestedChildrenNotCached &&
  1185. Math.round(
  1186. (this._statTestedChildrenNotCached * 100) /
  1187. (this._statTestedChildrenCached + this._statTestedChildrenNotCached)
  1188. )
  1189. }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${
  1190. this._statTestedChildrenCached + this._statTestedChildrenNotCached
  1191. })`
  1192. );
  1193. logger.log(`${this._statTestedEntries} entries tested`);
  1194. logger.log(
  1195. `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations`
  1196. );
  1197. logWhenMessage(
  1198. "File timestamp snapshot optimization",
  1199. this._fileTimestampsOptimization.getStatisticMessage()
  1200. );
  1201. logWhenMessage(
  1202. "File hash snapshot optimization",
  1203. this._fileHashesOptimization.getStatisticMessage()
  1204. );
  1205. logWhenMessage(
  1206. "File timestamp hash combination snapshot optimization",
  1207. this._fileTshsOptimization.getStatisticMessage()
  1208. );
  1209. logger.log(
  1210. `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations`
  1211. );
  1212. logWhenMessage(
  1213. "Directory timestamp snapshot optimization",
  1214. this._contextTimestampsOptimization.getStatisticMessage()
  1215. );
  1216. logWhenMessage(
  1217. "Directory hash snapshot optimization",
  1218. this._contextHashesOptimization.getStatisticMessage()
  1219. );
  1220. logWhenMessage(
  1221. "Directory timestamp hash combination snapshot optimization",
  1222. this._contextTshsOptimization.getStatisticMessage()
  1223. );
  1224. logWhenMessage(
  1225. "Missing items snapshot optimization",
  1226. this._missingExistenceOptimization.getStatisticMessage()
  1227. );
  1228. logger.log(`Managed items info in cache: ${this._managedItems.size} items`);
  1229. logWhenMessage(
  1230. "Managed items snapshot optimization",
  1231. this._managedItemInfoOptimization.getStatisticMessage()
  1232. );
  1233. logWhenMessage(
  1234. "Managed files snapshot optimization",
  1235. this._managedFilesOptimization.getStatisticMessage()
  1236. );
  1237. logWhenMessage(
  1238. "Managed contexts snapshot optimization",
  1239. this._managedContextsOptimization.getStatisticMessage()
  1240. );
  1241. logWhenMessage(
  1242. "Managed missing snapshot optimization",
  1243. this._managedMissingOptimization.getStatisticMessage()
  1244. );
  1245. }
  1246. /**
  1247. * @private
  1248. * @param {string} path path
  1249. * @param {string} reason reason
  1250. * @param {EXPECTED_ANY[]} args arguments
  1251. */
  1252. _log(path, reason, ...args) {
  1253. const key = path + reason;
  1254. const loggedPaths = /** @type {LoggedPaths} */ (this._loggedPaths);
  1255. if (loggedPaths.has(key)) return;
  1256. loggedPaths.add(key);
  1257. /** @type {Logger} */
  1258. (this.logger).debug(`${path} invalidated because ${reason}`, ...args);
  1259. if (--this._remainingLogs === 0) {
  1260. /** @type {Logger} */
  1261. (this.logger).debug(
  1262. "Logging limit has been reached and no further logging will be emitted by FileSystemInfo"
  1263. );
  1264. }
  1265. }
  1266. clear() {
  1267. this._remainingLogs = this.logger ? 40 : 0;
  1268. if (this._loggedPaths !== undefined) this._loggedPaths.clear();
  1269. this._snapshotCache = new WeakMap();
  1270. this._fileTimestampsOptimization.clear();
  1271. this._fileHashesOptimization.clear();
  1272. this._fileTshsOptimization.clear();
  1273. this._contextTimestampsOptimization.clear();
  1274. this._contextHashesOptimization.clear();
  1275. this._contextTshsOptimization.clear();
  1276. this._missingExistenceOptimization.clear();
  1277. this._managedItemInfoOptimization.clear();
  1278. this._managedFilesOptimization.clear();
  1279. this._managedContextsOptimization.clear();
  1280. this._managedMissingOptimization.clear();
  1281. this._fileTimestamps.clear();
  1282. this._fileHashes.clear();
  1283. this._fileTshs.clear();
  1284. this._contextTimestamps.clear();
  1285. this._contextHashes.clear();
  1286. this._contextTshs.clear();
  1287. this._managedItems.clear();
  1288. this._managedItems.clear();
  1289. this._cachedDeprecatedFileTimestamps = undefined;
  1290. this._cachedDeprecatedContextTimestamps = undefined;
  1291. this._statCreatedSnapshots = 0;
  1292. this._statTestedSnapshotsCached = 0;
  1293. this._statTestedSnapshotsNotCached = 0;
  1294. this._statTestedChildrenCached = 0;
  1295. this._statTestedChildrenNotCached = 0;
  1296. this._statTestedEntries = 0;
  1297. }
  1298. /**
  1299. * @param {ReadonlyMap<string, FileTimestamp>} map timestamps
  1300. * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it
  1301. * @returns {void}
  1302. */
  1303. addFileTimestamps(map, immutable) {
  1304. this._fileTimestamps.addAll(map, immutable);
  1305. this._cachedDeprecatedFileTimestamps = undefined;
  1306. }
  1307. /**
  1308. * @param {ReadonlyMap<string, ContextTimestamp>} map timestamps
  1309. * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it
  1310. * @returns {void}
  1311. */
  1312. addContextTimestamps(map, immutable) {
  1313. this._contextTimestamps.addAll(map, immutable);
  1314. this._cachedDeprecatedContextTimestamps = undefined;
  1315. }
  1316. /**
  1317. * @param {string} path file path
  1318. * @param {(err?: WebpackError | null, fileTimestamp?: FileTimestamp) => void} callback callback function
  1319. * @returns {void}
  1320. */
  1321. getFileTimestamp(path, callback) {
  1322. const cache = this._fileTimestamps.get(path);
  1323. if (cache !== undefined) return callback(null, cache);
  1324. this.fileTimestampQueue.add(path, callback);
  1325. }
  1326. /**
  1327. * @param {string} path context path
  1328. * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback function
  1329. * @returns {void}
  1330. */
  1331. getContextTimestamp(path, callback) {
  1332. const cache = this._contextTimestamps.get(path);
  1333. if (cache !== undefined) {
  1334. if (cache === "ignore") return callback(null, "ignore");
  1335. const resolved = getResolvedTimestamp(cache);
  1336. if (resolved !== undefined) return callback(null, resolved);
  1337. return this._resolveContextTimestamp(
  1338. /** @type {ResolvedContextFileSystemInfoEntry} */
  1339. (cache),
  1340. callback
  1341. );
  1342. }
  1343. this.contextTimestampQueue.add(path, (err, _entry) => {
  1344. if (err) return callback(err);
  1345. const entry = /** @type {ContextFileSystemInfoEntry} */ (_entry);
  1346. const resolved = getResolvedTimestamp(entry);
  1347. if (resolved !== undefined) return callback(null, resolved);
  1348. this._resolveContextTimestamp(entry, callback);
  1349. });
  1350. }
  1351. /**
  1352. * @private
  1353. * @param {string} path context path
  1354. * @param {(err?: WebpackError | null, contextTimestamp?: ContextTimestamp) => void} callback callback function
  1355. * @returns {void}
  1356. */
  1357. _getUnresolvedContextTimestamp(path, callback) {
  1358. const cache = this._contextTimestamps.get(path);
  1359. if (cache !== undefined) return callback(null, cache);
  1360. this.contextTimestampQueue.add(path, callback);
  1361. }
  1362. /**
  1363. * @param {string} path file path
  1364. * @param {(err?: WebpackError | null, hash?: string | null) => void} callback callback function
  1365. * @returns {void}
  1366. */
  1367. getFileHash(path, callback) {
  1368. const cache = this._fileHashes.get(path);
  1369. if (cache !== undefined) return callback(null, cache);
  1370. this.fileHashQueue.add(path, callback);
  1371. }
  1372. /**
  1373. * @param {string} path context path
  1374. * @param {(err?: WebpackError | null, contextHash?: string) => void} callback callback function
  1375. * @returns {void}
  1376. */
  1377. getContextHash(path, callback) {
  1378. const cache = this._contextHashes.get(path);
  1379. if (cache !== undefined) {
  1380. const resolved = getResolvedHash(cache);
  1381. if (resolved !== undefined) {
  1382. return callback(null, /** @type {string} */ (resolved));
  1383. }
  1384. return this._resolveContextHash(cache, callback);
  1385. }
  1386. this.contextHashQueue.add(path, (err, _entry) => {
  1387. if (err) return callback(err);
  1388. const entry = /** @type {ContextHash} */ (_entry);
  1389. const resolved = getResolvedHash(entry);
  1390. if (resolved !== undefined) {
  1391. return callback(null, /** @type {string} */ (resolved));
  1392. }
  1393. this._resolveContextHash(entry, callback);
  1394. });
  1395. }
  1396. /**
  1397. * @private
  1398. * @param {string} path context path
  1399. * @param {(err?: WebpackError | null, contextHash?: ContextHash | null) => void} callback callback function
  1400. * @returns {void}
  1401. */
  1402. _getUnresolvedContextHash(path, callback) {
  1403. const cache = this._contextHashes.get(path);
  1404. if (cache !== undefined) return callback(null, cache);
  1405. this.contextHashQueue.add(path, callback);
  1406. }
  1407. /**
  1408. * @param {string} path context path
  1409. * @param {(err?: WebpackError | null, resolvedContextTimestampAndHash?: ResolvedContextTimestampAndHash | null) => void} callback callback function
  1410. * @returns {void}
  1411. */
  1412. getContextTsh(path, callback) {
  1413. const cache = this._contextTshs.get(path);
  1414. if (cache !== undefined) {
  1415. const resolved = getResolvedTimestamp(cache);
  1416. if (resolved !== undefined) return callback(null, resolved);
  1417. return this._resolveContextTsh(cache, callback);
  1418. }
  1419. this.contextTshQueue.add(path, (err, _entry) => {
  1420. if (err) return callback(err);
  1421. const entry = /** @type {ContextTimestampAndHash} */ (_entry);
  1422. const resolved = getResolvedTimestamp(entry);
  1423. if (resolved !== undefined) return callback(null, resolved);
  1424. this._resolveContextTsh(entry, callback);
  1425. });
  1426. }
  1427. /**
  1428. * @private
  1429. * @param {string} path context path
  1430. * @param {(err?: WebpackError | null, contextTimestampAndHash?: ContextTimestampAndHash | null) => void} callback callback function
  1431. * @returns {void}
  1432. */
  1433. _getUnresolvedContextTsh(path, callback) {
  1434. const cache = this._contextTshs.get(path);
  1435. if (cache !== undefined) return callback(null, cache);
  1436. this.contextTshQueue.add(path, callback);
  1437. }
  1438. _createBuildDependenciesResolvers() {
  1439. const resolveContext = createResolver({
  1440. resolveToContext: true,
  1441. exportsFields: [],
  1442. fileSystem: this.fs
  1443. });
  1444. const resolveCjs = createResolver({
  1445. extensions: [".js", ".json", ".node"],
  1446. conditionNames: ["require", "node"],
  1447. exportsFields: ["exports"],
  1448. fileSystem: this.fs
  1449. });
  1450. const resolveCjsAsChild = createResolver({
  1451. extensions: [".js", ".json", ".node"],
  1452. conditionNames: ["require", "node"],
  1453. exportsFields: [],
  1454. fileSystem: this.fs
  1455. });
  1456. const resolveEsm = createResolver({
  1457. extensions: [".js", ".json", ".node"],
  1458. fullySpecified: true,
  1459. conditionNames: ["import", "node"],
  1460. exportsFields: ["exports"],
  1461. fileSystem: this.fs
  1462. });
  1463. return { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild };
  1464. }
  1465. /**
  1466. * @param {string} context context directory
  1467. * @param {Iterable<string>} deps dependencies
  1468. * @param {(err?: Error | null, resolveBuildDependenciesResult?: ResolveBuildDependenciesResult) => void} callback callback function
  1469. * @returns {void}
  1470. */
  1471. resolveBuildDependencies(context, deps, callback) {
  1472. const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } =
  1473. this._createBuildDependenciesResolvers();
  1474. /** @type {Files} */
  1475. const files = new Set();
  1476. /** @type {Symlinks} */
  1477. const fileSymlinks = new Set();
  1478. /** @type {Directories} */
  1479. const directories = new Set();
  1480. /** @type {Symlinks} */
  1481. const directorySymlinks = new Set();
  1482. /** @type {Missing} */
  1483. const missing = new Set();
  1484. /** @type {ResolveDependencies["files"]} */
  1485. const resolveFiles = new Set();
  1486. /** @type {ResolveDependencies["directories"]} */
  1487. const resolveDirectories = new Set();
  1488. /** @type {ResolveDependencies["missing"]} */
  1489. const resolveMissing = new Set();
  1490. /** @type {ResolveResults} */
  1491. const resolveResults = new Map();
  1492. /** @type {Set<string>} */
  1493. const invalidResolveResults = new Set();
  1494. const resolverContext = {
  1495. fileDependencies: resolveFiles,
  1496. contextDependencies: resolveDirectories,
  1497. missingDependencies: resolveMissing
  1498. };
  1499. /**
  1500. * @param {undefined | boolean | string} expected expected result
  1501. * @returns {string} expected result
  1502. */
  1503. const expectedToString = (expected) =>
  1504. expected ? ` (expected ${expected})` : "";
  1505. /** @typedef {{ type: JobType, context: string | undefined, path: string, issuer: Job | undefined, expected: undefined | boolean | string }} Job */
  1506. /**
  1507. * @param {Job} job job
  1508. * @returns {string} result
  1509. */
  1510. const jobToString = (job) => {
  1511. switch (job.type) {
  1512. case RBDT_RESOLVE_FILE:
  1513. return `resolve file ${job.path}${expectedToString(job.expected)}`;
  1514. case RBDT_RESOLVE_DIRECTORY:
  1515. return `resolve directory ${job.path}`;
  1516. case RBDT_RESOLVE_CJS_FILE:
  1517. return `resolve commonjs file ${job.path}${expectedToString(
  1518. job.expected
  1519. )}`;
  1520. case RBDT_RESOLVE_ESM_FILE:
  1521. return `resolve esm file ${job.path}${expectedToString(
  1522. job.expected
  1523. )}`;
  1524. case RBDT_DIRECTORY:
  1525. return `directory ${job.path}`;
  1526. case RBDT_FILE:
  1527. return `file ${job.path}`;
  1528. case RBDT_DIRECTORY_DEPENDENCIES:
  1529. return `directory dependencies ${job.path}`;
  1530. case RBDT_FILE_DEPENDENCIES:
  1531. return `file dependencies ${job.path}`;
  1532. }
  1533. return `unknown ${job.type} ${job.path}`;
  1534. };
  1535. /**
  1536. * @param {Job} job job
  1537. * @returns {string} string value
  1538. */
  1539. const pathToString = (job) => {
  1540. let result = ` at ${jobToString(job)}`;
  1541. /** @type {Job | undefined} */
  1542. (job) = job.issuer;
  1543. while (job !== undefined) {
  1544. result += `\n at ${jobToString(job)}`;
  1545. job = /** @type {Job} */ (job.issuer);
  1546. }
  1547. return result;
  1548. };
  1549. const logger = /** @type {Logger} */ (this.logger);
  1550. processAsyncTree(
  1551. Array.from(
  1552. deps,
  1553. (dep) =>
  1554. /** @type {Job} */ ({
  1555. type: RBDT_RESOLVE_INITIAL,
  1556. context,
  1557. path: dep,
  1558. expected: undefined,
  1559. issuer: undefined
  1560. })
  1561. ),
  1562. 20,
  1563. (job, push, callback) => {
  1564. const { type, context, path, expected } = job;
  1565. /**
  1566. * @param {string} path path
  1567. * @returns {void}
  1568. */
  1569. const resolveDirectory = (path) => {
  1570. const key = `d\n${context}\n${path}`;
  1571. if (resolveResults.has(key)) {
  1572. return callback();
  1573. }
  1574. resolveResults.set(key, undefined);
  1575. resolveContext(
  1576. /** @type {string} */ (context),
  1577. path,
  1578. resolverContext,
  1579. (err, _, result) => {
  1580. if (err) {
  1581. if (expected === false) {
  1582. resolveResults.set(key, false);
  1583. return callback();
  1584. }
  1585. invalidResolveResults.add(key);
  1586. err.message += `\nwhile resolving '${path}' in ${context} to a directory`;
  1587. return callback(err);
  1588. }
  1589. const resultPath = /** @type {ResolveRequest} */ (result).path;
  1590. resolveResults.set(key, resultPath);
  1591. push({
  1592. type: RBDT_DIRECTORY,
  1593. context: undefined,
  1594. path: /** @type {string} */ (resultPath),
  1595. expected: undefined,
  1596. issuer: job
  1597. });
  1598. callback();
  1599. }
  1600. );
  1601. };
  1602. /**
  1603. * @param {string} path path
  1604. * @param {("f" | "c" | "e")=} symbol symbol
  1605. * @param {(ResolveFunctionAsync)=} resolve resolve fn
  1606. * @returns {void}
  1607. */
  1608. const resolveFile = (path, symbol, resolve) => {
  1609. const key = `${symbol}\n${context}\n${path}`;
  1610. if (resolveResults.has(key)) {
  1611. return callback();
  1612. }
  1613. resolveResults.set(key, undefined);
  1614. /** @type {ResolveFunctionAsync} */
  1615. (resolve)(
  1616. /** @type {string} */ (context),
  1617. path,
  1618. resolverContext,
  1619. (err, _, result) => {
  1620. if (typeof expected === "string") {
  1621. if (!err && result && result.path === expected) {
  1622. resolveResults.set(key, result.path);
  1623. } else {
  1624. invalidResolveResults.add(key);
  1625. logger.warn(
  1626. `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${
  1627. err || (result && result.path)
  1628. }' instead. Resolving dependencies are ignored for this path.\n${pathToString(
  1629. job
  1630. )}`
  1631. );
  1632. }
  1633. } else {
  1634. if (err) {
  1635. if (expected === false) {
  1636. resolveResults.set(key, false);
  1637. return callback();
  1638. }
  1639. invalidResolveResults.add(key);
  1640. err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString(
  1641. job
  1642. )}`;
  1643. return callback(err);
  1644. }
  1645. const resultPath = /** @type {ResolveRequest} */ (result).path;
  1646. resolveResults.set(key, resultPath);
  1647. push({
  1648. type: RBDT_FILE,
  1649. context: undefined,
  1650. path: /** @type {string} */ (resultPath),
  1651. expected: undefined,
  1652. issuer: job
  1653. });
  1654. }
  1655. callback();
  1656. }
  1657. );
  1658. };
  1659. const resolvedType =
  1660. type === RBDT_RESOLVE_INITIAL
  1661. ? /[\\/]$/.test(path)
  1662. ? RBDT_RESOLVE_DIRECTORY
  1663. : RBDT_RESOLVE_FILE
  1664. : type;
  1665. switch (resolvedType) {
  1666. case RBDT_RESOLVE_FILE: {
  1667. resolveFile(
  1668. path,
  1669. "f",
  1670. /\.mjs$/.test(path) ? resolveEsm : resolveCjs
  1671. );
  1672. break;
  1673. }
  1674. case RBDT_RESOLVE_DIRECTORY: {
  1675. resolveDirectory(RBDT_RESOLVE_INITIAL ? path.slice(0, -1) : path);
  1676. break;
  1677. }
  1678. case RBDT_RESOLVE_CJS_FILE: {
  1679. resolveFile(path, "f", resolveCjs);
  1680. break;
  1681. }
  1682. case RBDT_RESOLVE_CJS_FILE_AS_CHILD: {
  1683. resolveFile(path, "c", resolveCjsAsChild);
  1684. break;
  1685. }
  1686. case RBDT_RESOLVE_ESM_FILE: {
  1687. resolveFile(path, "e", resolveEsm);
  1688. break;
  1689. }
  1690. case RBDT_FILE: {
  1691. if (files.has(path)) {
  1692. callback();
  1693. break;
  1694. }
  1695. files.add(path);
  1696. /** @type {NonNullable<InputFileSystem["realpath"]>} */
  1697. (this.fs.realpath)(path, (err, _realPath) => {
  1698. if (err) return callback(err);
  1699. const realPath = /** @type {string} */ (_realPath);
  1700. if (realPath !== path) {
  1701. fileSymlinks.add(path);
  1702. resolveFiles.add(path);
  1703. if (files.has(realPath)) return callback();
  1704. files.add(realPath);
  1705. }
  1706. push({
  1707. type: RBDT_FILE_DEPENDENCIES,
  1708. context: undefined,
  1709. path: realPath,
  1710. expected: undefined,
  1711. issuer: job
  1712. });
  1713. callback();
  1714. });
  1715. break;
  1716. }
  1717. case RBDT_DIRECTORY: {
  1718. if (directories.has(path)) {
  1719. callback();
  1720. break;
  1721. }
  1722. directories.add(path);
  1723. /** @type {NonNullable<InputFileSystem["realpath"]>} */
  1724. (this.fs.realpath)(path, (err, _realPath) => {
  1725. if (err) return callback(err);
  1726. const realPath = /** @type {string} */ (_realPath);
  1727. if (realPath !== path) {
  1728. directorySymlinks.add(path);
  1729. resolveFiles.add(path);
  1730. if (directories.has(realPath)) return callback();
  1731. directories.add(realPath);
  1732. }
  1733. push({
  1734. type: RBDT_DIRECTORY_DEPENDENCIES,
  1735. context: undefined,
  1736. path: realPath,
  1737. expected: undefined,
  1738. issuer: job
  1739. });
  1740. callback();
  1741. });
  1742. break;
  1743. }
  1744. case RBDT_FILE_DEPENDENCIES: {
  1745. // Check for known files without dependencies
  1746. if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) {
  1747. process.nextTick(callback);
  1748. break;
  1749. }
  1750. // Check commonjs cache for the module
  1751. /** @type {NodeModule | undefined} */
  1752. const module = require.cache[path];
  1753. if (
  1754. module &&
  1755. Array.isArray(module.children) &&
  1756. // https://github.com/nodejs/node/issues/59868
  1757. // Force use `es-module-lexer` for mjs
  1758. !/\.mjs$/.test(path)
  1759. ) {
  1760. children: for (const child of module.children) {
  1761. const childPath = child.filename;
  1762. if (childPath) {
  1763. push({
  1764. type: RBDT_FILE,
  1765. context: undefined,
  1766. path: childPath,
  1767. expected: undefined,
  1768. issuer: job
  1769. });
  1770. const context = dirname(this.fs, path);
  1771. for (const modulePath of module.paths) {
  1772. if (childPath.startsWith(modulePath)) {
  1773. const subPath = childPath.slice(modulePath.length + 1);
  1774. const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec(
  1775. subPath
  1776. );
  1777. if (packageMatch) {
  1778. push({
  1779. type: RBDT_FILE,
  1780. context: undefined,
  1781. path: `${
  1782. modulePath +
  1783. childPath[modulePath.length] +
  1784. packageMatch[0] +
  1785. childPath[modulePath.length]
  1786. }package.json`,
  1787. expected: false,
  1788. issuer: job
  1789. });
  1790. }
  1791. let request = subPath.replace(/\\/g, "/");
  1792. if (request.endsWith(".js")) {
  1793. request = request.slice(0, -3);
  1794. }
  1795. push({
  1796. type: RBDT_RESOLVE_CJS_FILE_AS_CHILD,
  1797. context,
  1798. path: request,
  1799. expected: child.filename,
  1800. issuer: job
  1801. });
  1802. continue children;
  1803. }
  1804. }
  1805. let request = relative(this.fs, context, childPath);
  1806. if (request.endsWith(".js")) request = request.slice(0, -3);
  1807. request = request.replace(/\\/g, "/");
  1808. if (!request.startsWith("../") && !isAbsolute(request)) {
  1809. request = `./${request}`;
  1810. }
  1811. push({
  1812. type: RBDT_RESOLVE_CJS_FILE,
  1813. context,
  1814. path: request,
  1815. expected: child.filename,
  1816. issuer: job
  1817. });
  1818. }
  1819. }
  1820. } else if (supportsEsm && /\.m?js$/.test(path)) {
  1821. if (!this._warnAboutExperimentalEsmTracking) {
  1822. logger.log(
  1823. "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" +
  1824. "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" +
  1825. "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking."
  1826. );
  1827. this._warnAboutExperimentalEsmTracking = true;
  1828. }
  1829. const lexer = getEsModuleLexer();
  1830. lexer.init.then(() => {
  1831. this.fs.readFile(path, (err, content) => {
  1832. if (err) return callback(err);
  1833. try {
  1834. const context = dirname(this.fs, path);
  1835. const source = /** @type {Buffer} */ (content).toString();
  1836. const [imports] = lexer.parse(source);
  1837. const added = new Set();
  1838. for (const imp of imports) {
  1839. try {
  1840. let dependency;
  1841. if (imp.d === -1) {
  1842. // import ... from "..."
  1843. dependency = parseString(
  1844. source.slice(imp.s - 1, imp.e + 1)
  1845. );
  1846. } else if (imp.d > -1) {
  1847. // import()
  1848. const expr = source.slice(imp.s, imp.e).trim();
  1849. dependency = parseString(expr);
  1850. } else {
  1851. // e.g. import.meta
  1852. continue;
  1853. }
  1854. // We should not track Node.js build dependencies
  1855. if (dependency.startsWith("node:")) continue;
  1856. if (builtinModules.has(dependency)) continue;
  1857. // Avoid extra jobs for identical imports
  1858. if (added.has(dependency)) continue;
  1859. push({
  1860. type: RBDT_RESOLVE_ESM_FILE,
  1861. context,
  1862. path: dependency,
  1863. expected: imp.d > -1 ? false : undefined,
  1864. issuer: job
  1865. });
  1866. added.add(dependency);
  1867. } catch (err1) {
  1868. logger.warn(
  1869. `Parsing of ${path} for build dependencies failed at 'import(${source.slice(
  1870. imp.s,
  1871. imp.e
  1872. )})'.\n` +
  1873. "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation."
  1874. );
  1875. logger.debug(pathToString(job));
  1876. logger.debug(/** @type {Error} */ (err1).stack);
  1877. }
  1878. }
  1879. } catch (err2) {
  1880. logger.warn(
  1881. `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..`
  1882. );
  1883. logger.debug(pathToString(job));
  1884. logger.debug(/** @type {Error} */ (err2).stack);
  1885. }
  1886. process.nextTick(callback);
  1887. });
  1888. }, callback);
  1889. break;
  1890. } else {
  1891. logger.log(
  1892. `Assuming ${path} has no dependencies as we were unable to assign it to any module system.`
  1893. );
  1894. logger.debug(pathToString(job));
  1895. }
  1896. process.nextTick(callback);
  1897. break;
  1898. }
  1899. case RBDT_DIRECTORY_DEPENDENCIES: {
  1900. const match =
  1901. /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path);
  1902. const packagePath = match ? match[1] : path;
  1903. const packageJson = join(this.fs, packagePath, "package.json");
  1904. this.fs.readFile(packageJson, (err, content) => {
  1905. if (err) {
  1906. if (err.code === "ENOENT") {
  1907. resolveMissing.add(packageJson);
  1908. const parent = dirname(this.fs, packagePath);
  1909. if (parent !== packagePath) {
  1910. push({
  1911. type: RBDT_DIRECTORY_DEPENDENCIES,
  1912. context: undefined,
  1913. path: parent,
  1914. expected: undefined,
  1915. issuer: job
  1916. });
  1917. }
  1918. callback();
  1919. return;
  1920. }
  1921. return callback(err);
  1922. }
  1923. resolveFiles.add(packageJson);
  1924. let packageData;
  1925. try {
  1926. packageData = JSON.parse(
  1927. /** @type {Buffer} */
  1928. (content).toString("utf8")
  1929. );
  1930. } catch (parseErr) {
  1931. return callback(/** @type {Error} */ (parseErr));
  1932. }
  1933. const depsObject = packageData.dependencies;
  1934. const optionalDepsObject = packageData.optionalDependencies;
  1935. const allDeps = new Set();
  1936. const optionalDeps = new Set();
  1937. if (typeof depsObject === "object" && depsObject) {
  1938. for (const dep of Object.keys(depsObject)) {
  1939. allDeps.add(dep);
  1940. }
  1941. }
  1942. if (
  1943. typeof optionalDepsObject === "object" &&
  1944. optionalDepsObject
  1945. ) {
  1946. for (const dep of Object.keys(optionalDepsObject)) {
  1947. allDeps.add(dep);
  1948. optionalDeps.add(dep);
  1949. }
  1950. }
  1951. for (const dep of allDeps) {
  1952. push({
  1953. type: RBDT_RESOLVE_DIRECTORY,
  1954. context: packagePath,
  1955. path: dep,
  1956. expected: !optionalDeps.has(dep),
  1957. issuer: job
  1958. });
  1959. }
  1960. callback();
  1961. });
  1962. break;
  1963. }
  1964. }
  1965. },
  1966. (err) => {
  1967. if (err) return callback(err);
  1968. for (const l of fileSymlinks) files.delete(l);
  1969. for (const l of directorySymlinks) directories.delete(l);
  1970. for (const k of invalidResolveResults) resolveResults.delete(k);
  1971. callback(null, {
  1972. files,
  1973. directories,
  1974. missing,
  1975. resolveResults,
  1976. resolveDependencies: {
  1977. files: resolveFiles,
  1978. directories: resolveDirectories,
  1979. missing: resolveMissing
  1980. }
  1981. });
  1982. }
  1983. );
  1984. }
  1985. /**
  1986. * @param {ResolveResults} resolveResults results from resolving
  1987. * @param {(err?: Error | null, result?: boolean) => void} callback callback with true when resolveResults resolve the same way
  1988. * @returns {void}
  1989. */
  1990. checkResolveResultsValid(resolveResults, callback) {
  1991. const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } =
  1992. this._createBuildDependenciesResolvers();
  1993. asyncLib.eachLimit(
  1994. resolveResults,
  1995. 20,
  1996. ([key, expectedResult], callback) => {
  1997. const [type, context, path] = key.split("\n");
  1998. switch (type) {
  1999. case "d":
  2000. resolveContext(context, path, {}, (err, _, result) => {
  2001. if (expectedResult === false) {
  2002. return callback(err ? undefined : INVALID);
  2003. }
  2004. if (err) return callback(err);
  2005. const resultPath = /** @type {ResolveRequest} */ (result).path;
  2006. if (resultPath !== expectedResult) return callback(INVALID);
  2007. callback();
  2008. });
  2009. break;
  2010. case "f":
  2011. resolveCjs(context, path, {}, (err, _, result) => {
  2012. if (expectedResult === false) {
  2013. return callback(err ? undefined : INVALID);
  2014. }
  2015. if (err) return callback(err);
  2016. const resultPath = /** @type {ResolveRequest} */ (result).path;
  2017. if (resultPath !== expectedResult) return callback(INVALID);
  2018. callback();
  2019. });
  2020. break;
  2021. case "c":
  2022. resolveCjsAsChild(context, path, {}, (err, _, result) => {
  2023. if (expectedResult === false) {
  2024. return callback(err ? undefined : INVALID);
  2025. }
  2026. if (err) return callback(err);
  2027. const resultPath = /** @type {ResolveRequest} */ (result).path;
  2028. if (resultPath !== expectedResult) return callback(INVALID);
  2029. callback();
  2030. });
  2031. break;
  2032. case "e":
  2033. resolveEsm(context, path, {}, (err, _, result) => {
  2034. if (expectedResult === false) {
  2035. return callback(err ? undefined : INVALID);
  2036. }
  2037. if (err) return callback(err);
  2038. const resultPath = /** @type {ResolveRequest} */ (result).path;
  2039. if (resultPath !== expectedResult) return callback(INVALID);
  2040. callback();
  2041. });
  2042. break;
  2043. default:
  2044. callback(new Error("Unexpected type in resolve result key"));
  2045. break;
  2046. }
  2047. },
  2048. /**
  2049. * @param {Error | typeof INVALID=} err error or invalid flag
  2050. * @returns {void}
  2051. */
  2052. (err) => {
  2053. if (err === INVALID) {
  2054. return callback(null, false);
  2055. }
  2056. if (err) {
  2057. return callback(err);
  2058. }
  2059. return callback(null, true);
  2060. }
  2061. );
  2062. }
  2063. /**
  2064. * @param {number | null | undefined} startTime when processing the files has started
  2065. * @param {Iterable<string> | null | undefined} files all files
  2066. * @param {Iterable<string> | null | undefined} directories all directories
  2067. * @param {Iterable<string> | null | undefined} missing all missing files or directories
  2068. * @param {SnapshotOptions | null | undefined} options options object (for future extensions)
  2069. * @param {(err: WebpackError | null, snapshot: Snapshot | null) => void} callback callback function
  2070. * @returns {void}
  2071. */
  2072. createSnapshot(startTime, files, directories, missing, options, callback) {
  2073. /** @type {FileTimestamps} */
  2074. const fileTimestamps = new Map();
  2075. /** @type {FileHashes} */
  2076. const fileHashes = new Map();
  2077. /** @type {FileTshs} */
  2078. const fileTshs = new Map();
  2079. /** @type {ContextTimestamps} */
  2080. const contextTimestamps = new Map();
  2081. /** @type {ContextHashes} */
  2082. const contextHashes = new Map();
  2083. /** @type {ContextTshs} */
  2084. const contextTshs = new Map();
  2085. /** @type {MissingExistence} */
  2086. const missingExistence = new Map();
  2087. /** @type {ManagedItemInfo} */
  2088. const managedItemInfo = new Map();
  2089. /** @type {ManagedFiles} */
  2090. const managedFiles = new Set();
  2091. /** @type {ManagedContexts} */
  2092. const managedContexts = new Set();
  2093. /** @type {ManagedMissing} */
  2094. const managedMissing = new Set();
  2095. /** @type {Children} */
  2096. const children = new Set();
  2097. const snapshot = new Snapshot();
  2098. if (startTime) snapshot.setStartTime(startTime);
  2099. /** @type {Set<string>} */
  2100. const managedItems = new Set();
  2101. /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */
  2102. const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1;
  2103. let jobs = 1;
  2104. const jobDone = () => {
  2105. if (--jobs === 0) {
  2106. if (fileTimestamps.size !== 0) {
  2107. snapshot.setFileTimestamps(fileTimestamps);
  2108. }
  2109. if (fileHashes.size !== 0) {
  2110. snapshot.setFileHashes(fileHashes);
  2111. }
  2112. if (fileTshs.size !== 0) {
  2113. snapshot.setFileTshs(fileTshs);
  2114. }
  2115. if (contextTimestamps.size !== 0) {
  2116. snapshot.setContextTimestamps(contextTimestamps);
  2117. }
  2118. if (contextHashes.size !== 0) {
  2119. snapshot.setContextHashes(contextHashes);
  2120. }
  2121. if (contextTshs.size !== 0) {
  2122. snapshot.setContextTshs(contextTshs);
  2123. }
  2124. if (missingExistence.size !== 0) {
  2125. snapshot.setMissingExistence(missingExistence);
  2126. }
  2127. if (managedItemInfo.size !== 0) {
  2128. snapshot.setManagedItemInfo(managedItemInfo);
  2129. }
  2130. this._managedFilesOptimization.optimize(snapshot, managedFiles);
  2131. if (managedFiles.size !== 0) {
  2132. snapshot.setManagedFiles(managedFiles);
  2133. }
  2134. this._managedContextsOptimization.optimize(snapshot, managedContexts);
  2135. if (managedContexts.size !== 0) {
  2136. snapshot.setManagedContexts(managedContexts);
  2137. }
  2138. this._managedMissingOptimization.optimize(snapshot, managedMissing);
  2139. if (managedMissing.size !== 0) {
  2140. snapshot.setManagedMissing(managedMissing);
  2141. }
  2142. if (children.size !== 0) {
  2143. snapshot.setChildren(children);
  2144. }
  2145. this._snapshotCache.set(snapshot, true);
  2146. this._statCreatedSnapshots++;
  2147. callback(null, snapshot);
  2148. }
  2149. };
  2150. const jobError = () => {
  2151. if (jobs > 0) {
  2152. // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
  2153. jobs = -100000000;
  2154. callback(null, null);
  2155. }
  2156. };
  2157. /**
  2158. * @param {string} path path
  2159. * @param {ManagedFiles} managedSet managed set
  2160. * @returns {boolean} true when managed
  2161. */
  2162. const checkManaged = (path, managedSet) => {
  2163. for (const unmanagedPath of this.unmanagedPathsRegExps) {
  2164. if (unmanagedPath.test(path)) return false;
  2165. }
  2166. for (const unmanagedPath of this.unmanagedPathsWithSlash) {
  2167. if (path.startsWith(unmanagedPath)) return false;
  2168. }
  2169. for (const immutablePath of this.immutablePathsRegExps) {
  2170. if (immutablePath.test(path)) {
  2171. managedSet.add(path);
  2172. return true;
  2173. }
  2174. }
  2175. for (const immutablePath of this.immutablePathsWithSlash) {
  2176. if (path.startsWith(immutablePath)) {
  2177. managedSet.add(path);
  2178. return true;
  2179. }
  2180. }
  2181. for (const managedPath of this.managedPathsRegExps) {
  2182. const match = managedPath.exec(path);
  2183. if (match) {
  2184. const managedItem = getManagedItem(match[1], path);
  2185. if (managedItem) {
  2186. managedItems.add(managedItem);
  2187. managedSet.add(path);
  2188. return true;
  2189. }
  2190. }
  2191. }
  2192. for (const managedPath of this.managedPathsWithSlash) {
  2193. if (path.startsWith(managedPath)) {
  2194. const managedItem = getManagedItem(managedPath, path);
  2195. if (managedItem) {
  2196. managedItems.add(managedItem);
  2197. managedSet.add(path);
  2198. return true;
  2199. }
  2200. }
  2201. }
  2202. return false;
  2203. };
  2204. /**
  2205. * @param {Iterable<string>} items items
  2206. * @param {Set<string>} managedSet managed set
  2207. * @returns {Set<string>} result
  2208. */
  2209. const captureNonManaged = (items, managedSet) => {
  2210. /** @type {Set<string>} */
  2211. const capturedItems = new Set();
  2212. for (const path of items) {
  2213. if (!checkManaged(path, managedSet)) capturedItems.add(path);
  2214. }
  2215. return capturedItems;
  2216. };
  2217. /**
  2218. * @param {ManagedFiles} capturedFiles captured files
  2219. */
  2220. const processCapturedFiles = (capturedFiles) => {
  2221. if (capturedFiles.size === 0) {
  2222. return;
  2223. }
  2224. switch (mode) {
  2225. case 3:
  2226. this._fileTshsOptimization.optimize(snapshot, capturedFiles);
  2227. for (const path of capturedFiles) {
  2228. const cache = this._fileTshs.get(path);
  2229. if (cache !== undefined) {
  2230. fileTshs.set(path, cache);
  2231. } else {
  2232. jobs++;
  2233. this._getFileTimestampAndHash(path, (err, entry) => {
  2234. if (err) {
  2235. if (this.logger) {
  2236. this.logger.debug(
  2237. `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}`
  2238. );
  2239. }
  2240. jobError();
  2241. } else {
  2242. fileTshs.set(path, /** @type {TimestampAndHash} */ (entry));
  2243. jobDone();
  2244. }
  2245. });
  2246. }
  2247. }
  2248. break;
  2249. case 2:
  2250. this._fileHashesOptimization.optimize(snapshot, capturedFiles);
  2251. for (const path of capturedFiles) {
  2252. const cache = this._fileHashes.get(path);
  2253. if (cache !== undefined) {
  2254. fileHashes.set(path, cache);
  2255. } else {
  2256. jobs++;
  2257. this.fileHashQueue.add(path, (err, entry) => {
  2258. if (err) {
  2259. if (this.logger) {
  2260. this.logger.debug(
  2261. `Error snapshotting file hash of ${path}: ${err.stack}`
  2262. );
  2263. }
  2264. jobError();
  2265. } else {
  2266. fileHashes.set(path, /** @type {string} */ (entry));
  2267. jobDone();
  2268. }
  2269. });
  2270. }
  2271. }
  2272. break;
  2273. case 1:
  2274. this._fileTimestampsOptimization.optimize(snapshot, capturedFiles);
  2275. for (const path of capturedFiles) {
  2276. const cache = this._fileTimestamps.get(path);
  2277. if (cache !== undefined) {
  2278. if (cache !== "ignore") {
  2279. fileTimestamps.set(path, cache);
  2280. }
  2281. } else {
  2282. jobs++;
  2283. this.fileTimestampQueue.add(path, (err, entry) => {
  2284. if (err) {
  2285. if (this.logger) {
  2286. this.logger.debug(
  2287. `Error snapshotting file timestamp of ${path}: ${err.stack}`
  2288. );
  2289. }
  2290. jobError();
  2291. } else {
  2292. fileTimestamps.set(
  2293. path,
  2294. /** @type {FileSystemInfoEntry} */
  2295. (entry)
  2296. );
  2297. jobDone();
  2298. }
  2299. });
  2300. }
  2301. }
  2302. break;
  2303. }
  2304. };
  2305. if (files) {
  2306. processCapturedFiles(captureNonManaged(files, managedFiles));
  2307. }
  2308. /**
  2309. * @param {ManagedContexts} capturedDirectories captured directories
  2310. */
  2311. const processCapturedDirectories = (capturedDirectories) => {
  2312. if (capturedDirectories.size === 0) {
  2313. return;
  2314. }
  2315. switch (mode) {
  2316. case 3:
  2317. this._contextTshsOptimization.optimize(snapshot, capturedDirectories);
  2318. for (const path of capturedDirectories) {
  2319. const cache = this._contextTshs.get(path);
  2320. /** @type {ResolvedContextTimestampAndHash | null | undefined} */
  2321. let resolved;
  2322. if (
  2323. cache !== undefined &&
  2324. (resolved = getResolvedTimestamp(cache)) !== undefined
  2325. ) {
  2326. contextTshs.set(path, resolved);
  2327. } else {
  2328. jobs++;
  2329. /**
  2330. * @param {(WebpackError | null)=} err error
  2331. * @param {(ResolvedContextTimestampAndHash | null)=} entry entry
  2332. * @returns {void}
  2333. */
  2334. const callback = (err, entry) => {
  2335. if (err) {
  2336. if (this.logger) {
  2337. this.logger.debug(
  2338. `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}`
  2339. );
  2340. }
  2341. jobError();
  2342. } else {
  2343. contextTshs.set(
  2344. path,
  2345. /** @type {ResolvedContextTimestampAndHash | null} */
  2346. (entry)
  2347. );
  2348. jobDone();
  2349. }
  2350. };
  2351. if (cache !== undefined) {
  2352. this._resolveContextTsh(cache, callback);
  2353. } else {
  2354. this.getContextTsh(path, callback);
  2355. }
  2356. }
  2357. }
  2358. break;
  2359. case 2:
  2360. this._contextHashesOptimization.optimize(
  2361. snapshot,
  2362. capturedDirectories
  2363. );
  2364. for (const path of capturedDirectories) {
  2365. const cache = this._contextHashes.get(path);
  2366. let resolved;
  2367. if (
  2368. cache !== undefined &&
  2369. (resolved = getResolvedHash(cache)) !== undefined
  2370. ) {
  2371. contextHashes.set(path, resolved);
  2372. } else {
  2373. jobs++;
  2374. /**
  2375. * @param {(WebpackError | null)=} err err
  2376. * @param {string=} entry entry
  2377. */
  2378. const callback = (err, entry) => {
  2379. if (err) {
  2380. if (this.logger) {
  2381. this.logger.debug(
  2382. `Error snapshotting context hash of ${path}: ${err.stack}`
  2383. );
  2384. }
  2385. jobError();
  2386. } else {
  2387. contextHashes.set(path, /** @type {string} */ (entry));
  2388. jobDone();
  2389. }
  2390. };
  2391. if (cache !== undefined) {
  2392. this._resolveContextHash(cache, callback);
  2393. } else {
  2394. this.getContextHash(path, callback);
  2395. }
  2396. }
  2397. }
  2398. break;
  2399. case 1:
  2400. this._contextTimestampsOptimization.optimize(
  2401. snapshot,
  2402. capturedDirectories
  2403. );
  2404. for (const path of capturedDirectories) {
  2405. const cache = this._contextTimestamps.get(path);
  2406. if (cache === "ignore") continue;
  2407. let resolved;
  2408. if (
  2409. cache !== undefined &&
  2410. (resolved = getResolvedTimestamp(cache)) !== undefined
  2411. ) {
  2412. contextTimestamps.set(path, resolved);
  2413. } else {
  2414. jobs++;
  2415. /**
  2416. * @param {(Error | null)=} err error
  2417. * @param {FileTimestamp=} entry entry
  2418. * @returns {void}
  2419. */
  2420. const callback = (err, entry) => {
  2421. if (err) {
  2422. if (this.logger) {
  2423. this.logger.debug(
  2424. `Error snapshotting context timestamp of ${path}: ${err.stack}`
  2425. );
  2426. }
  2427. jobError();
  2428. } else {
  2429. contextTimestamps.set(
  2430. path,
  2431. /** @type {FileSystemInfoEntry | null} */
  2432. (entry)
  2433. );
  2434. jobDone();
  2435. }
  2436. };
  2437. if (cache !== undefined) {
  2438. this._resolveContextTimestamp(
  2439. /** @type {ContextFileSystemInfoEntry} */
  2440. (cache),
  2441. callback
  2442. );
  2443. } else {
  2444. this.getContextTimestamp(path, callback);
  2445. }
  2446. }
  2447. }
  2448. break;
  2449. }
  2450. };
  2451. if (directories) {
  2452. processCapturedDirectories(
  2453. captureNonManaged(directories, managedContexts)
  2454. );
  2455. }
  2456. /**
  2457. * @param {ManagedMissing} capturedMissing captured missing
  2458. */
  2459. const processCapturedMissing = (capturedMissing) => {
  2460. if (capturedMissing.size === 0) {
  2461. return;
  2462. }
  2463. this._missingExistenceOptimization.optimize(snapshot, capturedMissing);
  2464. for (const path of capturedMissing) {
  2465. const cache = this._fileTimestamps.get(path);
  2466. if (cache !== undefined) {
  2467. if (cache !== "ignore") {
  2468. missingExistence.set(path, Boolean(cache));
  2469. }
  2470. } else {
  2471. jobs++;
  2472. this.fileTimestampQueue.add(path, (err, entry) => {
  2473. if (err) {
  2474. if (this.logger) {
  2475. this.logger.debug(
  2476. `Error snapshotting missing timestamp of ${path}: ${err.stack}`
  2477. );
  2478. }
  2479. jobError();
  2480. } else {
  2481. missingExistence.set(path, Boolean(entry));
  2482. jobDone();
  2483. }
  2484. });
  2485. }
  2486. }
  2487. };
  2488. if (missing) {
  2489. processCapturedMissing(captureNonManaged(missing, managedMissing));
  2490. }
  2491. this._managedItemInfoOptimization.optimize(snapshot, managedItems);
  2492. for (const path of managedItems) {
  2493. const cache = this._managedItems.get(path);
  2494. if (cache !== undefined) {
  2495. if (!cache.startsWith("*")) {
  2496. managedFiles.add(join(this.fs, path, "package.json"));
  2497. } else if (cache === "*nested") {
  2498. managedMissing.add(join(this.fs, path, "package.json"));
  2499. }
  2500. managedItemInfo.set(path, cache);
  2501. } else {
  2502. jobs++;
  2503. this.managedItemQueue.add(path, (err, entry) => {
  2504. if (err) {
  2505. if (this.logger) {
  2506. this.logger.debug(
  2507. `Error snapshotting managed item ${path}: ${err.stack}`
  2508. );
  2509. }
  2510. jobError();
  2511. } else if (entry) {
  2512. if (!entry.startsWith("*")) {
  2513. managedFiles.add(join(this.fs, path, "package.json"));
  2514. } else if (cache === "*nested") {
  2515. managedMissing.add(join(this.fs, path, "package.json"));
  2516. }
  2517. managedItemInfo.set(path, entry);
  2518. jobDone();
  2519. } else {
  2520. // Fallback to normal snapshotting
  2521. /**
  2522. * @param {Set<string>} set set
  2523. * @param {(set: Set<string>) => void} fn fn
  2524. */
  2525. const process = (set, fn) => {
  2526. if (set.size === 0) return;
  2527. const captured = new Set();
  2528. for (const file of set) {
  2529. if (file.startsWith(path)) captured.add(file);
  2530. }
  2531. if (captured.size > 0) fn(captured);
  2532. };
  2533. process(managedFiles, processCapturedFiles);
  2534. process(managedContexts, processCapturedDirectories);
  2535. process(managedMissing, processCapturedMissing);
  2536. jobDone();
  2537. }
  2538. });
  2539. }
  2540. }
  2541. jobDone();
  2542. }
  2543. /**
  2544. * @param {Snapshot} snapshot1 a snapshot
  2545. * @param {Snapshot} snapshot2 a snapshot
  2546. * @returns {Snapshot} merged snapshot
  2547. */
  2548. mergeSnapshots(snapshot1, snapshot2) {
  2549. const snapshot = new Snapshot();
  2550. if (snapshot1.hasStartTime() && snapshot2.hasStartTime()) {
  2551. snapshot.setStartTime(
  2552. Math.min(
  2553. /** @type {NonNullable<Snapshot["startTime"]>} */
  2554. (snapshot1.startTime),
  2555. /** @type {NonNullable<Snapshot["startTime"]>} */
  2556. (snapshot2.startTime)
  2557. )
  2558. );
  2559. } else if (snapshot2.hasStartTime()) {
  2560. snapshot.startTime = snapshot2.startTime;
  2561. } else if (snapshot1.hasStartTime()) {
  2562. snapshot.startTime = snapshot1.startTime;
  2563. }
  2564. if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) {
  2565. snapshot.setFileTimestamps(
  2566. mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps)
  2567. );
  2568. }
  2569. if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) {
  2570. snapshot.setFileHashes(
  2571. mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes)
  2572. );
  2573. }
  2574. if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) {
  2575. snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs));
  2576. }
  2577. if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) {
  2578. snapshot.setContextTimestamps(
  2579. mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps)
  2580. );
  2581. }
  2582. if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) {
  2583. snapshot.setContextHashes(
  2584. mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes)
  2585. );
  2586. }
  2587. if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) {
  2588. snapshot.setContextTshs(
  2589. mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs)
  2590. );
  2591. }
  2592. if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) {
  2593. snapshot.setMissingExistence(
  2594. mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence)
  2595. );
  2596. }
  2597. if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) {
  2598. snapshot.setManagedItemInfo(
  2599. mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo)
  2600. );
  2601. }
  2602. if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) {
  2603. snapshot.setManagedFiles(
  2604. mergeSets(snapshot1.managedFiles, snapshot2.managedFiles)
  2605. );
  2606. }
  2607. if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) {
  2608. snapshot.setManagedContexts(
  2609. mergeSets(snapshot1.managedContexts, snapshot2.managedContexts)
  2610. );
  2611. }
  2612. if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) {
  2613. snapshot.setManagedMissing(
  2614. mergeSets(snapshot1.managedMissing, snapshot2.managedMissing)
  2615. );
  2616. }
  2617. if (snapshot1.hasChildren() || snapshot2.hasChildren()) {
  2618. snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children));
  2619. }
  2620. if (
  2621. this._snapshotCache.get(snapshot1) === true &&
  2622. this._snapshotCache.get(snapshot2) === true
  2623. ) {
  2624. this._snapshotCache.set(snapshot, true);
  2625. }
  2626. return snapshot;
  2627. }
  2628. /**
  2629. * @param {Snapshot} snapshot the snapshot made
  2630. * @param {CheckSnapshotValidCallback} callback callback function
  2631. * @returns {void}
  2632. */
  2633. checkSnapshotValid(snapshot, callback) {
  2634. const cachedResult = this._snapshotCache.get(snapshot);
  2635. if (cachedResult !== undefined) {
  2636. this._statTestedSnapshotsCached++;
  2637. if (typeof cachedResult === "boolean") {
  2638. callback(null, cachedResult);
  2639. } else {
  2640. cachedResult.push(callback);
  2641. }
  2642. return;
  2643. }
  2644. this._statTestedSnapshotsNotCached++;
  2645. this._checkSnapshotValidNoCache(snapshot, callback);
  2646. }
  2647. /**
  2648. * @private
  2649. * @param {Snapshot} snapshot the snapshot made
  2650. * @param {CheckSnapshotValidCallback} callback callback function
  2651. * @returns {void}
  2652. */
  2653. _checkSnapshotValidNoCache(snapshot, callback) {
  2654. /** @type {number | undefined} */
  2655. let startTime;
  2656. if (snapshot.hasStartTime()) {
  2657. startTime = snapshot.startTime;
  2658. }
  2659. let jobs = 1;
  2660. const jobDone = () => {
  2661. if (--jobs === 0) {
  2662. this._snapshotCache.set(snapshot, true);
  2663. callback(null, true);
  2664. }
  2665. };
  2666. const invalid = () => {
  2667. if (jobs > 0) {
  2668. // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8)
  2669. jobs = -100000000;
  2670. this._snapshotCache.set(snapshot, false);
  2671. callback(null, false);
  2672. }
  2673. };
  2674. /**
  2675. * @param {string} path path
  2676. * @param {WebpackError} err err
  2677. */
  2678. const invalidWithError = (path, err) => {
  2679. if (this._remainingLogs > 0) {
  2680. this._log(path, "error occurred: %s", err);
  2681. }
  2682. invalid();
  2683. };
  2684. /**
  2685. * @param {string} path file path
  2686. * @param {string | null} current current hash
  2687. * @param {string | null} snap snapshot hash
  2688. * @returns {boolean} true, if ok
  2689. */
  2690. const checkHash = (path, current, snap) => {
  2691. if (current !== snap) {
  2692. // If hash differ it's invalid
  2693. if (this._remainingLogs > 0) {
  2694. this._log(path, "hashes differ (%s != %s)", current, snap);
  2695. }
  2696. return false;
  2697. }
  2698. return true;
  2699. };
  2700. /**
  2701. * @param {string} path file path
  2702. * @param {boolean} current current entry
  2703. * @param {boolean} snap entry from snapshot
  2704. * @returns {boolean} true, if ok
  2705. */
  2706. const checkExistence = (path, current, snap) => {
  2707. if (!current !== !snap) {
  2708. // If existence of item differs
  2709. // it's invalid
  2710. if (this._remainingLogs > 0) {
  2711. this._log(
  2712. path,
  2713. current ? "it didn't exist before" : "it does no longer exist"
  2714. );
  2715. }
  2716. return false;
  2717. }
  2718. return true;
  2719. };
  2720. /**
  2721. * @param {string} path file path
  2722. * @param {FileSystemInfoEntry | null} c current entry
  2723. * @param {FileSystemInfoEntry | null} s entry from snapshot
  2724. * @param {boolean} log log reason
  2725. * @returns {boolean} true, if ok
  2726. */
  2727. const checkFile = (path, c, s, log = true) => {
  2728. if (c === s) return true;
  2729. if (!checkExistence(path, Boolean(c), Boolean(s))) return false;
  2730. if (c) {
  2731. // For existing items only
  2732. if (typeof startTime === "number" && c.safeTime > startTime) {
  2733. // If a change happened after starting reading the item
  2734. // this may no longer be valid
  2735. if (log && this._remainingLogs > 0) {
  2736. this._log(
  2737. path,
  2738. "it may have changed (%d) after the start time of the snapshot (%d)",
  2739. c.safeTime,
  2740. startTime
  2741. );
  2742. }
  2743. return false;
  2744. }
  2745. const snap = /** @type {FileSystemInfoEntry} */ (s);
  2746. if (snap.timestamp !== undefined && c.timestamp !== snap.timestamp) {
  2747. // If we have a timestamp (it was a file or symlink) and it differs from current timestamp
  2748. // it's invalid
  2749. if (log && this._remainingLogs > 0) {
  2750. this._log(
  2751. path,
  2752. "timestamps differ (%d != %d)",
  2753. c.timestamp,
  2754. snap.timestamp
  2755. );
  2756. }
  2757. return false;
  2758. }
  2759. }
  2760. return true;
  2761. };
  2762. /**
  2763. * @param {string} path file path
  2764. * @param {ResolvedContextFileSystemInfoEntry | null} c current entry
  2765. * @param {ResolvedContextFileSystemInfoEntry | null} s entry from snapshot
  2766. * @param {boolean} log log reason
  2767. * @returns {boolean} true, if ok
  2768. */
  2769. const checkContext = (path, c, s, log = true) => {
  2770. if (c === s) return true;
  2771. if (!checkExistence(path, Boolean(c), Boolean(s))) return false;
  2772. if (c) {
  2773. // For existing items only
  2774. if (typeof startTime === "number" && c.safeTime > startTime) {
  2775. // If a change happened after starting reading the item
  2776. // this may no longer be valid
  2777. if (log && this._remainingLogs > 0) {
  2778. this._log(
  2779. path,
  2780. "it may have changed (%d) after the start time of the snapshot (%d)",
  2781. c.safeTime,
  2782. startTime
  2783. );
  2784. }
  2785. return false;
  2786. }
  2787. const snap = /** @type {ResolvedContextFileSystemInfoEntry} */ (s);
  2788. if (
  2789. snap.timestampHash !== undefined &&
  2790. c.timestampHash !== snap.timestampHash
  2791. ) {
  2792. // If we have a timestampHash (it was a directory) and it differs from current timestampHash
  2793. // it's invalid
  2794. if (log && this._remainingLogs > 0) {
  2795. this._log(
  2796. path,
  2797. "timestamps hashes differ (%s != %s)",
  2798. c.timestampHash,
  2799. snap.timestampHash
  2800. );
  2801. }
  2802. return false;
  2803. }
  2804. }
  2805. return true;
  2806. };
  2807. if (snapshot.hasChildren()) {
  2808. /**
  2809. * @param {(WebpackError | null)=} err err
  2810. * @param {boolean=} result result
  2811. * @returns {void}
  2812. */
  2813. const childCallback = (err, result) => {
  2814. if (err || !result) return invalid();
  2815. jobDone();
  2816. };
  2817. for (const child of /** @type {Children} */ (snapshot.children)) {
  2818. const cache = this._snapshotCache.get(child);
  2819. if (cache !== undefined) {
  2820. this._statTestedChildrenCached++;
  2821. /* istanbul ignore else */
  2822. if (typeof cache === "boolean") {
  2823. if (cache === false) {
  2824. invalid();
  2825. return;
  2826. }
  2827. } else {
  2828. jobs++;
  2829. cache.push(childCallback);
  2830. }
  2831. } else {
  2832. this._statTestedChildrenNotCached++;
  2833. jobs++;
  2834. this._checkSnapshotValidNoCache(child, childCallback);
  2835. }
  2836. }
  2837. }
  2838. if (snapshot.hasFileTimestamps()) {
  2839. const fileTimestamps =
  2840. /** @type {FileTimestamps} */
  2841. (snapshot.fileTimestamps);
  2842. this._statTestedEntries += fileTimestamps.size;
  2843. for (const [path, ts] of fileTimestamps) {
  2844. const cache = this._fileTimestamps.get(path);
  2845. if (cache !== undefined) {
  2846. if (cache !== "ignore" && !checkFile(path, cache, ts)) {
  2847. invalid();
  2848. return;
  2849. }
  2850. } else {
  2851. jobs++;
  2852. this.fileTimestampQueue.add(path, (err, entry) => {
  2853. if (err) return invalidWithError(path, err);
  2854. if (
  2855. !checkFile(
  2856. path,
  2857. /** @type {FileSystemInfoEntry | null} */ (entry),
  2858. ts
  2859. )
  2860. ) {
  2861. invalid();
  2862. } else {
  2863. jobDone();
  2864. }
  2865. });
  2866. }
  2867. }
  2868. }
  2869. /**
  2870. * @param {string} path file path
  2871. * @param {string | null} hash hash
  2872. */
  2873. const processFileHashSnapshot = (path, hash) => {
  2874. const cache = this._fileHashes.get(path);
  2875. if (cache !== undefined) {
  2876. if (cache !== "ignore" && !checkHash(path, cache, hash)) {
  2877. invalid();
  2878. }
  2879. } else {
  2880. jobs++;
  2881. this.fileHashQueue.add(path, (err, entry) => {
  2882. if (err) return invalidWithError(path, err);
  2883. if (!checkHash(path, /** @type {string} */ (entry), hash)) {
  2884. invalid();
  2885. } else {
  2886. jobDone();
  2887. }
  2888. });
  2889. }
  2890. };
  2891. if (snapshot.hasFileHashes()) {
  2892. const fileHashes = /** @type {FileHashes} */ (snapshot.fileHashes);
  2893. this._statTestedEntries += fileHashes.size;
  2894. for (const [path, hash] of fileHashes) {
  2895. processFileHashSnapshot(path, hash);
  2896. }
  2897. }
  2898. if (snapshot.hasFileTshs()) {
  2899. const fileTshs = /** @type {FileTshs} */ (snapshot.fileTshs);
  2900. this._statTestedEntries += fileTshs.size;
  2901. for (const [path, tsh] of fileTshs) {
  2902. if (typeof tsh === "string") {
  2903. processFileHashSnapshot(path, tsh);
  2904. } else {
  2905. const cache = this._fileTimestamps.get(path);
  2906. if (cache !== undefined) {
  2907. if (cache === "ignore" || !checkFile(path, cache, tsh, false)) {
  2908. processFileHashSnapshot(path, tsh && tsh.hash);
  2909. }
  2910. } else {
  2911. jobs++;
  2912. this.fileTimestampQueue.add(path, (err, entry) => {
  2913. if (err) return invalidWithError(path, err);
  2914. if (
  2915. !checkFile(
  2916. path,
  2917. /** @type {FileSystemInfoEntry | null} */
  2918. (entry),
  2919. tsh,
  2920. false
  2921. )
  2922. ) {
  2923. processFileHashSnapshot(path, tsh && tsh.hash);
  2924. }
  2925. jobDone();
  2926. });
  2927. }
  2928. }
  2929. }
  2930. }
  2931. if (snapshot.hasContextTimestamps()) {
  2932. const contextTimestamps =
  2933. /** @type {ContextTimestamps} */
  2934. (snapshot.contextTimestamps);
  2935. this._statTestedEntries += contextTimestamps.size;
  2936. for (const [path, ts] of contextTimestamps) {
  2937. const cache = this._contextTimestamps.get(path);
  2938. if (cache === "ignore") continue;
  2939. let resolved;
  2940. if (
  2941. cache !== undefined &&
  2942. (resolved = getResolvedTimestamp(cache)) !== undefined
  2943. ) {
  2944. if (!checkContext(path, resolved, ts)) {
  2945. invalid();
  2946. return;
  2947. }
  2948. } else {
  2949. jobs++;
  2950. /**
  2951. * @param {(WebpackError | null)=} err error
  2952. * @param {ResolvedContextTimestamp=} entry entry
  2953. * @returns {void}
  2954. */
  2955. const callback = (err, entry) => {
  2956. if (err) return invalidWithError(path, err);
  2957. if (
  2958. !checkContext(
  2959. path,
  2960. /** @type {ResolvedContextFileSystemInfoEntry | null} */
  2961. (entry),
  2962. ts
  2963. )
  2964. ) {
  2965. invalid();
  2966. } else {
  2967. jobDone();
  2968. }
  2969. };
  2970. if (cache !== undefined) {
  2971. this._resolveContextTimestamp(
  2972. /** @type {ContextFileSystemInfoEntry} */
  2973. (cache),
  2974. callback
  2975. );
  2976. } else {
  2977. this.getContextTimestamp(path, callback);
  2978. }
  2979. }
  2980. }
  2981. }
  2982. /**
  2983. * @param {string} path path
  2984. * @param {string | null} hash hash
  2985. */
  2986. const processContextHashSnapshot = (path, hash) => {
  2987. const cache = this._contextHashes.get(path);
  2988. let resolved;
  2989. if (
  2990. cache !== undefined &&
  2991. (resolved = getResolvedHash(cache)) !== undefined
  2992. ) {
  2993. if (!checkHash(path, resolved, hash)) {
  2994. invalid();
  2995. }
  2996. } else {
  2997. jobs++;
  2998. /**
  2999. * @param {(WebpackError | null)=} err err
  3000. * @param {string=} entry entry
  3001. * @returns {void}
  3002. */
  3003. const callback = (err, entry) => {
  3004. if (err) return invalidWithError(path, err);
  3005. if (!checkHash(path, /** @type {string} */ (entry), hash)) {
  3006. invalid();
  3007. } else {
  3008. jobDone();
  3009. }
  3010. };
  3011. if (cache !== undefined) {
  3012. this._resolveContextHash(cache, callback);
  3013. } else {
  3014. this.getContextHash(path, callback);
  3015. }
  3016. }
  3017. };
  3018. if (snapshot.hasContextHashes()) {
  3019. const contextHashes =
  3020. /** @type {ContextHashes} */
  3021. (snapshot.contextHashes);
  3022. this._statTestedEntries += contextHashes.size;
  3023. for (const [path, hash] of contextHashes) {
  3024. processContextHashSnapshot(path, hash);
  3025. }
  3026. }
  3027. if (snapshot.hasContextTshs()) {
  3028. const contextTshs = /** @type {ContextTshs} */ (snapshot.contextTshs);
  3029. this._statTestedEntries += contextTshs.size;
  3030. for (const [path, tsh] of contextTshs) {
  3031. if (typeof tsh === "string") {
  3032. processContextHashSnapshot(path, tsh);
  3033. } else {
  3034. const cache = this._contextTimestamps.get(path);
  3035. if (cache === "ignore") continue;
  3036. let resolved;
  3037. if (
  3038. cache !== undefined &&
  3039. (resolved = getResolvedTimestamp(cache)) !== undefined
  3040. ) {
  3041. if (
  3042. !checkContext(
  3043. path,
  3044. /** @type {ResolvedContextFileSystemInfoEntry | null} */
  3045. (resolved),
  3046. tsh,
  3047. false
  3048. )
  3049. ) {
  3050. processContextHashSnapshot(path, tsh && tsh.hash);
  3051. }
  3052. } else {
  3053. jobs++;
  3054. /**
  3055. * @param {(WebpackError | null)=} err error
  3056. * @param {ResolvedContextTimestamp=} entry entry
  3057. * @returns {void}
  3058. */
  3059. const callback = (err, entry) => {
  3060. if (err) return invalidWithError(path, err);
  3061. if (
  3062. !checkContext(
  3063. path,
  3064. // TODO: test with `"ignore"`
  3065. /** @type {ResolvedContextFileSystemInfoEntry | null} */
  3066. (entry),
  3067. tsh,
  3068. false
  3069. )
  3070. ) {
  3071. processContextHashSnapshot(path, tsh && tsh.hash);
  3072. }
  3073. jobDone();
  3074. };
  3075. if (cache !== undefined) {
  3076. this._resolveContextTimestamp(
  3077. /** @type {ContextFileSystemInfoEntry} */
  3078. (cache),
  3079. callback
  3080. );
  3081. } else {
  3082. this.getContextTimestamp(path, callback);
  3083. }
  3084. }
  3085. }
  3086. }
  3087. }
  3088. if (snapshot.hasMissingExistence()) {
  3089. const missingExistence =
  3090. /** @type {MissingExistence} */
  3091. (snapshot.missingExistence);
  3092. this._statTestedEntries += missingExistence.size;
  3093. for (const [path, existence] of missingExistence) {
  3094. const cache = this._fileTimestamps.get(path);
  3095. if (cache !== undefined) {
  3096. if (
  3097. cache !== "ignore" &&
  3098. !checkExistence(path, Boolean(cache), Boolean(existence))
  3099. ) {
  3100. invalid();
  3101. return;
  3102. }
  3103. } else {
  3104. jobs++;
  3105. this.fileTimestampQueue.add(path, (err, entry) => {
  3106. if (err) return invalidWithError(path, err);
  3107. if (!checkExistence(path, Boolean(entry), Boolean(existence))) {
  3108. invalid();
  3109. } else {
  3110. jobDone();
  3111. }
  3112. });
  3113. }
  3114. }
  3115. }
  3116. if (snapshot.hasManagedItemInfo()) {
  3117. const managedItemInfo =
  3118. /** @type {ManagedItemInfo} */
  3119. (snapshot.managedItemInfo);
  3120. this._statTestedEntries += managedItemInfo.size;
  3121. for (const [path, info] of managedItemInfo) {
  3122. const cache = this._managedItems.get(path);
  3123. if (cache !== undefined) {
  3124. if (!checkHash(path, cache, info)) {
  3125. invalid();
  3126. return;
  3127. }
  3128. } else {
  3129. jobs++;
  3130. this.managedItemQueue.add(path, (err, entry) => {
  3131. if (err) return invalidWithError(path, err);
  3132. if (!checkHash(path, /** @type {string} */ (entry), info)) {
  3133. invalid();
  3134. } else {
  3135. jobDone();
  3136. }
  3137. });
  3138. }
  3139. }
  3140. }
  3141. jobDone();
  3142. // if there was an async action
  3143. // try to join multiple concurrent request for this snapshot
  3144. if (jobs > 0) {
  3145. const callbacks = [callback];
  3146. callback = (err, result) => {
  3147. for (const callback of callbacks) callback(err, result);
  3148. };
  3149. this._snapshotCache.set(snapshot, callbacks);
  3150. }
  3151. }
  3152. /**
  3153. * @private
  3154. * @type {Processor<string, FileSystemInfoEntry>}
  3155. */
  3156. _readFileTimestamp(path, callback) {
  3157. this.fs.stat(path, (err, _stat) => {
  3158. if (err) {
  3159. if (err.code === "ENOENT") {
  3160. this._fileTimestamps.set(path, null);
  3161. this._cachedDeprecatedFileTimestamps = undefined;
  3162. return callback(null, null);
  3163. }
  3164. return callback(/** @type {WebpackError} */ (err));
  3165. }
  3166. const stat = /** @type {IStats} */ (_stat);
  3167. let ts;
  3168. if (stat.isDirectory()) {
  3169. ts = {
  3170. safeTime: 0,
  3171. timestamp: undefined
  3172. };
  3173. } else {
  3174. const mtime = Number(stat.mtime);
  3175. if (mtime) applyMtime(mtime);
  3176. ts = {
  3177. safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
  3178. timestamp: mtime
  3179. };
  3180. }
  3181. this._fileTimestamps.set(path, ts);
  3182. this._cachedDeprecatedFileTimestamps = undefined;
  3183. callback(null, ts);
  3184. });
  3185. }
  3186. /**
  3187. * @private
  3188. * @type {Processor<string, string>}
  3189. */
  3190. _readFileHash(path, callback) {
  3191. this.fs.readFile(path, (err, content) => {
  3192. if (err) {
  3193. if (err.code === "EISDIR") {
  3194. this._fileHashes.set(path, "directory");
  3195. return callback(null, "directory");
  3196. }
  3197. if (err.code === "ENOENT") {
  3198. this._fileHashes.set(path, null);
  3199. return callback(null, null);
  3200. }
  3201. if (err.code === "ERR_FS_FILE_TOO_LARGE") {
  3202. /** @type {Logger} */
  3203. (this.logger).warn(`Ignoring ${path} for hashing as it's very large`);
  3204. this._fileHashes.set(path, "too large");
  3205. return callback(null, "too large");
  3206. }
  3207. return callback(/** @type {WebpackError} */ (err));
  3208. }
  3209. const hash = createHash(this._hashFunction);
  3210. hash.update(/** @type {string | Buffer} */ (content));
  3211. const digest = hash.digest("hex");
  3212. this._fileHashes.set(path, digest);
  3213. callback(null, digest);
  3214. });
  3215. }
  3216. /**
  3217. * @private
  3218. * @param {string} path path
  3219. * @param {(err: WebpackError | null, timestampAndHash?: TimestampAndHash | string) => void} callback callback
  3220. */
  3221. _getFileTimestampAndHash(path, callback) {
  3222. /**
  3223. * @param {string} hash hash
  3224. * @returns {void}
  3225. */
  3226. const continueWithHash = (hash) => {
  3227. const cache = this._fileTimestamps.get(path);
  3228. if (cache !== undefined) {
  3229. if (cache !== "ignore") {
  3230. /** @type {TimestampAndHash} */
  3231. const result = {
  3232. .../** @type {FileSystemInfoEntry} */ (cache),
  3233. hash
  3234. };
  3235. this._fileTshs.set(path, result);
  3236. return callback(null, result);
  3237. }
  3238. this._fileTshs.set(path, hash);
  3239. return callback(null, hash);
  3240. }
  3241. this.fileTimestampQueue.add(path, (err, entry) => {
  3242. if (err) {
  3243. return callback(err);
  3244. }
  3245. /** @type {TimestampAndHash} */
  3246. const result = {
  3247. .../** @type {FileSystemInfoEntry} */ (entry),
  3248. hash
  3249. };
  3250. this._fileTshs.set(path, result);
  3251. return callback(null, result);
  3252. });
  3253. };
  3254. const cache = this._fileHashes.get(path);
  3255. if (cache !== undefined) {
  3256. continueWithHash(/** @type {string} */ (cache));
  3257. } else {
  3258. this.fileHashQueue.add(path, (err, entry) => {
  3259. if (err) {
  3260. return callback(err);
  3261. }
  3262. continueWithHash(/** @type {string} */ (entry));
  3263. });
  3264. }
  3265. }
  3266. /**
  3267. * @private
  3268. * @template T
  3269. * @template ItemType
  3270. * @param {object} options options
  3271. * @param {string} options.path path
  3272. * @param {(value: string) => ItemType} options.fromImmutablePath called when context item is an immutable path
  3273. * @param {(value: string) => ItemType} options.fromManagedItem called when context item is a managed path
  3274. * @param {(value: string, result: string, callback: (err?: WebpackError | null, itemType?: ItemType) => void) => void} options.fromSymlink called when context item is a symlink
  3275. * @param {(value: string, stats: IStats, callback: (err?: WebpackError | null, itemType?: ItemType | null) => void) => void} options.fromFile called when context item is a file
  3276. * @param {(value: string, stats: IStats, callback: (err?: WebpackError | null, itemType?: ItemType) => void) => void} options.fromDirectory called when context item is a directory
  3277. * @param {(arr: string[], arr1: ItemType[]) => T} options.reduce called from all context items
  3278. * @param {(err?: Error | null, result?: T | null) => void} callback callback
  3279. */
  3280. _readContext(
  3281. {
  3282. path,
  3283. fromImmutablePath,
  3284. fromManagedItem,
  3285. fromSymlink,
  3286. fromFile,
  3287. fromDirectory,
  3288. reduce
  3289. },
  3290. callback
  3291. ) {
  3292. this.fs.readdir(path, (err, _files) => {
  3293. if (err) {
  3294. if (err.code === "ENOENT") {
  3295. return callback(null, null);
  3296. }
  3297. return callback(err);
  3298. }
  3299. const files = /** @type {string[]} */ (_files)
  3300. .map((file) => file.normalize("NFC"))
  3301. .filter((file) => !/^\./.test(file))
  3302. .sort();
  3303. asyncLib.map(
  3304. files,
  3305. (file, callback) => {
  3306. const child = join(this.fs, path, file);
  3307. for (const immutablePath of this.immutablePathsRegExps) {
  3308. if (immutablePath.test(path)) {
  3309. // ignore any immutable path for timestamping
  3310. return callback(null, fromImmutablePath(path));
  3311. }
  3312. }
  3313. for (const immutablePath of this.immutablePathsWithSlash) {
  3314. if (path.startsWith(immutablePath)) {
  3315. // ignore any immutable path for timestamping
  3316. return callback(null, fromImmutablePath(path));
  3317. }
  3318. }
  3319. for (const managedPath of this.managedPathsRegExps) {
  3320. const match = managedPath.exec(path);
  3321. if (match) {
  3322. const managedItem = getManagedItem(match[1], path);
  3323. if (managedItem) {
  3324. // construct timestampHash from managed info
  3325. return this.managedItemQueue.add(managedItem, (err, info) => {
  3326. if (err) return callback(err);
  3327. return callback(
  3328. null,
  3329. fromManagedItem(/** @type {string} */ (info))
  3330. );
  3331. });
  3332. }
  3333. }
  3334. }
  3335. for (const managedPath of this.managedPathsWithSlash) {
  3336. if (path.startsWith(managedPath)) {
  3337. const managedItem = getManagedItem(managedPath, child);
  3338. if (managedItem) {
  3339. // construct timestampHash from managed info
  3340. return this.managedItemQueue.add(managedItem, (err, info) => {
  3341. if (err) return callback(err);
  3342. return callback(
  3343. null,
  3344. fromManagedItem(/** @type {string} */ (info))
  3345. );
  3346. });
  3347. }
  3348. }
  3349. }
  3350. lstatReadlinkAbsolute(this.fs, child, (err, _stat) => {
  3351. if (err) return callback(err);
  3352. const stat = /** @type {IStats | string} */ (_stat);
  3353. if (typeof stat === "string") {
  3354. return fromSymlink(child, stat, callback);
  3355. }
  3356. if (stat.isFile()) {
  3357. return fromFile(child, stat, callback);
  3358. }
  3359. if (stat.isDirectory()) {
  3360. return fromDirectory(child, stat, callback);
  3361. }
  3362. callback(null, null);
  3363. });
  3364. },
  3365. (err, results) => {
  3366. if (err) return callback(err);
  3367. const result = reduce(files, /** @type {ItemType[]} */ (results));
  3368. callback(null, result);
  3369. }
  3370. );
  3371. });
  3372. }
  3373. /**
  3374. * @private
  3375. * @type {Processor<string, ContextFileSystemInfoEntry>}
  3376. */
  3377. _readContextTimestamp(path, callback) {
  3378. this._readContext(
  3379. {
  3380. path,
  3381. fromImmutablePath: () =>
  3382. /** @type {ContextFileSystemInfoEntry | FileSystemInfoEntry | "ignore" | null} */
  3383. (null),
  3384. fromManagedItem: (info) => ({
  3385. safeTime: 0,
  3386. timestampHash: info
  3387. }),
  3388. fromSymlink: (file, target, callback) => {
  3389. callback(
  3390. null,
  3391. /** @type {ContextFileSystemInfoEntry} */
  3392. ({
  3393. timestampHash: target,
  3394. symlinks: new Set([target])
  3395. })
  3396. );
  3397. },
  3398. fromFile: (file, stat, callback) => {
  3399. // Prefer the cached value over our new stat to report consistent results
  3400. const cache = this._fileTimestamps.get(file);
  3401. if (cache !== undefined) {
  3402. return callback(null, cache === "ignore" ? null : cache);
  3403. }
  3404. const mtime = Number(stat.mtime);
  3405. if (mtime) applyMtime(mtime);
  3406. /** @type {FileSystemInfoEntry} */
  3407. const ts = {
  3408. safeTime: mtime ? mtime + FS_ACCURACY : Infinity,
  3409. timestamp: mtime
  3410. };
  3411. this._fileTimestamps.set(file, ts);
  3412. this._cachedDeprecatedFileTimestamps = undefined;
  3413. callback(null, ts);
  3414. },
  3415. fromDirectory: (directory, stat, callback) => {
  3416. this.contextTimestampQueue.increaseParallelism();
  3417. this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => {
  3418. this.contextTimestampQueue.decreaseParallelism();
  3419. callback(err, tsEntry);
  3420. });
  3421. },
  3422. reduce: (files, tsEntries) => {
  3423. let symlinks;
  3424. const hash = createHash(this._hashFunction);
  3425. for (const file of files) hash.update(file);
  3426. let safeTime = 0;
  3427. for (const _e of tsEntries) {
  3428. if (!_e) {
  3429. hash.update("n");
  3430. continue;
  3431. }
  3432. const entry =
  3433. /** @type {FileSystemInfoEntry | ContextFileSystemInfoEntry} */
  3434. (_e);
  3435. if (/** @type {FileSystemInfoEntry} */ (entry).timestamp) {
  3436. hash.update("f");
  3437. hash.update(
  3438. `${/** @type {FileSystemInfoEntry} */ (entry).timestamp}`
  3439. );
  3440. } else if (
  3441. /** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash
  3442. ) {
  3443. hash.update("d");
  3444. hash.update(
  3445. `${/** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash}`
  3446. );
  3447. }
  3448. if (
  3449. /** @type {ContextFileSystemInfoEntry} */
  3450. (entry).symlinks !== undefined
  3451. ) {
  3452. if (symlinks === undefined) symlinks = new Set();
  3453. addAll(
  3454. /** @type {ContextFileSystemInfoEntry} */ (entry).symlinks,
  3455. symlinks
  3456. );
  3457. }
  3458. if (entry.safeTime) {
  3459. safeTime = Math.max(safeTime, entry.safeTime);
  3460. }
  3461. }
  3462. const digest = hash.digest("hex");
  3463. /** @type {ContextFileSystemInfoEntry} */
  3464. const result = {
  3465. safeTime,
  3466. timestampHash: digest
  3467. };
  3468. if (symlinks) result.symlinks = symlinks;
  3469. return result;
  3470. }
  3471. },
  3472. (err, result) => {
  3473. if (err) return callback(/** @type {WebpackError} */ (err));
  3474. this._contextTimestamps.set(path, result);
  3475. this._cachedDeprecatedContextTimestamps = undefined;
  3476. callback(null, result);
  3477. }
  3478. );
  3479. }
  3480. /**
  3481. * @private
  3482. * @param {ContextFileSystemInfoEntry} entry entry
  3483. * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback
  3484. * @returns {void}
  3485. */
  3486. _resolveContextTimestamp(entry, callback) {
  3487. /** @type {string[]} */
  3488. const hashes = [];
  3489. let safeTime = 0;
  3490. processAsyncTree(
  3491. /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
  3492. 10,
  3493. (target, push, callback) => {
  3494. this._getUnresolvedContextTimestamp(target, (err, entry) => {
  3495. if (err) return callback(err);
  3496. if (entry && entry !== "ignore") {
  3497. hashes.push(/** @type {string} */ (entry.timestampHash));
  3498. if (entry.safeTime) {
  3499. safeTime = Math.max(safeTime, entry.safeTime);
  3500. }
  3501. if (entry.symlinks !== undefined) {
  3502. for (const target of entry.symlinks) push(target);
  3503. }
  3504. }
  3505. callback();
  3506. });
  3507. },
  3508. (err) => {
  3509. if (err) return callback(/** @type {WebpackError} */ (err));
  3510. const hash = createHash(this._hashFunction);
  3511. hash.update(/** @type {string} */ (entry.timestampHash));
  3512. if (entry.safeTime) {
  3513. safeTime = Math.max(safeTime, entry.safeTime);
  3514. }
  3515. hashes.sort();
  3516. for (const h of hashes) {
  3517. hash.update(h);
  3518. }
  3519. callback(
  3520. null,
  3521. (entry.resolved = {
  3522. safeTime,
  3523. timestampHash: hash.digest("hex")
  3524. })
  3525. );
  3526. }
  3527. );
  3528. }
  3529. /**
  3530. * @private
  3531. * @type {Processor<string, ContextHash>}
  3532. */
  3533. _readContextHash(path, callback) {
  3534. this._readContext(
  3535. {
  3536. path,
  3537. fromImmutablePath: () => /** @type {ContextHash | ""} */ (""),
  3538. fromManagedItem: (info) => info || "",
  3539. fromSymlink: (file, target, callback) => {
  3540. callback(
  3541. null,
  3542. /** @type {ContextHash} */
  3543. ({
  3544. hash: target,
  3545. symlinks: new Set([target])
  3546. })
  3547. );
  3548. },
  3549. fromFile: (file, stat, callback) =>
  3550. this.getFileHash(file, (err, hash) => {
  3551. callback(err, hash || "");
  3552. }),
  3553. fromDirectory: (directory, stat, callback) => {
  3554. this.contextHashQueue.increaseParallelism();
  3555. this._getUnresolvedContextHash(directory, (err, hash) => {
  3556. this.contextHashQueue.decreaseParallelism();
  3557. callback(err, hash || "");
  3558. });
  3559. },
  3560. /**
  3561. * @param {string[]} files files
  3562. * @param {(string | ContextHash)[]} fileHashes hashes
  3563. * @returns {ContextHash} reduced hash
  3564. */
  3565. reduce: (files, fileHashes) => {
  3566. let symlinks;
  3567. const hash = createHash(this._hashFunction);
  3568. for (const file of files) hash.update(file);
  3569. for (const entry of fileHashes) {
  3570. if (typeof entry === "string") {
  3571. hash.update(entry);
  3572. } else {
  3573. hash.update(entry.hash);
  3574. if (entry.symlinks) {
  3575. if (symlinks === undefined) symlinks = new Set();
  3576. addAll(entry.symlinks, symlinks);
  3577. }
  3578. }
  3579. }
  3580. /** @type {ContextHash} */
  3581. const result = {
  3582. hash: hash.digest("hex")
  3583. };
  3584. if (symlinks) result.symlinks = symlinks;
  3585. return result;
  3586. }
  3587. },
  3588. (err, _result) => {
  3589. if (err) return callback(/** @type {WebpackError} */ (err));
  3590. const result = /** @type {ContextHash} */ (_result);
  3591. this._contextHashes.set(path, result);
  3592. return callback(null, result);
  3593. }
  3594. );
  3595. }
  3596. /**
  3597. * @private
  3598. * @param {ContextHash} entry context hash
  3599. * @param {(err: WebpackError | null, contextHash?: string) => void} callback callback
  3600. * @returns {void}
  3601. */
  3602. _resolveContextHash(entry, callback) {
  3603. /** @type {string[]} */
  3604. const hashes = [];
  3605. processAsyncTree(
  3606. /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
  3607. 10,
  3608. (target, push, callback) => {
  3609. this._getUnresolvedContextHash(target, (err, hash) => {
  3610. if (err) return callback(err);
  3611. if (hash) {
  3612. hashes.push(hash.hash);
  3613. if (hash.symlinks !== undefined) {
  3614. for (const target of hash.symlinks) push(target);
  3615. }
  3616. }
  3617. callback();
  3618. });
  3619. },
  3620. (err) => {
  3621. if (err) return callback(/** @type {WebpackError} */ (err));
  3622. const hash = createHash(this._hashFunction);
  3623. hash.update(entry.hash);
  3624. hashes.sort();
  3625. for (const h of hashes) {
  3626. hash.update(h);
  3627. }
  3628. callback(null, (entry.resolved = hash.digest("hex")));
  3629. }
  3630. );
  3631. }
  3632. /**
  3633. * @private
  3634. * @type {Processor<string, ContextTimestampAndHash>}
  3635. */
  3636. _readContextTimestampAndHash(path, callback) {
  3637. /**
  3638. * @param {ContextTimestamp} timestamp timestamp
  3639. * @param {ContextHash} hash hash
  3640. */
  3641. const finalize = (timestamp, hash) => {
  3642. const result =
  3643. /** @type {ContextTimestampAndHash} */
  3644. (timestamp === "ignore" ? hash : { ...timestamp, ...hash });
  3645. this._contextTshs.set(path, result);
  3646. callback(null, result);
  3647. };
  3648. const cachedHash = this._contextHashes.get(path);
  3649. const cachedTimestamp = this._contextTimestamps.get(path);
  3650. if (cachedHash !== undefined) {
  3651. if (cachedTimestamp !== undefined) {
  3652. finalize(cachedTimestamp, cachedHash);
  3653. } else {
  3654. this.contextTimestampQueue.add(path, (err, entry) => {
  3655. if (err) return callback(err);
  3656. finalize(
  3657. /** @type {ContextFileSystemInfoEntry} */
  3658. (entry),
  3659. cachedHash
  3660. );
  3661. });
  3662. }
  3663. } else if (cachedTimestamp !== undefined) {
  3664. this.contextHashQueue.add(path, (err, entry) => {
  3665. if (err) return callback(err);
  3666. finalize(cachedTimestamp, /** @type {ContextHash} */ (entry));
  3667. });
  3668. } else {
  3669. this._readContext(
  3670. {
  3671. path,
  3672. fromImmutablePath: () =>
  3673. /** @type {ContextTimestampAndHash | Omit<ContextTimestampAndHash, "safeTime"> | string | null} */ (
  3674. null
  3675. ),
  3676. fromManagedItem: (info) => ({
  3677. safeTime: 0,
  3678. timestampHash: info,
  3679. hash: info || ""
  3680. }),
  3681. fromSymlink: (file, target, callback) => {
  3682. callback(null, {
  3683. timestampHash: target,
  3684. hash: target,
  3685. symlinks: new Set([target])
  3686. });
  3687. },
  3688. fromFile: (file, stat, callback) => {
  3689. this._getFileTimestampAndHash(file, callback);
  3690. },
  3691. fromDirectory: (directory, stat, callback) => {
  3692. this.contextTshQueue.increaseParallelism();
  3693. this.contextTshQueue.add(directory, (err, result) => {
  3694. this.contextTshQueue.decreaseParallelism();
  3695. callback(err, result);
  3696. });
  3697. },
  3698. /**
  3699. * @param {string[]} files files
  3700. * @param {(Partial<TimestampAndHash> & Partial<ContextTimestampAndHash> | string | null)[]} results results
  3701. * @returns {ContextTimestampAndHash} tsh
  3702. */
  3703. reduce: (files, results) => {
  3704. let symlinks;
  3705. const tsHash = createHash(this._hashFunction);
  3706. const hash = createHash(this._hashFunction);
  3707. for (const file of files) {
  3708. tsHash.update(file);
  3709. hash.update(file);
  3710. }
  3711. let safeTime = 0;
  3712. for (const entry of results) {
  3713. if (!entry) {
  3714. tsHash.update("n");
  3715. continue;
  3716. }
  3717. if (typeof entry === "string") {
  3718. tsHash.update("n");
  3719. hash.update(entry);
  3720. continue;
  3721. }
  3722. if (entry.timestamp) {
  3723. tsHash.update("f");
  3724. tsHash.update(`${entry.timestamp}`);
  3725. } else if (entry.timestampHash) {
  3726. tsHash.update("d");
  3727. tsHash.update(`${entry.timestampHash}`);
  3728. }
  3729. if (entry.symlinks !== undefined) {
  3730. if (symlinks === undefined) symlinks = new Set();
  3731. addAll(entry.symlinks, symlinks);
  3732. }
  3733. if (entry.safeTime) {
  3734. safeTime = Math.max(safeTime, entry.safeTime);
  3735. }
  3736. hash.update(/** @type {string} */ (entry.hash));
  3737. }
  3738. /** @type {ContextTimestampAndHash} */
  3739. const result = {
  3740. safeTime,
  3741. timestampHash: tsHash.digest("hex"),
  3742. hash: hash.digest("hex")
  3743. };
  3744. if (symlinks) result.symlinks = symlinks;
  3745. return result;
  3746. }
  3747. },
  3748. (err, _result) => {
  3749. if (err) return callback(/** @type {WebpackError} */ (err));
  3750. const result = /** @type {ContextTimestampAndHash} */ (_result);
  3751. this._contextTshs.set(path, result);
  3752. return callback(null, result);
  3753. }
  3754. );
  3755. }
  3756. }
  3757. /**
  3758. * @private
  3759. * @param {ContextTimestampAndHash} entry entry
  3760. * @param {ProcessorCallback<ResolvedContextTimestampAndHash>} callback callback
  3761. * @returns {void}
  3762. */
  3763. _resolveContextTsh(entry, callback) {
  3764. /** @type {string[]} */
  3765. const hashes = [];
  3766. /** @type {string[]} */
  3767. const tsHashes = [];
  3768. let safeTime = 0;
  3769. processAsyncTree(
  3770. /** @type {NonNullable<ContextHash["symlinks"]>} */ (entry.symlinks),
  3771. 10,
  3772. (target, push, callback) => {
  3773. this._getUnresolvedContextTsh(target, (err, entry) => {
  3774. if (err) return callback(err);
  3775. if (entry) {
  3776. hashes.push(entry.hash);
  3777. if (entry.timestampHash) tsHashes.push(entry.timestampHash);
  3778. if (entry.safeTime) {
  3779. safeTime = Math.max(safeTime, entry.safeTime);
  3780. }
  3781. if (entry.symlinks !== undefined) {
  3782. for (const target of entry.symlinks) push(target);
  3783. }
  3784. }
  3785. callback();
  3786. });
  3787. },
  3788. (err) => {
  3789. if (err) return callback(/** @type {WebpackError} */ (err));
  3790. const hash = createHash(this._hashFunction);
  3791. const tsHash = createHash(this._hashFunction);
  3792. hash.update(entry.hash);
  3793. if (entry.timestampHash) tsHash.update(entry.timestampHash);
  3794. if (entry.safeTime) {
  3795. safeTime = Math.max(safeTime, entry.safeTime);
  3796. }
  3797. hashes.sort();
  3798. for (const h of hashes) {
  3799. hash.update(h);
  3800. }
  3801. tsHashes.sort();
  3802. for (const h of tsHashes) {
  3803. tsHash.update(h);
  3804. }
  3805. callback(
  3806. null,
  3807. (entry.resolved = {
  3808. safeTime,
  3809. timestampHash: tsHash.digest("hex"),
  3810. hash: hash.digest("hex")
  3811. })
  3812. );
  3813. }
  3814. );
  3815. }
  3816. /**
  3817. * @private
  3818. * @type {Processor<string, Set<string>>}
  3819. */
  3820. _getManagedItemDirectoryInfo(path, callback) {
  3821. this.fs.readdir(path, (err, elements) => {
  3822. if (err) {
  3823. if (err.code === "ENOENT" || err.code === "ENOTDIR") {
  3824. return callback(null, EMPTY_SET);
  3825. }
  3826. return callback(/** @type {WebpackError} */ (err));
  3827. }
  3828. const set = new Set(
  3829. /** @type {string[]} */ (elements).map((element) =>
  3830. join(this.fs, path, element)
  3831. )
  3832. );
  3833. callback(null, set);
  3834. });
  3835. }
  3836. /**
  3837. * @private
  3838. * @type {Processor<string, string>}
  3839. */
  3840. _getManagedItemInfo(path, callback) {
  3841. const dir = dirname(this.fs, path);
  3842. this.managedItemDirectoryQueue.add(dir, (err, elements) => {
  3843. if (err) {
  3844. return callback(err);
  3845. }
  3846. if (!(/** @type {Set<string>} */ (elements).has(path))) {
  3847. // file or directory doesn't exist
  3848. this._managedItems.set(path, "*missing");
  3849. return callback(null, "*missing");
  3850. }
  3851. // something exists
  3852. // it may be a file or directory
  3853. if (
  3854. path.endsWith("node_modules") &&
  3855. (path.endsWith("/node_modules") || path.endsWith("\\node_modules"))
  3856. ) {
  3857. // we are only interested in existence of this special directory
  3858. this._managedItems.set(path, "*node_modules");
  3859. return callback(null, "*node_modules");
  3860. }
  3861. // we assume it's a directory, as files shouldn't occur in managed paths
  3862. const packageJsonPath = join(this.fs, path, "package.json");
  3863. this.fs.readFile(packageJsonPath, (err, content) => {
  3864. if (err) {
  3865. if (err.code === "ENOENT" || err.code === "ENOTDIR") {
  3866. // no package.json or path is not a directory
  3867. this.fs.readdir(path, (err, elements) => {
  3868. if (
  3869. !err &&
  3870. /** @type {string[]} */ (elements).length === 1 &&
  3871. /** @type {string[]} */ (elements)[0] === "node_modules"
  3872. ) {
  3873. // This is only a grouping folder e.g. used by yarn
  3874. // we are only interested in existence of this special directory
  3875. this._managedItems.set(path, "*nested");
  3876. return callback(null, "*nested");
  3877. }
  3878. /** @type {Logger} */
  3879. (this.logger).warn(
  3880. `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)`
  3881. );
  3882. return callback();
  3883. });
  3884. return;
  3885. }
  3886. return callback(/** @type {WebpackError} */ (err));
  3887. }
  3888. let data;
  3889. try {
  3890. data = JSON.parse(/** @type {Buffer} */ (content).toString("utf8"));
  3891. } catch (parseErr) {
  3892. return callback(/** @type {WebpackError} */ (parseErr));
  3893. }
  3894. if (!data.name) {
  3895. /** @type {Logger} */
  3896. (this.logger).warn(
  3897. `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)`
  3898. );
  3899. return callback();
  3900. }
  3901. const info = `${data.name || ""}@${data.version || ""}`;
  3902. this._managedItems.set(path, info);
  3903. callback(null, info);
  3904. });
  3905. });
  3906. }
  3907. getDeprecatedFileTimestamps() {
  3908. if (this._cachedDeprecatedFileTimestamps !== undefined) {
  3909. return this._cachedDeprecatedFileTimestamps;
  3910. }
  3911. /** @type {Map<string, number | null>} */
  3912. const map = new Map();
  3913. for (const [path, info] of this._fileTimestamps) {
  3914. if (info) map.set(path, typeof info === "object" ? info.safeTime : null);
  3915. }
  3916. return (this._cachedDeprecatedFileTimestamps = map);
  3917. }
  3918. getDeprecatedContextTimestamps() {
  3919. if (this._cachedDeprecatedContextTimestamps !== undefined) {
  3920. return this._cachedDeprecatedContextTimestamps;
  3921. }
  3922. /** @type {Map<string, number | null>} */
  3923. const map = new Map();
  3924. for (const [path, info] of this._contextTimestamps) {
  3925. if (info) map.set(path, typeof info === "object" ? info.safeTime : null);
  3926. }
  3927. return (this._cachedDeprecatedContextTimestamps = map);
  3928. }
  3929. }
  3930. module.exports = FileSystemInfo;
  3931. module.exports.Snapshot = Snapshot;