FileSystemInfo.js 102 KB

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