FileSystemInfo.js 104 KB

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