FileSystemInfo.js 118 KB

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