FileSystemInfo.js 106 KB

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