FileSystemInfo.js 103 KB

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