Compilation.js 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const asyncLib = require("neo-async");
  8. const {
  9. AsyncParallelHook,
  10. AsyncSeriesBailHook,
  11. AsyncSeriesHook,
  12. HookMap,
  13. SyncBailHook,
  14. SyncHook,
  15. SyncWaterfallHook
  16. } = require("tapable");
  17. const { CachedSource } = require("webpack-sources");
  18. const { MultiItemCache } = require("./CacheFacade");
  19. const Chunk = require("./Chunk");
  20. const ChunkGraph = require("./ChunkGraph");
  21. const ChunkGroup = require("./ChunkGroup");
  22. const ChunkRenderError = require("./ChunkRenderError");
  23. const ChunkTemplate = require("./ChunkTemplate");
  24. const CodeGenerationError = require("./CodeGenerationError");
  25. const CodeGenerationResults = require("./CodeGenerationResults");
  26. const Dependency = require("./Dependency");
  27. const DependencyTemplates = require("./DependencyTemplates");
  28. const Entrypoint = require("./Entrypoint");
  29. const ErrorHelpers = require("./ErrorHelpers");
  30. const FileSystemInfo = require("./FileSystemInfo");
  31. const {
  32. connectChunkGroupAndChunk,
  33. connectChunkGroupParentAndChild,
  34. connectEntrypointAndDependOn
  35. } = require("./GraphHelpers");
  36. const {
  37. makeWebpackError,
  38. tryRunOrWebpackError
  39. } = require("./HookWebpackError");
  40. const MainTemplate = require("./MainTemplate");
  41. const Module = require("./Module");
  42. const ModuleDependencyError = require("./ModuleDependencyError");
  43. const ModuleDependencyWarning = require("./ModuleDependencyWarning");
  44. const ModuleGraph = require("./ModuleGraph");
  45. const ModuleHashingError = require("./ModuleHashingError");
  46. const ModuleNotFoundError = require("./ModuleNotFoundError");
  47. const ModuleProfile = require("./ModuleProfile");
  48. const ModuleRestoreError = require("./ModuleRestoreError");
  49. const ModuleStoreError = require("./ModuleStoreError");
  50. const ModuleTemplate = require("./ModuleTemplate");
  51. const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
  52. const RuntimeGlobals = require("./RuntimeGlobals");
  53. const RuntimeTemplate = require("./RuntimeTemplate");
  54. const Stats = require("./Stats");
  55. const WebpackError = require("./WebpackError");
  56. const buildChunkGraph = require("./buildChunkGraph");
  57. const BuildCycleError = require("./errors/BuildCycleError");
  58. const { LogType, Logger } = require("./logging/Logger");
  59. const StatsFactory = require("./stats/StatsFactory");
  60. const StatsPrinter = require("./stats/StatsPrinter");
  61. const { equals: arrayEquals } = require("./util/ArrayHelpers");
  62. const AsyncQueue = require("./util/AsyncQueue");
  63. const LazySet = require("./util/LazySet");
  64. const { getOrInsert } = require("./util/MapHelpers");
  65. const WeakTupleMap = require("./util/WeakTupleMap");
  66. const { cachedCleverMerge } = require("./util/cleverMerge");
  67. const {
  68. compareIds,
  69. compareLocations,
  70. compareModulesByIdentifier,
  71. compareSelect,
  72. compareStringsNumeric,
  73. concatComparators
  74. } = require("./util/comparators");
  75. const createHash = require("./util/createHash");
  76. const {
  77. arrayToSetDeprecation,
  78. createFakeHook,
  79. soonFrozenObjectDeprecation
  80. } = require("./util/deprecation");
  81. const processAsyncTree = require("./util/processAsyncTree");
  82. const { getRuntimeKey } = require("./util/runtime");
  83. const { isSourceEqual } = require("./util/source");
  84. /** @typedef {import("webpack-sources").Source} Source */
  85. /** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
  86. /** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
  87. /** @typedef {import("../declarations/WebpackOptions").HashDigest} HashDigest */
  88. /** @typedef {import("../declarations/WebpackOptions").HashDigestLength} HashDigestLength */
  89. /** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */
  90. /** @typedef {import("../declarations/WebpackOptions").Plugins} Plugins */
  91. /** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
  92. /** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptionsWithDefaults */
  93. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  94. /** @typedef {import("./Cache")} Cache */
  95. /** @typedef {import("./CacheFacade")} CacheFacade */
  96. /** @typedef {import("./Chunk").ChunkName} ChunkName */
  97. /** @typedef {import("./Chunk").ChunkId} ChunkId */
  98. /** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */
  99. /** @typedef {import("./Compiler")} Compiler */
  100. /** @typedef {import("./Compiler").CompilationParams} CompilationParams */
  101. /** @typedef {import("./Compiler").MemCache} MemCache */
  102. /** @typedef {import("./Compiler").WeakReferences} WeakReferences */
  103. /** @typedef {import("./Compiler").ModuleMemCachesItem} ModuleMemCachesItem */
  104. /** @typedef {import("./Compiler").Records} Records */
  105. /** @typedef {import("./DependenciesBlock")} DependenciesBlock */
  106. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  107. /** @typedef {import("./Dependency").ReferencedExports} ReferencedExports */
  108. /** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
  109. /** @typedef {import("./Module").NameForCondition} NameForCondition */
  110. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  111. /** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
  112. /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
  113. /** @typedef {import("./NormalModule").NormalModuleCompilationHooks} NormalModuleCompilationHooks */
  114. /** @typedef {import("./Module").FactoryMeta} FactoryMeta */
  115. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  116. /** @typedef {import("./ModuleFactory")} ModuleFactory */
  117. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  118. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  119. /** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */
  120. /** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */
  121. /** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
  122. /** @typedef {import("./NormalModule").ParserOptions} ParserOptions */
  123. /** @typedef {import("./NormalModule").GeneratorOptions} GeneratorOptions */
  124. /** @typedef {import("./RequestShortener")} RequestShortener */
  125. /** @typedef {import("./RuntimeModule")} RuntimeModule */
  126. /** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */
  127. /** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */
  128. /** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */
  129. /** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */
  130. /** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */
  131. /** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
  132. /** @typedef {import("./util/Hash")} Hash */
  133. /**
  134. * @template T
  135. * @typedef {import("tapable").AsArray<T>} AsArray<T>
  136. */
  137. /**
  138. * @template T
  139. * @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
  140. */
  141. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  142. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  143. /**
  144. * @callback Callback
  145. * @param {(WebpackError | null)=} err
  146. * @returns {void}
  147. */
  148. /**
  149. * @callback ModuleCallback
  150. * @param {WebpackError | null=} err
  151. * @param {Module | null=} result
  152. * @returns {void}
  153. */
  154. /**
  155. * @callback ModuleFactoryResultCallback
  156. * @param {WebpackError | null=} err
  157. * @param {ModuleFactoryResult | null=} result
  158. * @returns {void}
  159. */
  160. /**
  161. * @callback ModuleOrModuleFactoryResultCallback
  162. * @param {WebpackError | null=} err
  163. * @param {Module | ModuleFactoryResult | null=} result
  164. * @returns {void}
  165. */
  166. /**
  167. * @callback ExecuteModuleCallback
  168. * @param {WebpackError | null=} err
  169. * @param {ExecuteModuleResult | null=} result
  170. * @returns {void}
  171. */
  172. /** @typedef {new (...args: EXPECTED_ANY[]) => Dependency} DependencyConstructor */
  173. /** @typedef {Record<string, Source>} CompilationAssets */
  174. /**
  175. * @typedef {object} AvailableModulesChunkGroupMapping
  176. * @property {ChunkGroup} chunkGroup
  177. * @property {Set<Module>} availableModules
  178. * @property {boolean} needCopy
  179. */
  180. /**
  181. * @typedef {object} DependenciesBlockLike
  182. * @property {Dependency[]} dependencies
  183. * @property {AsyncDependenciesBlock[]} blocks
  184. */
  185. /** @typedef {Set<Chunk>} Chunks */
  186. /**
  187. * @typedef {object} ChunkPathData
  188. * @property {string | number} id
  189. * @property {string=} name
  190. * @property {string} hash
  191. * @property {HashWithLengthFunction=} hashWithLength
  192. * @property {(Record<string, string>)=} contentHash
  193. * @property {(Record<string, HashWithLengthFunction>)=} contentHashWithLength
  194. */
  195. /**
  196. * @typedef {object} ChunkHashContext
  197. * @property {CodeGenerationResults} codeGenerationResults results of code generation
  198. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  199. * @property {ModuleGraph} moduleGraph the module graph
  200. * @property {ChunkGraph} chunkGraph the chunk graph
  201. */
  202. /**
  203. * @typedef {object} RuntimeRequirementsContext
  204. * @property {ChunkGraph} chunkGraph the chunk graph
  205. * @property {CodeGenerationResults} codeGenerationResults the code generation results
  206. */
  207. /**
  208. * @typedef {object} ExecuteModuleOptions
  209. * @property {EntryOptions=} entryOptions
  210. */
  211. /** @typedef {LazySet<string>} FileSystemDependencies */
  212. /** @typedef {EXPECTED_ANY} ExecuteModuleExports */
  213. /**
  214. * @typedef {object} ExecuteModuleResult
  215. * @property {ExecuteModuleExports} exports
  216. * @property {boolean} cacheable
  217. * @property {ExecuteModuleAssets} assets
  218. * @property {FileSystemDependencies} fileDependencies
  219. * @property {FileSystemDependencies} contextDependencies
  220. * @property {FileSystemDependencies} missingDependencies
  221. * @property {FileSystemDependencies} buildDependencies
  222. */
  223. /**
  224. * @typedef {object} ExecuteModuleObject
  225. * @property {string=} id module id
  226. * @property {ExecuteModuleExports} exports exports
  227. * @property {boolean} loaded is loaded
  228. * @property {Error=} error error
  229. */
  230. /**
  231. * @typedef {object} ExecuteModuleArgument
  232. * @property {Module} module
  233. * @property {ExecuteModuleObject=} moduleObject
  234. * @property {CodeGenerationResult} codeGenerationResult
  235. */
  236. /** @typedef {((id: string) => ExecuteModuleExports) & { i?: ((options: ExecuteOptions) => void)[], c?: Record<string, ExecuteModuleObject> }} WebpackRequire */
  237. /**
  238. * @typedef {object} ExecuteOptions
  239. * @property {string=} id module id
  240. * @property {ExecuteModuleObject} module module
  241. * @property {WebpackRequire} require require function
  242. */
  243. /** @typedef {Map<string, { source: Source, info: AssetInfo | undefined }>} ExecuteModuleAssets */
  244. /**
  245. * @typedef {object} ExecuteModuleContext
  246. * @property {ExecuteModuleAssets} assets
  247. * @property {Chunk} chunk
  248. * @property {ChunkGraph} chunkGraph
  249. * @property {WebpackRequire=} __webpack_require__
  250. */
  251. /**
  252. * @typedef {object} EntryData
  253. * @property {Dependency[]} dependencies dependencies of the entrypoint that should be evaluated at startup
  254. * @property {Dependency[]} includeDependencies dependencies of the entrypoint that should be included but not evaluated
  255. * @property {EntryOptions} options options of the entrypoint
  256. */
  257. /**
  258. * @typedef {object} LogEntry
  259. * @property {string} type
  260. * @property {EXPECTED_ANY[]=} args
  261. * @property {number} time
  262. * @property {string[]=} trace
  263. */
  264. /**
  265. * @typedef {object} KnownAssetInfo
  266. * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash)
  267. * @property {boolean=} minimized whether the asset is minimized
  268. * @property {string | string[]=} fullhash the value(s) of the full hash used for this asset
  269. * @property {string | string[]=} chunkhash the value(s) of the chunk hash used for this asset
  270. * @property {string | string[]=} modulehash the value(s) of the module hash used for this asset
  271. * @property {string | string[]=} contenthash the value(s) of the content hash used for this asset
  272. * @property {string=} sourceFilename when asset was created from a source file (potentially transformed), the original filename relative to compilation context
  273. * @property {number=} size size in bytes, only set after asset has been emitted
  274. * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets
  275. * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR)
  276. * @property {boolean=} javascriptModule true, when asset is javascript and an ESM
  277. * @property {boolean=} manifest true, when file is a manifest
  278. * @property {Record<string, null | string | string[]>=} related object of pointers to other assets, keyed by type of relation (only points from parent to child)
  279. */
  280. /** @typedef {KnownAssetInfo & Record<string, EXPECTED_ANY>} AssetInfo */
  281. /** @typedef {{ path: string, info: AssetInfo }} InterpolatedPathAndAssetInfo */
  282. /**
  283. * @typedef {object} Asset
  284. * @property {string} name the filename of the asset
  285. * @property {Source} source source of the asset
  286. * @property {AssetInfo} info info about the asset
  287. */
  288. /** @typedef {(length: number) => string} HashWithLengthFunction */
  289. /**
  290. * @typedef {object} ModulePathData
  291. * @property {string | number} id
  292. * @property {string} hash
  293. * @property {HashWithLengthFunction=} hashWithLength
  294. */
  295. /** @typedef {(id: string | number) => string | number} PrepareIdFunction */
  296. /**
  297. * @typedef {object} PathData
  298. * @property {ChunkGraph=} chunkGraph
  299. * @property {string=} hash
  300. * @property {HashWithLengthFunction=} hashWithLength
  301. * @property {(Chunk | ChunkPathData)=} chunk
  302. * @property {(Module | ModulePathData)=} module
  303. * @property {RuntimeSpec=} runtime
  304. * @property {string=} filename
  305. * @property {string=} basename
  306. * @property {string=} query
  307. * @property {string=} contentHashType
  308. * @property {string=} contentHash
  309. * @property {HashWithLengthFunction=} contentHashWithLength
  310. * @property {boolean=} noChunkHash
  311. * @property {string=} url
  312. * @property {PrepareIdFunction=} prepareId
  313. */
  314. /** @typedef {"module" | "chunk" | "root-of-chunk" | "nested"} ExcludeModulesType */
  315. /**
  316. * @typedef {object} KnownNormalizedStatsOptions
  317. * @property {string} context
  318. * @property {RequestShortener} requestShortener
  319. * @property {string | false} chunksSort
  320. * @property {string | false} modulesSort
  321. * @property {string | false} chunkModulesSort
  322. * @property {string | false} nestedModulesSort
  323. * @property {string | false} assetsSort
  324. * @property {boolean} ids
  325. * @property {boolean} cachedAssets
  326. * @property {boolean} groupAssetsByEmitStatus
  327. * @property {boolean} groupAssetsByPath
  328. * @property {boolean} groupAssetsByExtension
  329. * @property {number} assetsSpace
  330. * @property {((value: string, asset: StatsAsset) => boolean)[]} excludeAssets
  331. * @property {((name: string, module: StatsModule, type: ExcludeModulesType) => boolean)[]} excludeModules
  332. * @property {((warning: StatsError, textValue: string) => boolean)[]} warningsFilter
  333. * @property {boolean} cachedModules
  334. * @property {boolean} orphanModules
  335. * @property {boolean} dependentModules
  336. * @property {boolean} runtimeModules
  337. * @property {boolean} groupModulesByCacheStatus
  338. * @property {boolean} groupModulesByLayer
  339. * @property {boolean} groupModulesByAttributes
  340. * @property {boolean} groupModulesByPath
  341. * @property {boolean} groupModulesByExtension
  342. * @property {boolean} groupModulesByType
  343. * @property {boolean | "auto"} entrypoints
  344. * @property {boolean} chunkGroups
  345. * @property {boolean} chunkGroupAuxiliary
  346. * @property {boolean} chunkGroupChildren
  347. * @property {number} chunkGroupMaxAssets
  348. * @property {number} modulesSpace
  349. * @property {number} chunkModulesSpace
  350. * @property {number} nestedModulesSpace
  351. * @property {false | "none" | "error" | "warn" | "info" | "log" | "verbose"} logging
  352. * @property {((value: string) => boolean)[]} loggingDebug
  353. * @property {boolean} loggingTrace
  354. * @property {EXPECTED_ANY} _env
  355. */
  356. /** @typedef {KnownNormalizedStatsOptions & Omit<StatsOptions, keyof KnownNormalizedStatsOptions> & Record<string, EXPECTED_ANY>} NormalizedStatsOptions */
  357. /**
  358. * @typedef {object} KnownCreateStatsOptionsContext
  359. * @property {boolean=} forToString
  360. */
  361. /** @typedef {KnownCreateStatsOptionsContext & Record<string, EXPECTED_ANY>} CreateStatsOptionsContext */
  362. /** @typedef {{ module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}} CodeGenerationJob */
  363. /** @typedef {CodeGenerationJob[]} CodeGenerationJobs */
  364. /** @typedef {{javascript: ModuleTemplate}} ModuleTemplates */
  365. /** @typedef {Set<Module>} NotCodeGeneratedModules */
  366. /** @type {AssetInfo} */
  367. const EMPTY_ASSET_INFO = Object.freeze({});
  368. const esmDependencyCategory = "esm";
  369. // TODO webpack 6: remove
  370. const deprecatedNormalModuleLoaderHook = util.deprecate(
  371. /**
  372. * @param {Compilation} compilation compilation
  373. * @returns {NormalModuleCompilationHooks["loader"]} hooks
  374. */
  375. (compilation) =>
  376. require("./NormalModule").getCompilationHooks(compilation).loader,
  377. "Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader",
  378. "DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK"
  379. );
  380. // TODO webpack 6: remove
  381. /**
  382. * @param {ModuleTemplates | undefined} moduleTemplates module templates
  383. */
  384. const defineRemovedModuleTemplates = (moduleTemplates) => {
  385. Object.defineProperties(moduleTemplates, {
  386. asset: {
  387. enumerable: false,
  388. configurable: false,
  389. get: () => {
  390. throw new WebpackError(
  391. "Compilation.moduleTemplates.asset has been removed"
  392. );
  393. }
  394. },
  395. webassembly: {
  396. enumerable: false,
  397. configurable: false,
  398. get: () => {
  399. throw new WebpackError(
  400. "Compilation.moduleTemplates.webassembly has been removed"
  401. );
  402. }
  403. }
  404. });
  405. moduleTemplates = undefined;
  406. };
  407. const byId = compareSelect((c) => c.id, compareIds);
  408. const byNameOrHash = concatComparators(
  409. compareSelect((c) => c.name, compareIds),
  410. compareSelect((c) => c.fullHash, compareIds)
  411. );
  412. const byMessage = compareSelect(
  413. (err) => `${err.message}`,
  414. compareStringsNumeric
  415. );
  416. const byModule = compareSelect(
  417. (err) => (err.module && err.module.identifier()) || "",
  418. compareStringsNumeric
  419. );
  420. const byLocation = compareSelect((err) => err.loc, compareLocations);
  421. const compareErrors = concatComparators(byModule, byLocation, byMessage);
  422. /**
  423. * @typedef {object} KnownUnsafeCacheData
  424. * @property {FactoryMeta=} factoryMeta factory meta
  425. * @property {ResolveOptions=} resolveOptions resolve options
  426. * @property {ParserOptions=} parserOptions
  427. * @property {GeneratorOptions=} generatorOptions
  428. */
  429. /** @typedef {KnownUnsafeCacheData & Record<string, EXPECTED_ANY>} UnsafeCacheData */
  430. /**
  431. * @typedef {Module & { restoreFromUnsafeCache?: (unsafeCacheData: UnsafeCacheData, moduleFactory: ModuleFactory, compilationParams: CompilationParams) => void }} ModuleWithRestoreFromUnsafeCache
  432. */
  433. /** @type {WeakMap<Dependency, ModuleWithRestoreFromUnsafeCache | null>} */
  434. const unsafeCacheDependencies = new WeakMap();
  435. /** @type {WeakMap<ModuleWithRestoreFromUnsafeCache, UnsafeCacheData>} */
  436. const unsafeCacheData = new WeakMap();
  437. /** @typedef {{ id: ModuleId, modules?: Map<Module, ModuleId>, blocks?: (ChunkId | null)[] }} References */
  438. /** @typedef {Map<Module, WeakTupleMap<EXPECTED_ANY[], EXPECTED_ANY>>} ModuleMemCaches */
  439. class Compilation {
  440. /**
  441. * Creates an instance of Compilation.
  442. * @param {Compiler} compiler the compiler which created the compilation
  443. * @param {CompilationParams} params the compilation parameters
  444. */
  445. constructor(compiler, params) {
  446. this._backCompat = compiler._backCompat;
  447. const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this);
  448. /** @typedef {{ additionalAssets?: boolean | ((assets: CompilationAssets) => void) }} ProcessAssetsAdditionalOptions */
  449. /** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */
  450. const processAssetsHook = new AsyncSeriesHook(["assets"]);
  451. let savedAssets = new Set();
  452. /**
  453. * @param {CompilationAssets} assets assets
  454. * @returns {CompilationAssets} new assets
  455. */
  456. const popNewAssets = (assets) => {
  457. let newAssets;
  458. for (const file of Object.keys(assets)) {
  459. if (savedAssets.has(file)) continue;
  460. if (newAssets === undefined) {
  461. newAssets = Object.create(null);
  462. }
  463. newAssets[file] = assets[file];
  464. savedAssets.add(file);
  465. }
  466. return newAssets;
  467. };
  468. processAssetsHook.intercept({
  469. name: "Compilation",
  470. call: () => {
  471. savedAssets = new Set(Object.keys(this.assets));
  472. },
  473. register: (tap) => {
  474. const { type, name } = tap;
  475. const { fn, additionalAssets, ...remainingTap } = tap;
  476. const additionalAssetsFn =
  477. additionalAssets === true ? fn : additionalAssets;
  478. /** @typedef {WeakSet<CompilationAssets>} ProcessedAssets */
  479. /** @type {ProcessedAssets | undefined} */
  480. const processedAssets = additionalAssetsFn ? new WeakSet() : undefined;
  481. /**
  482. * @param {CompilationAssets} assets to be processed by additionalAssetsFn
  483. * @returns {CompilationAssets} available assets
  484. */
  485. const getAvailableAssets = (assets) => {
  486. /** @type {CompilationAssets} */
  487. const availableAssets = {};
  488. for (const file of Object.keys(assets)) {
  489. // https://github.com/webpack-contrib/compression-webpack-plugin/issues/390
  490. if (this.assets[file]) {
  491. availableAssets[file] = assets[file];
  492. }
  493. }
  494. return availableAssets;
  495. };
  496. switch (type) {
  497. case "sync":
  498. if (additionalAssetsFn) {
  499. this.hooks.processAdditionalAssets.tap(name, (assets) => {
  500. if (
  501. /** @type {ProcessedAssets} */
  502. (processedAssets).has(this.assets)
  503. ) {
  504. additionalAssetsFn(getAvailableAssets(assets));
  505. }
  506. });
  507. }
  508. return {
  509. ...remainingTap,
  510. type: "async",
  511. /**
  512. * @param {CompilationAssets} assets assets
  513. * @param {(err?: Error | null, result?: void) => void} callback callback
  514. * @returns {void}
  515. */
  516. fn: (assets, callback) => {
  517. try {
  518. fn(assets);
  519. } catch (err) {
  520. return callback(/** @type {Error} */ (err));
  521. }
  522. if (processedAssets !== undefined) {
  523. processedAssets.add(this.assets);
  524. }
  525. const newAssets = popNewAssets(assets);
  526. if (newAssets !== undefined) {
  527. this.hooks.processAdditionalAssets.callAsync(
  528. newAssets,
  529. callback
  530. );
  531. return;
  532. }
  533. callback();
  534. }
  535. };
  536. case "async":
  537. if (additionalAssetsFn) {
  538. this.hooks.processAdditionalAssets.tapAsync(
  539. name,
  540. (assets, callback) => {
  541. if (
  542. /** @type {ProcessedAssets} */
  543. (processedAssets).has(this.assets)
  544. ) {
  545. return additionalAssetsFn(
  546. getAvailableAssets(assets),
  547. callback
  548. );
  549. }
  550. callback();
  551. }
  552. );
  553. }
  554. return {
  555. ...remainingTap,
  556. /**
  557. * @param {CompilationAssets} assets assets
  558. * @param {(err?: Error | null, result?: void) => void} callback callback
  559. * @returns {void}
  560. */
  561. fn: (assets, callback) => {
  562. fn(
  563. assets,
  564. /**
  565. * @param {Error} err err
  566. * @returns {void}
  567. */
  568. (err) => {
  569. if (err) return callback(err);
  570. if (processedAssets !== undefined) {
  571. processedAssets.add(this.assets);
  572. }
  573. const newAssets = popNewAssets(assets);
  574. if (newAssets !== undefined) {
  575. this.hooks.processAdditionalAssets.callAsync(
  576. newAssets,
  577. callback
  578. );
  579. return;
  580. }
  581. callback();
  582. }
  583. );
  584. }
  585. };
  586. case "promise":
  587. if (additionalAssetsFn) {
  588. this.hooks.processAdditionalAssets.tapPromise(name, (assets) => {
  589. if (
  590. /** @type {ProcessedAssets} */
  591. (processedAssets).has(this.assets)
  592. ) {
  593. return additionalAssetsFn(getAvailableAssets(assets));
  594. }
  595. return Promise.resolve();
  596. });
  597. }
  598. return {
  599. ...remainingTap,
  600. /**
  601. * @param {CompilationAssets} assets assets
  602. * @returns {Promise<CompilationAssets>} result
  603. */
  604. fn: (assets) => {
  605. const p = fn(assets);
  606. if (!p || !p.then) return p;
  607. return p.then(() => {
  608. if (processedAssets !== undefined) {
  609. processedAssets.add(this.assets);
  610. }
  611. const newAssets = popNewAssets(assets);
  612. if (newAssets !== undefined) {
  613. return this.hooks.processAdditionalAssets.promise(
  614. newAssets
  615. );
  616. }
  617. });
  618. }
  619. };
  620. }
  621. }
  622. });
  623. /** @type {SyncHook<[CompilationAssets]>} */
  624. const afterProcessAssetsHook = new SyncHook(["assets"]);
  625. /**
  626. * @template T
  627. * @param {string} name name of the hook
  628. * @param {number} stage new stage
  629. * @param {() => AsArray<T>} getArgs get old hook function args
  630. * @param {string=} code deprecation code (not deprecated when unset)
  631. * @returns {FakeHook<Pick<AsyncSeriesHook<T>, "tap" | "tapAsync" | "tapPromise" | "name">> | undefined} fake hook which redirects
  632. */
  633. const createProcessAssetsHook = (name, stage, getArgs, code) => {
  634. if (!this._backCompat && code) return;
  635. /**
  636. * @param {string} reason reason
  637. * @returns {string} error message
  638. */
  639. const errorMessage = (
  640. reason
  641. ) => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}.
  642. BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`;
  643. /**
  644. * @param {string | (import("tapable").TapOptions & { name: string } & ProcessAssetsAdditionalOptions)} options hook options
  645. * @returns {import("tapable").TapOptions & { name: string } & ProcessAssetsAdditionalOptions} modified options
  646. */
  647. const getOptions = (options) => {
  648. if (typeof options === "string") options = { name: options };
  649. if (options.stage) {
  650. throw new Error(errorMessage("it's using the 'stage' option"));
  651. }
  652. return { ...options, stage };
  653. };
  654. return createFakeHook(
  655. {
  656. name,
  657. /** @type {AsyncSeriesHook<T>["intercept"]} */
  658. intercept(_interceptor) {
  659. throw new Error(errorMessage("it's using 'intercept'"));
  660. },
  661. /** @type {AsyncSeriesHook<T>["tap"]} */
  662. tap: (options, fn) => {
  663. processAssetsHook.tap(getOptions(options), () => fn(...getArgs()));
  664. },
  665. /** @type {AsyncSeriesHook<T>["tapAsync"]} */
  666. tapAsync: (options, fn) => {
  667. processAssetsHook.tapAsync(
  668. getOptions(options),
  669. (assets, callback) =>
  670. /** @type {EXPECTED_ANY} */ (fn)(...getArgs(), callback)
  671. );
  672. },
  673. /** @type {AsyncSeriesHook<T>["tapPromise"]} */
  674. tapPromise: (options, fn) => {
  675. processAssetsHook.tapPromise(getOptions(options), () =>
  676. fn(...getArgs())
  677. );
  678. }
  679. },
  680. `${name} is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)`,
  681. code
  682. );
  683. };
  684. this.hooks = Object.freeze({
  685. /** @type {SyncHook<[Module]>} */
  686. buildModule: new SyncHook(["module"]),
  687. /** @type {SyncHook<[Module]>} */
  688. rebuildModule: new SyncHook(["module"]),
  689. /** @type {SyncHook<[Module, WebpackError]>} */
  690. failedModule: new SyncHook(["module", "error"]),
  691. /** @type {SyncHook<[Module]>} */
  692. succeedModule: new SyncHook(["module"]),
  693. /** @type {SyncHook<[Module]>} */
  694. stillValidModule: new SyncHook(["module"]),
  695. /** @type {SyncHook<[Dependency, EntryOptions]>} */
  696. addEntry: new SyncHook(["entry", "options"]),
  697. /** @type {SyncHook<[Dependency, EntryOptions, Error]>} */
  698. failedEntry: new SyncHook(["entry", "options", "error"]),
  699. /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */
  700. succeedEntry: new SyncHook(["entry", "options", "module"]),
  701. /** @type {SyncWaterfallHook<[ReferencedExports, Dependency, RuntimeSpec]>} */
  702. dependencyReferencedExports: new SyncWaterfallHook([
  703. "referencedExports",
  704. "dependency",
  705. "runtime"
  706. ]),
  707. /** @type {SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */
  708. executeModule: new SyncHook(["options", "context"]),
  709. /** @type {AsyncParallelHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */
  710. prepareModuleExecution: new AsyncParallelHook(["options", "context"]),
  711. /** @type {AsyncSeriesHook<[Iterable<Module>]>} */
  712. finishModules: new AsyncSeriesHook(["modules"]),
  713. /** @type {AsyncSeriesHook<[Module]>} */
  714. finishRebuildingModule: new AsyncSeriesHook(["module"]),
  715. /** @type {SyncHook<[]>} */
  716. unseal: new SyncHook([]),
  717. /** @type {SyncHook<[]>} */
  718. seal: new SyncHook([]),
  719. /** @type {SyncHook<[]>} */
  720. beforeChunks: new SyncHook([]),
  721. /**
  722. * The `afterChunks` hook is called directly after the chunks and module graph have
  723. * been created and before the chunks and modules have been optimized. This hook is useful to
  724. * inspect, analyze, and/or modify the chunk graph.
  725. * @type {SyncHook<[Iterable<Chunk>]>}
  726. */
  727. afterChunks: new SyncHook(["chunks"]),
  728. /** @type {SyncBailHook<[Iterable<Module>], boolean | void>} */
  729. optimizeDependencies: new SyncBailHook(["modules"]),
  730. /** @type {SyncHook<[Iterable<Module>]>} */
  731. afterOptimizeDependencies: new SyncHook(["modules"]),
  732. /** @type {SyncHook<[]>} */
  733. optimize: new SyncHook([]),
  734. /** @type {SyncBailHook<[Iterable<Module>], boolean | void>} */
  735. optimizeModules: new SyncBailHook(["modules"]),
  736. /** @type {SyncHook<[Iterable<Module>]>} */
  737. afterOptimizeModules: new SyncHook(["modules"]),
  738. /** @type {SyncBailHook<[Iterable<Chunk>, ChunkGroup[]], boolean | void>} */
  739. optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]),
  740. /** @type {SyncHook<[Iterable<Chunk>, ChunkGroup[]]>} */
  741. afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]),
  742. /** @type {AsyncSeriesHook<[Iterable<Chunk>, Iterable<Module>]>} */
  743. optimizeTree: new AsyncSeriesHook(["chunks", "modules"]),
  744. /** @type {SyncHook<[Iterable<Chunk>, Iterable<Module>]>} */
  745. afterOptimizeTree: new SyncHook(["chunks", "modules"]),
  746. /** @type {AsyncSeriesBailHook<[Iterable<Chunk>, Iterable<Module>], void>} */
  747. optimizeChunkModules: new AsyncSeriesBailHook(["chunks", "modules"]),
  748. /** @type {SyncHook<[Iterable<Chunk>, Iterable<Module>]>} */
  749. afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]),
  750. /** @type {SyncBailHook<[], boolean | void>} */
  751. shouldRecord: new SyncBailHook([]),
  752. /** @type {SyncHook<[Chunk, RuntimeRequirements, RuntimeRequirementsContext]>} */
  753. additionalChunkRuntimeRequirements: new SyncHook([
  754. "chunk",
  755. "runtimeRequirements",
  756. "context"
  757. ]),
  758. /** @type {HookMap<SyncBailHook<[Chunk, RuntimeRequirements, RuntimeRequirementsContext], void>>} */
  759. runtimeRequirementInChunk: new HookMap(
  760. () => new SyncBailHook(["chunk", "runtimeRequirements", "context"])
  761. ),
  762. /** @type {SyncHook<[Module, RuntimeRequirements, RuntimeRequirementsContext]>} */
  763. additionalModuleRuntimeRequirements: new SyncHook([
  764. "module",
  765. "runtimeRequirements",
  766. "context"
  767. ]),
  768. /** @type {HookMap<SyncBailHook<[Module, RuntimeRequirements, RuntimeRequirementsContext], void>>} */
  769. runtimeRequirementInModule: new HookMap(
  770. () => new SyncBailHook(["module", "runtimeRequirements", "context"])
  771. ),
  772. /** @type {SyncHook<[Chunk, RuntimeRequirements, RuntimeRequirementsContext]>} */
  773. additionalTreeRuntimeRequirements: new SyncHook([
  774. "chunk",
  775. "runtimeRequirements",
  776. "context"
  777. ]),
  778. /** @type {HookMap<SyncBailHook<[Chunk, RuntimeRequirements, RuntimeRequirementsContext], void>>} */
  779. runtimeRequirementInTree: new HookMap(
  780. () => new SyncBailHook(["chunk", "runtimeRequirements", "context"])
  781. ),
  782. /** @type {SyncHook<[RuntimeModule, Chunk]>} */
  783. runtimeModule: new SyncHook(["module", "chunk"]),
  784. /** @type {SyncHook<[Iterable<Module>, Records]>} */
  785. reviveModules: new SyncHook(["modules", "records"]),
  786. /** @type {SyncHook<[Iterable<Module>]>} */
  787. beforeModuleIds: new SyncHook(["modules"]),
  788. /** @type {SyncHook<[Iterable<Module>]>} */
  789. moduleIds: new SyncHook(["modules"]),
  790. /** @type {SyncHook<[Iterable<Module>]>} */
  791. optimizeModuleIds: new SyncHook(["modules"]),
  792. /** @type {SyncHook<[Iterable<Module>]>} */
  793. afterOptimizeModuleIds: new SyncHook(["modules"]),
  794. /** @type {SyncHook<[Iterable<Chunk>, Records]>} */
  795. reviveChunks: new SyncHook(["chunks", "records"]),
  796. /** @type {SyncHook<[Iterable<Chunk>]>} */
  797. beforeChunkIds: new SyncHook(["chunks"]),
  798. /** @type {SyncHook<[Iterable<Chunk>]>} */
  799. chunkIds: new SyncHook(["chunks"]),
  800. /** @type {SyncHook<[Iterable<Chunk>]>} */
  801. optimizeChunkIds: new SyncHook(["chunks"]),
  802. /** @type {SyncHook<[Iterable<Chunk>]>} */
  803. afterOptimizeChunkIds: new SyncHook(["chunks"]),
  804. /** @type {SyncHook<[Iterable<Module>, Records]>} */
  805. recordModules: new SyncHook(["modules", "records"]),
  806. /** @type {SyncHook<[Iterable<Chunk>, Records]>} */
  807. recordChunks: new SyncHook(["chunks", "records"]),
  808. /** @type {SyncHook<[Iterable<Module>]>} */
  809. optimizeCodeGeneration: new SyncHook(["modules"]),
  810. /** @type {SyncHook<[]>} */
  811. beforeModuleHash: new SyncHook([]),
  812. /** @type {SyncHook<[]>} */
  813. afterModuleHash: new SyncHook([]),
  814. /** @type {SyncHook<[]>} */
  815. beforeCodeGeneration: new SyncHook([]),
  816. /** @type {SyncHook<[]>} */
  817. afterCodeGeneration: new SyncHook([]),
  818. /** @type {SyncHook<[]>} */
  819. beforeRuntimeRequirements: new SyncHook([]),
  820. /** @type {SyncHook<[]>} */
  821. afterRuntimeRequirements: new SyncHook([]),
  822. /** @type {SyncHook<[]>} */
  823. beforeHash: new SyncHook([]),
  824. /** @type {SyncHook<[Chunk]>} */
  825. contentHash: new SyncHook(["chunk"]),
  826. /** @type {SyncHook<[]>} */
  827. afterHash: new SyncHook([]),
  828. /** @type {SyncHook<[Records]>} */
  829. recordHash: new SyncHook(["records"]),
  830. /** @type {SyncHook<[Compilation, Records]>} */
  831. record: new SyncHook(["compilation", "records"]),
  832. /** @type {SyncHook<[]>} */
  833. beforeModuleAssets: new SyncHook([]),
  834. /** @type {SyncBailHook<[], boolean | void>} */
  835. shouldGenerateChunkAssets: new SyncBailHook([]),
  836. /** @type {SyncHook<[]>} */
  837. beforeChunkAssets: new SyncHook([]),
  838. // TODO webpack 6 remove
  839. /** @deprecated */
  840. additionalChunkAssets:
  841. /** @type {FakeHook<Pick<AsyncSeriesHook<[Chunks]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
  842. (
  843. createProcessAssetsHook(
  844. "additionalChunkAssets",
  845. Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
  846. () => [this.chunks],
  847. "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS"
  848. )
  849. ),
  850. // TODO webpack 6 deprecate
  851. /** @deprecated */
  852. additionalAssets:
  853. /** @type {FakeHook<Pick<AsyncSeriesHook<[]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
  854. (
  855. createProcessAssetsHook(
  856. "additionalAssets",
  857. Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
  858. () => []
  859. )
  860. ),
  861. // TODO webpack 6 remove
  862. /** @deprecated */
  863. optimizeChunkAssets:
  864. /** @type {FakeHook<Pick<AsyncSeriesHook<[Chunks]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
  865. (
  866. createProcessAssetsHook(
  867. "optimizeChunkAssets",
  868. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE,
  869. () => [this.chunks],
  870. "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS"
  871. )
  872. ),
  873. // TODO webpack 6 remove
  874. /** @deprecated */
  875. afterOptimizeChunkAssets:
  876. /** @type {FakeHook<Pick<AsyncSeriesHook<[Chunks]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
  877. (
  878. createProcessAssetsHook(
  879. "afterOptimizeChunkAssets",
  880. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1,
  881. () => [this.chunks],
  882. "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS"
  883. )
  884. ),
  885. // TODO webpack 6 deprecate
  886. /** @deprecated */
  887. optimizeAssets: processAssetsHook,
  888. // TODO webpack 6 deprecate
  889. /** @deprecated */
  890. afterOptimizeAssets: afterProcessAssetsHook,
  891. processAssets: processAssetsHook,
  892. afterProcessAssets: afterProcessAssetsHook,
  893. /** @type {AsyncSeriesHook<[CompilationAssets]>} */
  894. processAdditionalAssets: new AsyncSeriesHook(["assets"]),
  895. /** @type {SyncBailHook<[], boolean | void>} */
  896. needAdditionalSeal: new SyncBailHook([]),
  897. /** @type {AsyncSeriesHook<[]>} */
  898. afterSeal: new AsyncSeriesHook([]),
  899. /** @type {SyncWaterfallHook<[RenderManifestEntry[], RenderManifestOptions]>} */
  900. renderManifest: new SyncWaterfallHook(["result", "options"]),
  901. /** @type {SyncHook<[Hash]>} */
  902. fullHash: new SyncHook(["hash"]),
  903. /** @type {SyncHook<[Chunk, Hash, ChunkHashContext]>} */
  904. chunkHash: new SyncHook(["chunk", "chunkHash", "ChunkHashContext"]),
  905. /** @type {SyncHook<[Module, string]>} */
  906. moduleAsset: new SyncHook(["module", "filename"]),
  907. /** @type {SyncHook<[Chunk, string]>} */
  908. chunkAsset: new SyncHook(["chunk", "filename"]),
  909. /** @type {SyncWaterfallHook<[string, PathData, AssetInfo | undefined]>} */
  910. assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]),
  911. /** @type {SyncBailHook<[], boolean | void>} */
  912. needAdditionalPass: new SyncBailHook([]),
  913. /** @type {SyncHook<[Compiler, string, number]>} */
  914. childCompiler: new SyncHook([
  915. "childCompiler",
  916. "compilerName",
  917. "compilerIndex"
  918. ]),
  919. /** @type {SyncBailHook<[string, LogEntry], boolean | void>} */
  920. log: new SyncBailHook(["origin", "logEntry"]),
  921. /** @type {SyncWaterfallHook<[Error[]]>} */
  922. processWarnings: new SyncWaterfallHook(["warnings"]),
  923. /** @type {SyncWaterfallHook<[Error[]]>} */
  924. processErrors: new SyncWaterfallHook(["errors"]),
  925. /** @type {HookMap<SyncHook<[Partial<NormalizedStatsOptions>, CreateStatsOptionsContext]>>} */
  926. statsPreset: new HookMap(() => new SyncHook(["options", "context"])),
  927. /** @type {SyncHook<[Partial<NormalizedStatsOptions>, CreateStatsOptionsContext]>} */
  928. statsNormalize: new SyncHook(["options", "context"]),
  929. /** @type {SyncHook<[StatsFactory, NormalizedStatsOptions]>} */
  930. statsFactory: new SyncHook(["statsFactory", "options"]),
  931. /** @type {SyncHook<[StatsPrinter, NormalizedStatsOptions]>} */
  932. statsPrinter: new SyncHook(["statsPrinter", "options"]),
  933. get normalModuleLoader() {
  934. return getNormalModuleLoader();
  935. }
  936. });
  937. /** @type {string=} */
  938. this.name = undefined;
  939. /** @type {number | undefined} */
  940. this.startTime = undefined;
  941. /** @type {number | undefined} */
  942. this.endTime = undefined;
  943. /** @type {Compiler} */
  944. this.compiler = compiler;
  945. this.resolverFactory = compiler.resolverFactory;
  946. /** @type {InputFileSystem} */
  947. this.inputFileSystem =
  948. /** @type {InputFileSystem} */
  949. (compiler.inputFileSystem);
  950. this.fileSystemInfo = new FileSystemInfo(this.inputFileSystem, {
  951. unmanagedPaths: compiler.unmanagedPaths,
  952. managedPaths: compiler.managedPaths,
  953. immutablePaths: compiler.immutablePaths,
  954. logger: this.getLogger("webpack.FileSystemInfo"),
  955. hashFunction: compiler.options.output.hashFunction
  956. });
  957. if (compiler.fileTimestamps) {
  958. this.fileSystemInfo.addFileTimestamps(compiler.fileTimestamps, true);
  959. }
  960. if (compiler.contextTimestamps) {
  961. this.fileSystemInfo.addContextTimestamps(
  962. compiler.contextTimestamps,
  963. true
  964. );
  965. }
  966. /** @type {ValueCacheVersions} */
  967. this.valueCacheVersions = new Map();
  968. this.requestShortener = compiler.requestShortener;
  969. this.compilerPath = compiler.compilerPath;
  970. this.logger = this.getLogger("webpack.Compilation");
  971. const options = /** @type {WebpackOptions} */ (compiler.options);
  972. this.options = options;
  973. this.outputOptions =
  974. /** @type {OutputOptionsWithDefaults} */
  975. (options && options.output);
  976. /** @type {boolean} */
  977. this.bail = (options && options.bail) || false;
  978. /** @type {boolean} */
  979. this.profile = (options && options.profile) || false;
  980. this.params = params;
  981. this.mainTemplate = new MainTemplate(this.outputOptions, this);
  982. this.chunkTemplate = new ChunkTemplate(this.outputOptions, this);
  983. this.runtimeTemplate = new RuntimeTemplate(
  984. this,
  985. this.outputOptions,
  986. this.requestShortener
  987. );
  988. /** @type {ModuleTemplates} */
  989. this.moduleTemplates = {
  990. javascript: new ModuleTemplate(this.runtimeTemplate, this)
  991. };
  992. defineRemovedModuleTemplates(this.moduleTemplates);
  993. // We need to think how implement types here
  994. /** @type {ModuleMemCaches | undefined} */
  995. this.moduleMemCaches = undefined;
  996. /** @type {ModuleMemCaches | undefined} */
  997. this.moduleMemCaches2 = undefined;
  998. /** @type {ModuleGraph} */
  999. this.moduleGraph = new ModuleGraph();
  1000. /** @type {ChunkGraph} */
  1001. this.chunkGraph = new ChunkGraph(
  1002. this.moduleGraph,
  1003. this.outputOptions.hashFunction
  1004. );
  1005. /** @type {CodeGenerationResults | undefined} */
  1006. this.codeGenerationResults = undefined;
  1007. /** @type {AsyncQueue<Module, Module, Module>} */
  1008. this.processDependenciesQueue = new AsyncQueue({
  1009. name: "processDependencies",
  1010. parallelism: options.parallelism || 100,
  1011. processor: this._processModuleDependencies.bind(this)
  1012. });
  1013. /** @type {AsyncQueue<Module, string, Module>} */
  1014. this.addModuleQueue = new AsyncQueue({
  1015. name: "addModule",
  1016. parent: this.processDependenciesQueue,
  1017. getKey: (module) => module.identifier(),
  1018. processor: this._addModule.bind(this)
  1019. });
  1020. /** @type {AsyncQueue<FactorizeModuleOptions, string, Module | ModuleFactoryResult>} */
  1021. this.factorizeQueue = new AsyncQueue({
  1022. name: "factorize",
  1023. parent: this.addModuleQueue,
  1024. processor: this._factorizeModule.bind(this)
  1025. });
  1026. /** @type {AsyncQueue<Module, Module, Module>} */
  1027. this.buildQueue = new AsyncQueue({
  1028. name: "build",
  1029. parent: this.factorizeQueue,
  1030. processor: this._buildModule.bind(this)
  1031. });
  1032. /** @type {AsyncQueue<Module, Module, Module>} */
  1033. this.rebuildQueue = new AsyncQueue({
  1034. name: "rebuild",
  1035. parallelism: options.parallelism || 100,
  1036. processor: this._rebuildModule.bind(this)
  1037. });
  1038. /**
  1039. * Modules in value are building during the build of Module in key.
  1040. * Means value blocking key from finishing.
  1041. * Needed to detect build cycles.
  1042. * @type {WeakMap<Module, Set<Module>>}
  1043. */
  1044. this.creatingModuleDuringBuild = new WeakMap();
  1045. /** @type {Map<Exclude<ChunkName, null>, EntryData>} */
  1046. this.entries = new Map();
  1047. /** @type {EntryData} */
  1048. this.globalEntry = {
  1049. dependencies: [],
  1050. includeDependencies: [],
  1051. options: {
  1052. name: undefined
  1053. }
  1054. };
  1055. /** @type {Map<string, Entrypoint>} */
  1056. this.entrypoints = new Map();
  1057. /** @type {Entrypoint[]} */
  1058. this.asyncEntrypoints = [];
  1059. /** @type {Chunks} */
  1060. this.chunks = new Set();
  1061. /** @type {ChunkGroup[]} */
  1062. this.chunkGroups = [];
  1063. /** @type {Map<string, ChunkGroup>} */
  1064. this.namedChunkGroups = new Map();
  1065. /** @type {Map<string, Chunk>} */
  1066. this.namedChunks = new Map();
  1067. /** @type {Set<Module>} */
  1068. this.modules = new Set();
  1069. if (this._backCompat) {
  1070. arrayToSetDeprecation(this.chunks, "Compilation.chunks");
  1071. arrayToSetDeprecation(this.modules, "Compilation.modules");
  1072. }
  1073. /**
  1074. * @private
  1075. * @type {Map<string, Module>}
  1076. */
  1077. this._modules = new Map();
  1078. /** @type {Records | null} */
  1079. this.records = null;
  1080. /** @type {string[]} */
  1081. this.additionalChunkAssets = [];
  1082. /** @type {CompilationAssets} */
  1083. this.assets = {};
  1084. /** @type {Map<string, AssetInfo>} */
  1085. this.assetsInfo = new Map();
  1086. /** @type {Map<string, Map<string, Set<string>>>} */
  1087. this._assetsRelatedIn = new Map();
  1088. /** @type {Error[]} */
  1089. this.errors = [];
  1090. /** @type {Error[]} */
  1091. this.warnings = [];
  1092. /** @type {Compilation[]} */
  1093. this.children = [];
  1094. /** @type {Map<string, LogEntry[]>} */
  1095. this.logging = new Map();
  1096. /** @type {Map<DependencyConstructor, ModuleFactory>} */
  1097. this.dependencyFactories = new Map();
  1098. /** @type {DependencyTemplates} */
  1099. this.dependencyTemplates = new DependencyTemplates(
  1100. this.outputOptions.hashFunction
  1101. );
  1102. /** @type {Record<string, number>} */
  1103. this.childrenCounters = {};
  1104. /** @type {Set<number> | null} */
  1105. this.usedChunkIds = null;
  1106. /** @type {Set<number> | null} */
  1107. this.usedModuleIds = null;
  1108. /** @type {boolean} */
  1109. this.needAdditionalPass = false;
  1110. /** @type {Set<ModuleWithRestoreFromUnsafeCache>} */
  1111. this._restoredUnsafeCacheModuleEntries = new Set();
  1112. /** @type {Map<string, ModuleWithRestoreFromUnsafeCache>} */
  1113. this._restoredUnsafeCacheEntries = new Map();
  1114. /** @type {WeakSet<Module>} */
  1115. this.builtModules = new WeakSet();
  1116. /** @type {WeakSet<Module>} */
  1117. this.codeGeneratedModules = new WeakSet();
  1118. /** @type {WeakSet<Module>} */
  1119. this.buildTimeExecutedModules = new WeakSet();
  1120. /** @type {Set<string>} */
  1121. this.emittedAssets = new Set();
  1122. /** @type {Set<string>} */
  1123. this.comparedForEmitAssets = new Set();
  1124. /** @type {FileSystemDependencies} */
  1125. this.fileDependencies = new LazySet();
  1126. /** @type {FileSystemDependencies} */
  1127. this.contextDependencies = new LazySet();
  1128. /** @type {FileSystemDependencies} */
  1129. this.missingDependencies = new LazySet();
  1130. /** @type {FileSystemDependencies} */
  1131. this.buildDependencies = new LazySet();
  1132. // TODO webpack 6 remove
  1133. this.compilationDependencies = {
  1134. add: util.deprecate(
  1135. /**
  1136. * @param {string} item item
  1137. * @returns {FileSystemDependencies} file dependencies
  1138. */
  1139. (item) => this.fileDependencies.add(item),
  1140. "Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)",
  1141. "DEP_WEBPACK_COMPILATION_COMPILATION_DEPENDENCIES"
  1142. )
  1143. };
  1144. this._modulesCache = this.getCache("Compilation/modules");
  1145. this._assetsCache = this.getCache("Compilation/assets");
  1146. this._codeGenerationCache = this.getCache("Compilation/codeGeneration");
  1147. const unsafeCache = options.module.unsafeCache;
  1148. this._unsafeCache = Boolean(unsafeCache);
  1149. this._unsafeCachePredicate =
  1150. typeof unsafeCache === "function" ? unsafeCache : () => true;
  1151. }
  1152. getStats() {
  1153. return new Stats(this);
  1154. }
  1155. /**
  1156. * @param {string | boolean | StatsOptions | undefined} optionsOrPreset stats option value
  1157. * @param {CreateStatsOptionsContext=} context context
  1158. * @returns {NormalizedStatsOptions} normalized options
  1159. */
  1160. createStatsOptions(optionsOrPreset, context = {}) {
  1161. if (typeof optionsOrPreset === "boolean") {
  1162. optionsOrPreset = {
  1163. preset: optionsOrPreset === false ? "none" : "normal"
  1164. };
  1165. } else if (typeof optionsOrPreset === "string") {
  1166. optionsOrPreset = { preset: optionsOrPreset };
  1167. }
  1168. if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) {
  1169. // We use this method of shallow cloning this object to include
  1170. // properties in the prototype chain
  1171. /** @type {Partial<NormalizedStatsOptions>} */
  1172. const options = {};
  1173. for (const key in optionsOrPreset) {
  1174. options[key] = optionsOrPreset[/** @type {keyof StatsOptions} */ (key)];
  1175. }
  1176. if (options.preset !== undefined) {
  1177. this.hooks.statsPreset.for(options.preset).call(options, context);
  1178. }
  1179. this.hooks.statsNormalize.call(options, context);
  1180. return /** @type {NormalizedStatsOptions} */ (options);
  1181. }
  1182. /** @type {Partial<NormalizedStatsOptions>} */
  1183. const options = {};
  1184. this.hooks.statsNormalize.call(options, context);
  1185. return /** @type {NormalizedStatsOptions} */ (options);
  1186. }
  1187. /**
  1188. * @param {NormalizedStatsOptions} options options
  1189. * @returns {StatsFactory} the stats factory
  1190. */
  1191. createStatsFactory(options) {
  1192. const statsFactory = new StatsFactory();
  1193. this.hooks.statsFactory.call(statsFactory, options);
  1194. return statsFactory;
  1195. }
  1196. /**
  1197. * @param {NormalizedStatsOptions} options options
  1198. * @returns {StatsPrinter} the stats printer
  1199. */
  1200. createStatsPrinter(options) {
  1201. const statsPrinter = new StatsPrinter();
  1202. this.hooks.statsPrinter.call(statsPrinter, options);
  1203. return statsPrinter;
  1204. }
  1205. /**
  1206. * @param {string} name cache name
  1207. * @returns {CacheFacade} the cache facade instance
  1208. */
  1209. getCache(name) {
  1210. return this.compiler.getCache(name);
  1211. }
  1212. /**
  1213. * @param {string | (() => string)} name name of the logger, or function called once to get the logger name
  1214. * @returns {Logger} a logger with that name
  1215. */
  1216. getLogger(name) {
  1217. if (!name) {
  1218. throw new TypeError("Compilation.getLogger(name) called without a name");
  1219. }
  1220. /** @type {LogEntry[] | undefined} */
  1221. let logEntries;
  1222. return new Logger(
  1223. (type, args) => {
  1224. if (typeof name === "function") {
  1225. name = name();
  1226. if (!name) {
  1227. throw new TypeError(
  1228. "Compilation.getLogger(name) called with a function not returning a name"
  1229. );
  1230. }
  1231. }
  1232. let trace;
  1233. switch (type) {
  1234. case LogType.warn:
  1235. case LogType.error:
  1236. case LogType.trace:
  1237. trace = ErrorHelpers.cutOffLoaderExecution(
  1238. /** @type {string} */ (new Error("Trace").stack)
  1239. )
  1240. .split("\n")
  1241. .slice(3);
  1242. break;
  1243. }
  1244. /** @type {LogEntry} */
  1245. const logEntry = {
  1246. time: Date.now(),
  1247. type,
  1248. args,
  1249. trace
  1250. };
  1251. /* eslint-disable no-console */
  1252. if (this.hooks.log.call(name, logEntry) === undefined) {
  1253. if (
  1254. logEntry.type === LogType.profileEnd &&
  1255. typeof console.profileEnd === "function"
  1256. ) {
  1257. console.profileEnd(
  1258. `[${name}] ${/** @type {NonNullable<LogEntry["args"]>} */ (logEntry.args)[0]}`
  1259. );
  1260. }
  1261. if (logEntries === undefined) {
  1262. logEntries = this.logging.get(name);
  1263. if (logEntries === undefined) {
  1264. logEntries = [];
  1265. this.logging.set(name, logEntries);
  1266. }
  1267. }
  1268. logEntries.push(logEntry);
  1269. if (
  1270. logEntry.type === LogType.profile &&
  1271. typeof console.profile === "function"
  1272. ) {
  1273. console.profile(
  1274. `[${name}] ${
  1275. /** @type {NonNullable<LogEntry["args"]>} */
  1276. (logEntry.args)[0]
  1277. }`
  1278. );
  1279. }
  1280. /* eslint-enable no-console */
  1281. }
  1282. },
  1283. (childName) => {
  1284. if (typeof name === "function") {
  1285. if (typeof childName === "function") {
  1286. return this.getLogger(() => {
  1287. if (typeof name === "function") {
  1288. name = name();
  1289. if (!name) {
  1290. throw new TypeError(
  1291. "Compilation.getLogger(name) called with a function not returning a name"
  1292. );
  1293. }
  1294. }
  1295. if (typeof childName === "function") {
  1296. childName = childName();
  1297. if (!childName) {
  1298. throw new TypeError(
  1299. "Logger.getChildLogger(name) called with a function not returning a name"
  1300. );
  1301. }
  1302. }
  1303. return `${name}/${childName}`;
  1304. });
  1305. }
  1306. return this.getLogger(() => {
  1307. if (typeof name === "function") {
  1308. name = name();
  1309. if (!name) {
  1310. throw new TypeError(
  1311. "Compilation.getLogger(name) called with a function not returning a name"
  1312. );
  1313. }
  1314. }
  1315. return `${name}/${childName}`;
  1316. });
  1317. }
  1318. if (typeof childName === "function") {
  1319. return this.getLogger(() => {
  1320. if (typeof childName === "function") {
  1321. childName = childName();
  1322. if (!childName) {
  1323. throw new TypeError(
  1324. "Logger.getChildLogger(name) called with a function not returning a name"
  1325. );
  1326. }
  1327. }
  1328. return `${name}/${childName}`;
  1329. });
  1330. }
  1331. return this.getLogger(`${name}/${childName}`);
  1332. }
  1333. );
  1334. }
  1335. /**
  1336. * @param {Module} module module to be added that was created
  1337. * @param {ModuleCallback} callback returns the module in the compilation,
  1338. * it could be the passed one (if new), or an already existing in the compilation
  1339. * @returns {void}
  1340. */
  1341. addModule(module, callback) {
  1342. this.addModuleQueue.add(module, callback);
  1343. }
  1344. /**
  1345. * @param {Module} module module to be added that was created
  1346. * @param {ModuleCallback} callback returns the module in the compilation,
  1347. * it could be the passed one (if new), or an already existing in the compilation
  1348. * @returns {void}
  1349. */
  1350. _addModule(module, callback) {
  1351. const identifier = module.identifier();
  1352. const alreadyAddedModule = this._modules.get(identifier);
  1353. if (alreadyAddedModule) {
  1354. return callback(null, alreadyAddedModule);
  1355. }
  1356. const currentProfile = this.profile
  1357. ? this.moduleGraph.getProfile(module)
  1358. : undefined;
  1359. if (currentProfile !== undefined) {
  1360. currentProfile.markRestoringStart();
  1361. }
  1362. this._modulesCache.get(identifier, null, (err, cacheModule) => {
  1363. if (err) return callback(new ModuleRestoreError(module, err));
  1364. if (currentProfile !== undefined) {
  1365. currentProfile.markRestoringEnd();
  1366. currentProfile.markIntegrationStart();
  1367. }
  1368. if (cacheModule) {
  1369. cacheModule.updateCacheModule(module);
  1370. module = cacheModule;
  1371. }
  1372. this._modules.set(identifier, module);
  1373. this.modules.add(module);
  1374. if (this._backCompat) {
  1375. ModuleGraph.setModuleGraphForModule(module, this.moduleGraph);
  1376. }
  1377. if (currentProfile !== undefined) {
  1378. currentProfile.markIntegrationEnd();
  1379. }
  1380. callback(null, module);
  1381. });
  1382. }
  1383. /**
  1384. * Fetches a module from a compilation by its identifier
  1385. * @param {Module} module the module provided
  1386. * @returns {Module} the module requested
  1387. */
  1388. getModule(module) {
  1389. const identifier = module.identifier();
  1390. return /** @type {Module} */ (this._modules.get(identifier));
  1391. }
  1392. /**
  1393. * Attempts to search for a module by its identifier
  1394. * @param {string} identifier identifier (usually path) for module
  1395. * @returns {Module|undefined} attempt to search for module and return it, else undefined
  1396. */
  1397. findModule(identifier) {
  1398. return this._modules.get(identifier);
  1399. }
  1400. /**
  1401. * Schedules a build of the module object
  1402. * @param {Module} module module to be built
  1403. * @param {ModuleCallback} callback the callback
  1404. * @returns {void}
  1405. */
  1406. buildModule(module, callback) {
  1407. this.buildQueue.add(module, callback);
  1408. }
  1409. /**
  1410. * Builds the module object
  1411. * @param {Module} module module to be built
  1412. * @param {ModuleCallback} callback the callback
  1413. * @returns {void}
  1414. */
  1415. _buildModule(module, callback) {
  1416. const currentProfile = this.profile
  1417. ? this.moduleGraph.getProfile(module)
  1418. : undefined;
  1419. if (currentProfile !== undefined) {
  1420. currentProfile.markBuildingStart();
  1421. }
  1422. module.needBuild(
  1423. {
  1424. compilation: this,
  1425. fileSystemInfo: this.fileSystemInfo,
  1426. valueCacheVersions: this.valueCacheVersions
  1427. },
  1428. (err, needBuild) => {
  1429. if (err) return callback(err);
  1430. if (!needBuild) {
  1431. if (currentProfile !== undefined) {
  1432. currentProfile.markBuildingEnd();
  1433. }
  1434. this.hooks.stillValidModule.call(module);
  1435. return callback();
  1436. }
  1437. this.hooks.buildModule.call(module);
  1438. this.builtModules.add(module);
  1439. module.build(
  1440. this.options,
  1441. this,
  1442. this.resolverFactory.get("normal", module.resolveOptions),
  1443. /** @type {InputFileSystem} */
  1444. (this.inputFileSystem),
  1445. (err) => {
  1446. if (currentProfile !== undefined) {
  1447. currentProfile.markBuildingEnd();
  1448. }
  1449. if (err) {
  1450. this.hooks.failedModule.call(module, err);
  1451. return callback(err);
  1452. }
  1453. if (currentProfile !== undefined) {
  1454. currentProfile.markStoringStart();
  1455. }
  1456. this._modulesCache.store(
  1457. module.identifier(),
  1458. null,
  1459. module,
  1460. (err) => {
  1461. if (currentProfile !== undefined) {
  1462. currentProfile.markStoringEnd();
  1463. }
  1464. if (err) {
  1465. this.hooks.failedModule.call(
  1466. module,
  1467. /** @type {WebpackError} */ (err)
  1468. );
  1469. return callback(new ModuleStoreError(module, err));
  1470. }
  1471. this.hooks.succeedModule.call(module);
  1472. return callback();
  1473. }
  1474. );
  1475. }
  1476. );
  1477. }
  1478. );
  1479. }
  1480. /**
  1481. * @param {Module} module to be processed for deps
  1482. * @param {ModuleCallback} callback callback to be triggered
  1483. * @returns {void}
  1484. */
  1485. processModuleDependencies(module, callback) {
  1486. this.processDependenciesQueue.add(module, callback);
  1487. }
  1488. /**
  1489. * @param {Module} module to be processed for deps
  1490. * @returns {void}
  1491. */
  1492. processModuleDependenciesNonRecursive(module) {
  1493. /**
  1494. * @param {DependenciesBlock} block block
  1495. */
  1496. const processDependenciesBlock = (block) => {
  1497. if (block.dependencies) {
  1498. let i = 0;
  1499. for (const dep of block.dependencies) {
  1500. this.moduleGraph.setParents(dep, block, module, i++);
  1501. }
  1502. }
  1503. if (block.blocks) {
  1504. for (const b of block.blocks) processDependenciesBlock(b);
  1505. }
  1506. };
  1507. processDependenciesBlock(module);
  1508. }
  1509. /**
  1510. * @param {Module} module to be processed for deps
  1511. * @param {ModuleCallback} callback callback to be triggered
  1512. * @returns {void}
  1513. */
  1514. _processModuleDependencies(module, callback) {
  1515. /** @type {{ factory: ModuleFactory, dependencies: Dependency[], context: string | undefined, originModule: Module | null }[]} */
  1516. const sortedDependencies = [];
  1517. /** @type {boolean} */
  1518. const hasLowPriorityDependencies = module.dependencies.some(
  1519. Dependency.isLowPriorityDependency
  1520. );
  1521. /** @type {DependenciesBlock} */
  1522. let currentBlock;
  1523. /** @type {Map<ModuleFactory, Map<string, Dependency[]>>} */
  1524. let dependencies;
  1525. /** @type {DependencyConstructor} */
  1526. let factoryCacheKey;
  1527. /** @type {ModuleFactory} */
  1528. let factoryCacheKey2;
  1529. /** @typedef {Map<string, Dependency[]>} FactoryCacheValue */
  1530. /** @type {FactoryCacheValue | undefined} */
  1531. let factoryCacheValue;
  1532. /** @type {string} */
  1533. let listCacheKey1;
  1534. /** @type {string} */
  1535. let listCacheKey2;
  1536. /** @type {Dependency[]} */
  1537. let listCacheValue;
  1538. let inProgressSorting = 1;
  1539. let inProgressTransitive = 1;
  1540. /**
  1541. * @param {WebpackError=} err error
  1542. * @returns {void}
  1543. */
  1544. const onDependenciesSorted = (err) => {
  1545. if (err) return callback(err);
  1546. // early exit without changing parallelism back and forth
  1547. if (sortedDependencies.length === 0 && inProgressTransitive === 1) {
  1548. return callback();
  1549. }
  1550. // This is nested so we need to allow one additional task
  1551. this.processDependenciesQueue.increaseParallelism();
  1552. for (const item of sortedDependencies) {
  1553. inProgressTransitive++;
  1554. // eslint-disable-next-line no-loop-func
  1555. this.handleModuleCreation(item, (err) => {
  1556. // In V8, the Error objects keep a reference to the functions on the stack. These warnings &
  1557. // errors are created inside closures that keep a reference to the Compilation, so errors are
  1558. // leaking the Compilation object.
  1559. if (err && this.bail) {
  1560. if (inProgressTransitive <= 0) return;
  1561. inProgressTransitive = -1;
  1562. // eslint-disable-next-line no-self-assign
  1563. err.stack = err.stack;
  1564. onTransitiveTasksFinished(err);
  1565. return;
  1566. }
  1567. if (--inProgressTransitive === 0) onTransitiveTasksFinished();
  1568. });
  1569. }
  1570. if (--inProgressTransitive === 0) onTransitiveTasksFinished();
  1571. };
  1572. /**
  1573. * @param {WebpackError=} err error
  1574. * @returns {void}
  1575. */
  1576. const onTransitiveTasksFinished = (err) => {
  1577. if (err) return callback(err);
  1578. this.processDependenciesQueue.decreaseParallelism();
  1579. return callback();
  1580. };
  1581. /**
  1582. * @param {Dependency} dep dependency
  1583. * @param {number} index index in block
  1584. * @returns {void}
  1585. */
  1586. const processDependency = (dep, index) => {
  1587. this.moduleGraph.setParents(dep, currentBlock, module, index);
  1588. if (this._unsafeCache) {
  1589. try {
  1590. const unsafeCachedModule = unsafeCacheDependencies.get(dep);
  1591. if (unsafeCachedModule === null) return;
  1592. if (unsafeCachedModule !== undefined) {
  1593. if (
  1594. this._restoredUnsafeCacheModuleEntries.has(unsafeCachedModule)
  1595. ) {
  1596. this._handleExistingModuleFromUnsafeCache(
  1597. module,
  1598. dep,
  1599. unsafeCachedModule
  1600. );
  1601. return;
  1602. }
  1603. const identifier = unsafeCachedModule.identifier();
  1604. const cachedModule =
  1605. this._restoredUnsafeCacheEntries.get(identifier);
  1606. if (cachedModule !== undefined) {
  1607. // update unsafe cache to new module
  1608. unsafeCacheDependencies.set(dep, cachedModule);
  1609. this._handleExistingModuleFromUnsafeCache(
  1610. module,
  1611. dep,
  1612. cachedModule
  1613. );
  1614. return;
  1615. }
  1616. inProgressSorting++;
  1617. this._modulesCache.get(identifier, null, (err, cachedModule) => {
  1618. if (err) {
  1619. if (inProgressSorting <= 0) return;
  1620. inProgressSorting = -1;
  1621. onDependenciesSorted(/** @type {WebpackError} */ (err));
  1622. return;
  1623. }
  1624. try {
  1625. if (!this._restoredUnsafeCacheEntries.has(identifier)) {
  1626. const data = unsafeCacheData.get(cachedModule);
  1627. if (data === undefined) {
  1628. processDependencyForResolving(dep);
  1629. if (--inProgressSorting === 0) onDependenciesSorted();
  1630. return;
  1631. }
  1632. if (cachedModule !== unsafeCachedModule) {
  1633. unsafeCacheDependencies.set(dep, cachedModule);
  1634. }
  1635. cachedModule.restoreFromUnsafeCache(
  1636. data,
  1637. this.params.normalModuleFactory,
  1638. this.params
  1639. );
  1640. this._restoredUnsafeCacheEntries.set(
  1641. identifier,
  1642. cachedModule
  1643. );
  1644. this._restoredUnsafeCacheModuleEntries.add(cachedModule);
  1645. if (!this.modules.has(cachedModule)) {
  1646. inProgressTransitive++;
  1647. this._handleNewModuleFromUnsafeCache(
  1648. module,
  1649. dep,
  1650. cachedModule,
  1651. (err) => {
  1652. if (err) {
  1653. if (inProgressTransitive <= 0) return;
  1654. inProgressTransitive = -1;
  1655. onTransitiveTasksFinished(err);
  1656. }
  1657. if (--inProgressTransitive === 0) {
  1658. return onTransitiveTasksFinished();
  1659. }
  1660. }
  1661. );
  1662. if (--inProgressSorting === 0) onDependenciesSorted();
  1663. return;
  1664. }
  1665. }
  1666. if (unsafeCachedModule !== cachedModule) {
  1667. unsafeCacheDependencies.set(dep, cachedModule);
  1668. }
  1669. this._handleExistingModuleFromUnsafeCache(
  1670. module,
  1671. dep,
  1672. cachedModule
  1673. ); // a3
  1674. } catch (err) {
  1675. if (inProgressSorting <= 0) return;
  1676. inProgressSorting = -1;
  1677. onDependenciesSorted(/** @type {WebpackError} */ (err));
  1678. return;
  1679. }
  1680. if (--inProgressSorting === 0) onDependenciesSorted();
  1681. });
  1682. return;
  1683. }
  1684. } catch (err) {
  1685. // eslint-disable-next-line no-console
  1686. console.error(err);
  1687. }
  1688. }
  1689. processDependencyForResolving(dep);
  1690. };
  1691. /**
  1692. * @param {Dependency} dep dependency
  1693. * @returns {void}
  1694. */
  1695. const processDependencyForResolving = (dep) => {
  1696. const resourceIdent = dep.getResourceIdentifier();
  1697. if (resourceIdent !== undefined && resourceIdent !== null) {
  1698. const category = dep.category;
  1699. const constructor =
  1700. /** @type {DependencyConstructor} */
  1701. (dep.constructor);
  1702. if (factoryCacheKey === constructor) {
  1703. // Fast path 1: same constructor as prev item
  1704. if (listCacheKey1 === category && listCacheKey2 === resourceIdent) {
  1705. // Super fast path 1: also same resource
  1706. listCacheValue.push(dep);
  1707. return;
  1708. }
  1709. } else {
  1710. const factory = this.dependencyFactories.get(constructor);
  1711. if (factory === undefined) {
  1712. throw new Error(
  1713. `No module factory available for dependency type: ${constructor.name}`
  1714. );
  1715. }
  1716. if (factoryCacheKey2 === factory) {
  1717. // Fast path 2: same factory as prev item
  1718. factoryCacheKey = constructor;
  1719. if (listCacheKey1 === category && listCacheKey2 === resourceIdent) {
  1720. // Super fast path 2: also same resource
  1721. listCacheValue.push(dep);
  1722. return;
  1723. }
  1724. } else {
  1725. // Slow path
  1726. if (factoryCacheKey2 !== undefined) {
  1727. // Archive last cache entry
  1728. if (dependencies === undefined) dependencies = new Map();
  1729. dependencies.set(
  1730. factoryCacheKey2,
  1731. /** @type {FactoryCacheValue} */ (factoryCacheValue)
  1732. );
  1733. factoryCacheValue = dependencies.get(factory);
  1734. if (factoryCacheValue === undefined) {
  1735. factoryCacheValue = new Map();
  1736. }
  1737. } else {
  1738. factoryCacheValue = new Map();
  1739. }
  1740. factoryCacheKey = constructor;
  1741. factoryCacheKey2 = factory;
  1742. }
  1743. }
  1744. // Here webpack is using heuristic that assumes
  1745. // mostly esm dependencies would be used
  1746. // so we don't allocate extra string for them
  1747. const cacheKey =
  1748. category === esmDependencyCategory
  1749. ? resourceIdent
  1750. : `${category}${resourceIdent}`;
  1751. let list = /** @type {FactoryCacheValue} */ (factoryCacheValue).get(
  1752. cacheKey
  1753. );
  1754. if (list === undefined) {
  1755. /** @type {FactoryCacheValue} */
  1756. (factoryCacheValue).set(cacheKey, (list = []));
  1757. const newItem = {
  1758. factory: factoryCacheKey2,
  1759. dependencies: list,
  1760. context: dep.getContext(),
  1761. originModule: module
  1762. };
  1763. if (hasLowPriorityDependencies) {
  1764. let insertIndex = sortedDependencies.length;
  1765. while (insertIndex > 0) {
  1766. const item = sortedDependencies[insertIndex - 1];
  1767. const isAllLowPriorityDependencies = item.dependencies.every(
  1768. Dependency.isLowPriorityDependency
  1769. );
  1770. if (isAllLowPriorityDependencies) {
  1771. insertIndex--;
  1772. } else {
  1773. break;
  1774. }
  1775. }
  1776. sortedDependencies.splice(insertIndex, 0, newItem);
  1777. } else {
  1778. sortedDependencies.push(newItem);
  1779. }
  1780. }
  1781. list.push(dep);
  1782. listCacheKey1 = category;
  1783. listCacheKey2 = resourceIdent;
  1784. listCacheValue = list;
  1785. }
  1786. };
  1787. try {
  1788. /** @type {DependenciesBlock[]} */
  1789. const queue = [module];
  1790. do {
  1791. const block = /** @type {DependenciesBlock} */ (queue.pop());
  1792. if (block.dependencies) {
  1793. currentBlock = block;
  1794. let i = 0;
  1795. for (const dep of block.dependencies) processDependency(dep, i++);
  1796. }
  1797. if (block.blocks) {
  1798. for (const b of block.blocks) queue.push(b);
  1799. }
  1800. } while (queue.length !== 0);
  1801. } catch (err) {
  1802. return callback(/** @type {WebpackError} */ (err));
  1803. }
  1804. if (--inProgressSorting === 0) onDependenciesSorted();
  1805. }
  1806. /**
  1807. * @private
  1808. * @param {Module} originModule original module
  1809. * @param {Dependency} dependency dependency
  1810. * @param {Module} module cached module
  1811. * @param {Callback} callback callback
  1812. */
  1813. _handleNewModuleFromUnsafeCache(originModule, dependency, module, callback) {
  1814. const moduleGraph = this.moduleGraph;
  1815. moduleGraph.setResolvedModule(originModule, dependency, module);
  1816. moduleGraph.setIssuerIfUnset(
  1817. module,
  1818. originModule !== undefined ? originModule : null
  1819. );
  1820. this._modules.set(module.identifier(), module);
  1821. this.modules.add(module);
  1822. if (this._backCompat) {
  1823. ModuleGraph.setModuleGraphForModule(module, this.moduleGraph);
  1824. }
  1825. this._handleModuleBuildAndDependencies(
  1826. originModule,
  1827. module,
  1828. true,
  1829. false,
  1830. callback
  1831. );
  1832. }
  1833. /**
  1834. * @private
  1835. * @param {Module} originModule original modules
  1836. * @param {Dependency} dependency dependency
  1837. * @param {Module} module cached module
  1838. */
  1839. _handleExistingModuleFromUnsafeCache(originModule, dependency, module) {
  1840. const moduleGraph = this.moduleGraph;
  1841. moduleGraph.setResolvedModule(originModule, dependency, module);
  1842. }
  1843. /**
  1844. * @param {FactorizeModuleOptions} options options
  1845. * @param {ModuleOrModuleFactoryResultCallback} callback callback
  1846. * @returns {void}
  1847. */
  1848. _factorizeModule(
  1849. {
  1850. currentProfile,
  1851. factory,
  1852. dependencies,
  1853. originModule,
  1854. factoryResult,
  1855. contextInfo,
  1856. context
  1857. },
  1858. callback
  1859. ) {
  1860. if (currentProfile !== undefined) {
  1861. currentProfile.markFactoryStart();
  1862. }
  1863. factory.create(
  1864. {
  1865. contextInfo: {
  1866. issuer: originModule
  1867. ? /** @type {NameForCondition} */ (originModule.nameForCondition())
  1868. : "",
  1869. issuerLayer: originModule ? originModule.layer : null,
  1870. compiler: this.compiler.name,
  1871. ...contextInfo
  1872. },
  1873. resolveOptions: originModule ? originModule.resolveOptions : undefined,
  1874. context:
  1875. context ||
  1876. (originModule
  1877. ? /** @type {string} */ (originModule.context)
  1878. : this.compiler.context),
  1879. dependencies
  1880. },
  1881. (err, result) => {
  1882. if (result) {
  1883. // TODO webpack 6: remove
  1884. // For backward-compat
  1885. if (result.module === undefined && result instanceof Module) {
  1886. result = {
  1887. module: result
  1888. };
  1889. }
  1890. if (!factoryResult) {
  1891. const {
  1892. fileDependencies,
  1893. contextDependencies,
  1894. missingDependencies
  1895. } = result;
  1896. if (fileDependencies) {
  1897. this.fileDependencies.addAll(fileDependencies);
  1898. }
  1899. if (contextDependencies) {
  1900. this.contextDependencies.addAll(contextDependencies);
  1901. }
  1902. if (missingDependencies) {
  1903. this.missingDependencies.addAll(missingDependencies);
  1904. }
  1905. }
  1906. }
  1907. if (err) {
  1908. const notFoundError = new ModuleNotFoundError(
  1909. originModule,
  1910. err,
  1911. /** @type {DependencyLocation} */
  1912. (dependencies.map((d) => d.loc).find(Boolean))
  1913. );
  1914. return callback(notFoundError, factoryResult ? result : undefined);
  1915. }
  1916. if (!result) {
  1917. return callback();
  1918. }
  1919. if (currentProfile !== undefined) {
  1920. currentProfile.markFactoryEnd();
  1921. }
  1922. callback(null, factoryResult ? result : result.module);
  1923. }
  1924. );
  1925. }
  1926. /**
  1927. * @overload
  1928. * @param {FactorizeModuleOptions & { factoryResult?: false }} options options
  1929. * @param {ModuleCallback} callback callback
  1930. * @returns {void}
  1931. */
  1932. /**
  1933. * @overload
  1934. * @param {FactorizeModuleOptions & { factoryResult: true }} options options
  1935. * @param {ModuleFactoryResultCallback} callback callback
  1936. * @returns {void}
  1937. */
  1938. /**
  1939. * @param {FactorizeModuleOptions & { factoryResult?: false } | FactorizeModuleOptions & { factoryResult: true }} options options
  1940. * @param {ModuleCallback | ModuleFactoryResultCallback} callback callback
  1941. */
  1942. factorizeModule(options, callback) {
  1943. this.factorizeQueue.add(
  1944. options,
  1945. /** @type {ModuleOrModuleFactoryResultCallback} */
  1946. (callback)
  1947. );
  1948. }
  1949. /**
  1950. * @typedef {object} HandleModuleCreationOptions
  1951. * @property {ModuleFactory} factory
  1952. * @property {Dependency[]} dependencies
  1953. * @property {Module | null} originModule
  1954. * @property {Partial<ModuleFactoryCreateDataContextInfo>=} contextInfo
  1955. * @property {string=} context
  1956. * @property {boolean=} recursive recurse into dependencies of the created module
  1957. * @property {boolean=} connectOrigin connect the resolved module with the origin module
  1958. * @property {boolean=} checkCycle check the cycle dependencies of the created module
  1959. */
  1960. /**
  1961. * @param {HandleModuleCreationOptions} options options object
  1962. * @param {ModuleCallback} callback callback
  1963. * @returns {void}
  1964. */
  1965. handleModuleCreation(
  1966. {
  1967. factory,
  1968. dependencies,
  1969. originModule,
  1970. contextInfo,
  1971. context,
  1972. recursive = true,
  1973. connectOrigin = recursive,
  1974. checkCycle = !recursive
  1975. },
  1976. callback
  1977. ) {
  1978. const moduleGraph = this.moduleGraph;
  1979. const currentProfile = this.profile ? new ModuleProfile() : undefined;
  1980. this.factorizeModule(
  1981. {
  1982. currentProfile,
  1983. factory,
  1984. dependencies,
  1985. factoryResult: true,
  1986. originModule,
  1987. contextInfo,
  1988. context
  1989. },
  1990. (err, factoryResult) => {
  1991. const applyFactoryResultDependencies = () => {
  1992. const { fileDependencies, contextDependencies, missingDependencies } =
  1993. /** @type {ModuleFactoryResult} */ (factoryResult);
  1994. if (fileDependencies) {
  1995. this.fileDependencies.addAll(fileDependencies);
  1996. }
  1997. if (contextDependencies) {
  1998. this.contextDependencies.addAll(contextDependencies);
  1999. }
  2000. if (missingDependencies) {
  2001. this.missingDependencies.addAll(missingDependencies);
  2002. }
  2003. };
  2004. if (err) {
  2005. if (factoryResult) applyFactoryResultDependencies();
  2006. if (dependencies.every((d) => d.optional)) {
  2007. this.warnings.push(err);
  2008. return callback();
  2009. }
  2010. this.errors.push(err);
  2011. return callback(err);
  2012. }
  2013. const newModule =
  2014. /** @type {ModuleFactoryResult} */
  2015. (factoryResult).module;
  2016. if (!newModule) {
  2017. applyFactoryResultDependencies();
  2018. return callback();
  2019. }
  2020. if (currentProfile !== undefined) {
  2021. moduleGraph.setProfile(newModule, currentProfile);
  2022. }
  2023. this.addModule(newModule, (err, _module) => {
  2024. if (err) {
  2025. applyFactoryResultDependencies();
  2026. if (!err.module) {
  2027. err.module = _module;
  2028. }
  2029. this.errors.push(err);
  2030. return callback(err);
  2031. }
  2032. const module =
  2033. /** @type {ModuleWithRestoreFromUnsafeCache} */
  2034. (_module);
  2035. if (
  2036. this._unsafeCache &&
  2037. /** @type {ModuleFactoryResult} */
  2038. (factoryResult).cacheable !== false &&
  2039. module.restoreFromUnsafeCache &&
  2040. this._unsafeCachePredicate(module)
  2041. ) {
  2042. const unsafeCacheableModule =
  2043. /** @type {ModuleWithRestoreFromUnsafeCache} */
  2044. (module);
  2045. for (const dependency of dependencies) {
  2046. moduleGraph.setResolvedModule(
  2047. connectOrigin ? originModule : null,
  2048. dependency,
  2049. unsafeCacheableModule
  2050. );
  2051. unsafeCacheDependencies.set(dependency, unsafeCacheableModule);
  2052. }
  2053. if (!unsafeCacheData.has(unsafeCacheableModule)) {
  2054. unsafeCacheData.set(
  2055. unsafeCacheableModule,
  2056. unsafeCacheableModule.getUnsafeCacheData()
  2057. );
  2058. }
  2059. } else {
  2060. applyFactoryResultDependencies();
  2061. for (const dependency of dependencies) {
  2062. moduleGraph.setResolvedModule(
  2063. connectOrigin ? originModule : null,
  2064. dependency,
  2065. module
  2066. );
  2067. }
  2068. }
  2069. moduleGraph.setIssuerIfUnset(
  2070. module,
  2071. originModule !== undefined ? originModule : null
  2072. );
  2073. if (module !== newModule && currentProfile !== undefined) {
  2074. const otherProfile = moduleGraph.getProfile(module);
  2075. if (otherProfile !== undefined) {
  2076. currentProfile.mergeInto(otherProfile);
  2077. } else {
  2078. moduleGraph.setProfile(module, currentProfile);
  2079. }
  2080. }
  2081. this._handleModuleBuildAndDependencies(
  2082. originModule,
  2083. module,
  2084. recursive,
  2085. checkCycle,
  2086. callback
  2087. );
  2088. });
  2089. }
  2090. );
  2091. }
  2092. /**
  2093. * @private
  2094. * @param {Module | null} originModule original module
  2095. * @param {Module} module module
  2096. * @param {boolean} recursive true if make it recursive, otherwise false
  2097. * @param {boolean} checkCycle true if need to check cycle, otherwise false
  2098. * @param {ModuleCallback} callback callback
  2099. * @returns {void}
  2100. */
  2101. _handleModuleBuildAndDependencies(
  2102. originModule,
  2103. module,
  2104. recursive,
  2105. checkCycle,
  2106. callback
  2107. ) {
  2108. // Check for cycles when build is trigger inside another build
  2109. /** @type {Set<Module> | undefined} */
  2110. let creatingModuleDuringBuildSet;
  2111. if (
  2112. checkCycle &&
  2113. this.buildQueue.isProcessing(/** @type {Module} */ (originModule))
  2114. ) {
  2115. // Track build dependency
  2116. creatingModuleDuringBuildSet = this.creatingModuleDuringBuild.get(
  2117. /** @type {Module} */
  2118. (originModule)
  2119. );
  2120. if (creatingModuleDuringBuildSet === undefined) {
  2121. creatingModuleDuringBuildSet = new Set();
  2122. this.creatingModuleDuringBuild.set(
  2123. /** @type {Module} */
  2124. (originModule),
  2125. creatingModuleDuringBuildSet
  2126. );
  2127. }
  2128. creatingModuleDuringBuildSet.add(module);
  2129. // When building is blocked by another module
  2130. // search for a cycle, cancel the cycle by throwing
  2131. // an error (otherwise this would deadlock)
  2132. const blockReasons = this.creatingModuleDuringBuild.get(module);
  2133. if (blockReasons !== undefined) {
  2134. const set = new Set(blockReasons);
  2135. for (const item of set) {
  2136. const blockReasons = this.creatingModuleDuringBuild.get(item);
  2137. if (blockReasons !== undefined) {
  2138. for (const m of blockReasons) {
  2139. if (m === module) {
  2140. return callback(new BuildCycleError(module));
  2141. }
  2142. set.add(m);
  2143. }
  2144. }
  2145. }
  2146. }
  2147. }
  2148. this.buildModule(module, (err) => {
  2149. if (creatingModuleDuringBuildSet !== undefined) {
  2150. creatingModuleDuringBuildSet.delete(module);
  2151. }
  2152. if (err) {
  2153. if (!err.module) {
  2154. err.module = module;
  2155. }
  2156. this.errors.push(err);
  2157. return callback(err);
  2158. }
  2159. if (!recursive) {
  2160. this.processModuleDependenciesNonRecursive(module);
  2161. callback(null, module);
  2162. return;
  2163. }
  2164. // This avoids deadlocks for circular dependencies
  2165. if (this.processDependenciesQueue.isProcessing(module)) {
  2166. return callback(null, module);
  2167. }
  2168. this.processModuleDependencies(module, (err) => {
  2169. if (err) {
  2170. return callback(err);
  2171. }
  2172. callback(null, module);
  2173. });
  2174. });
  2175. }
  2176. /**
  2177. * @param {string} context context string path
  2178. * @param {Dependency} dependency dependency used to create Module chain
  2179. * @param {ModuleCallback} callback callback for when module chain is complete
  2180. * @returns {void} will throw if dependency instance is not a valid Dependency
  2181. */
  2182. addModuleChain(context, dependency, callback) {
  2183. return this.addModuleTree({ context, dependency }, callback);
  2184. }
  2185. /**
  2186. * @param {object} options options
  2187. * @param {string} options.context context string path
  2188. * @param {Dependency} options.dependency dependency used to create Module chain
  2189. * @param {Partial<ModuleFactoryCreateDataContextInfo>=} options.contextInfo additional context info for the root module
  2190. * @param {ModuleCallback} callback callback for when module chain is complete
  2191. * @returns {void} will throw if dependency instance is not a valid Dependency
  2192. */
  2193. addModuleTree({ context, dependency, contextInfo }, callback) {
  2194. if (
  2195. typeof dependency !== "object" ||
  2196. dependency === null ||
  2197. !dependency.constructor
  2198. ) {
  2199. return callback(
  2200. new WebpackError("Parameter 'dependency' must be a Dependency")
  2201. );
  2202. }
  2203. const Dep =
  2204. /** @type {DependencyConstructor} */
  2205. (dependency.constructor);
  2206. const moduleFactory = this.dependencyFactories.get(Dep);
  2207. if (!moduleFactory) {
  2208. return callback(
  2209. new WebpackError(
  2210. `No dependency factory available for this dependency type: ${dependency.constructor.name}`
  2211. )
  2212. );
  2213. }
  2214. this.handleModuleCreation(
  2215. {
  2216. factory: moduleFactory,
  2217. dependencies: [dependency],
  2218. originModule: null,
  2219. contextInfo,
  2220. context
  2221. },
  2222. (err, result) => {
  2223. if (err && this.bail) {
  2224. callback(err);
  2225. this.buildQueue.stop();
  2226. this.rebuildQueue.stop();
  2227. this.processDependenciesQueue.stop();
  2228. this.factorizeQueue.stop();
  2229. } else if (!err && result) {
  2230. callback(null, result);
  2231. } else {
  2232. callback();
  2233. }
  2234. }
  2235. );
  2236. }
  2237. /**
  2238. * @param {string} context context path for entry
  2239. * @param {Dependency} entry entry dependency that should be followed
  2240. * @param {string | EntryOptions} optionsOrName options or deprecated name of entry
  2241. * @param {ModuleCallback} callback callback function
  2242. * @returns {void} returns
  2243. */
  2244. addEntry(context, entry, optionsOrName, callback) {
  2245. // TODO webpack 6 remove
  2246. const options =
  2247. typeof optionsOrName === "object"
  2248. ? optionsOrName
  2249. : { name: optionsOrName };
  2250. this._addEntryItem(context, entry, "dependencies", options, callback);
  2251. }
  2252. /**
  2253. * @param {string} context context path for entry
  2254. * @param {Dependency} dependency dependency that should be followed
  2255. * @param {EntryOptions} options options
  2256. * @param {ModuleCallback} callback callback function
  2257. * @returns {void} returns
  2258. */
  2259. addInclude(context, dependency, options, callback) {
  2260. this._addEntryItem(
  2261. context,
  2262. dependency,
  2263. "includeDependencies",
  2264. options,
  2265. callback
  2266. );
  2267. }
  2268. /**
  2269. * @param {string} context context path for entry
  2270. * @param {Dependency} entry entry dependency that should be followed
  2271. * @param {"dependencies" | "includeDependencies"} target type of entry
  2272. * @param {EntryOptions} options options
  2273. * @param {ModuleCallback} callback callback function
  2274. * @returns {void} returns
  2275. */
  2276. _addEntryItem(context, entry, target, options, callback) {
  2277. const { name } = options;
  2278. /** @type {EntryData | undefined} */
  2279. let entryData =
  2280. name !== undefined ? this.entries.get(name) : this.globalEntry;
  2281. if (entryData === undefined) {
  2282. entryData = {
  2283. dependencies: [],
  2284. includeDependencies: [],
  2285. options: {
  2286. name: undefined,
  2287. ...options
  2288. }
  2289. };
  2290. entryData[target].push(entry);
  2291. this.entries.set(
  2292. /** @type {NonNullable<EntryOptions["name"]>} */
  2293. (name),
  2294. entryData
  2295. );
  2296. } else {
  2297. entryData[target].push(entry);
  2298. for (const key_ of Object.keys(options)) {
  2299. const key = /** @type {keyof EntryOptions} */ (key_);
  2300. if (options[key] === undefined) continue;
  2301. if (entryData.options[key] === options[key]) continue;
  2302. if (
  2303. Array.isArray(entryData.options[key]) &&
  2304. Array.isArray(options[key]) &&
  2305. arrayEquals(entryData.options[key], options[key])
  2306. ) {
  2307. continue;
  2308. }
  2309. if (entryData.options[key] === undefined) {
  2310. /** @type {EntryOptions[keyof EntryOptions]} */
  2311. (entryData.options[key]) = options[key];
  2312. } else {
  2313. return callback(
  2314. new WebpackError(
  2315. `Conflicting entry option ${key} = ${entryData.options[key]} vs ${options[key]}`
  2316. )
  2317. );
  2318. }
  2319. }
  2320. }
  2321. this.hooks.addEntry.call(entry, options);
  2322. this.addModuleTree(
  2323. {
  2324. context,
  2325. dependency: entry,
  2326. contextInfo: entryData.options.layer
  2327. ? { issuerLayer: entryData.options.layer }
  2328. : undefined
  2329. },
  2330. (err, module) => {
  2331. if (err) {
  2332. this.hooks.failedEntry.call(entry, options, err);
  2333. return callback(err);
  2334. }
  2335. this.hooks.succeedEntry.call(
  2336. entry,
  2337. options,
  2338. /** @type {Module} */
  2339. (module)
  2340. );
  2341. return callback(null, module);
  2342. }
  2343. );
  2344. }
  2345. /**
  2346. * @param {Module} module module to be rebuilt
  2347. * @param {ModuleCallback} callback callback when module finishes rebuilding
  2348. * @returns {void}
  2349. */
  2350. rebuildModule(module, callback) {
  2351. this.rebuildQueue.add(module, callback);
  2352. }
  2353. /**
  2354. * @param {Module} module module to be rebuilt
  2355. * @param {ModuleCallback} callback callback when module finishes rebuilding
  2356. * @returns {void}
  2357. */
  2358. _rebuildModule(module, callback) {
  2359. this.hooks.rebuildModule.call(module);
  2360. const oldDependencies = [...module.dependencies];
  2361. const oldBlocks = [...module.blocks];
  2362. module.invalidateBuild();
  2363. this.buildQueue.invalidate(module);
  2364. this.buildModule(module, (err) => {
  2365. if (err) {
  2366. return this.hooks.finishRebuildingModule.callAsync(module, (err2) => {
  2367. if (err2) {
  2368. callback(
  2369. makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule")
  2370. );
  2371. return;
  2372. }
  2373. callback(err);
  2374. });
  2375. }
  2376. this.processDependenciesQueue.invalidate(module);
  2377. this.moduleGraph.unfreeze();
  2378. this.processModuleDependencies(module, (err) => {
  2379. if (err) return callback(err);
  2380. this.removeReasonsOfDependencyBlock(module, {
  2381. dependencies: oldDependencies,
  2382. blocks: oldBlocks
  2383. });
  2384. this.hooks.finishRebuildingModule.callAsync(module, (err2) => {
  2385. if (err2) {
  2386. callback(
  2387. makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule")
  2388. );
  2389. return;
  2390. }
  2391. callback(null, module);
  2392. });
  2393. });
  2394. });
  2395. }
  2396. /**
  2397. * @private
  2398. * @param {Set<Module>} modules modules
  2399. */
  2400. _computeAffectedModules(modules) {
  2401. const moduleMemCacheCache = this.compiler.moduleMemCaches;
  2402. if (!moduleMemCacheCache) return;
  2403. if (!this.moduleMemCaches) {
  2404. this.moduleMemCaches = new Map();
  2405. this.moduleGraph.setModuleMemCaches(this.moduleMemCaches);
  2406. }
  2407. const { moduleGraph, moduleMemCaches } = this;
  2408. const affectedModules = new Set();
  2409. const infectedModules = new Set();
  2410. let statNew = 0;
  2411. let statChanged = 0;
  2412. let statUnchanged = 0;
  2413. let statReferencesChanged = 0;
  2414. let statWithoutBuild = 0;
  2415. /**
  2416. * @param {Module} module module
  2417. * @returns {WeakReferences | undefined} references
  2418. */
  2419. const computeReferences = (module) => {
  2420. /** @type {WeakReferences | undefined} */
  2421. let references;
  2422. for (const connection of moduleGraph.getOutgoingConnections(module)) {
  2423. const d = connection.dependency;
  2424. const m = connection.module;
  2425. if (!d || !m || unsafeCacheDependencies.has(d)) continue;
  2426. if (references === undefined) references = new WeakMap();
  2427. references.set(d, m);
  2428. }
  2429. return references;
  2430. };
  2431. /**
  2432. * @param {Module} module the module
  2433. * @param {WeakReferences | undefined} references references
  2434. * @returns {boolean} true, when the references differ
  2435. */
  2436. const compareReferences = (module, references) => {
  2437. if (references === undefined) return true;
  2438. for (const connection of moduleGraph.getOutgoingConnections(module)) {
  2439. const d = connection.dependency;
  2440. if (!d) continue;
  2441. const entry = references.get(d);
  2442. if (entry === undefined) continue;
  2443. if (entry !== connection.module) return false;
  2444. }
  2445. return true;
  2446. };
  2447. const modulesWithoutCache = new Set(modules);
  2448. for (const [module, cachedMemCache] of moduleMemCacheCache) {
  2449. if (modulesWithoutCache.has(module)) {
  2450. const buildInfo = module.buildInfo;
  2451. if (buildInfo) {
  2452. if (cachedMemCache.buildInfo !== buildInfo) {
  2453. // use a new one
  2454. /** @type {MemCache} */
  2455. const memCache = new WeakTupleMap();
  2456. moduleMemCaches.set(module, memCache);
  2457. affectedModules.add(module);
  2458. cachedMemCache.buildInfo = buildInfo;
  2459. cachedMemCache.references = computeReferences(module);
  2460. cachedMemCache.memCache = memCache;
  2461. statChanged++;
  2462. } else if (!compareReferences(module, cachedMemCache.references)) {
  2463. // use a new one
  2464. /** @type {MemCache} */
  2465. const memCache = new WeakTupleMap();
  2466. moduleMemCaches.set(module, memCache);
  2467. affectedModules.add(module);
  2468. cachedMemCache.references = computeReferences(module);
  2469. cachedMemCache.memCache = memCache;
  2470. statReferencesChanged++;
  2471. } else {
  2472. // keep the old mem cache
  2473. moduleMemCaches.set(module, cachedMemCache.memCache);
  2474. statUnchanged++;
  2475. }
  2476. } else {
  2477. infectedModules.add(module);
  2478. moduleMemCacheCache.delete(module);
  2479. statWithoutBuild++;
  2480. }
  2481. modulesWithoutCache.delete(module);
  2482. } else {
  2483. moduleMemCacheCache.delete(module);
  2484. }
  2485. }
  2486. for (const module of modulesWithoutCache) {
  2487. const buildInfo = module.buildInfo;
  2488. if (buildInfo) {
  2489. // create a new entry
  2490. const memCache = new WeakTupleMap();
  2491. moduleMemCacheCache.set(module, {
  2492. buildInfo,
  2493. references: computeReferences(module),
  2494. memCache
  2495. });
  2496. moduleMemCaches.set(module, memCache);
  2497. affectedModules.add(module);
  2498. statNew++;
  2499. } else {
  2500. infectedModules.add(module);
  2501. statWithoutBuild++;
  2502. }
  2503. }
  2504. /**
  2505. * @param {Readonly<ModuleGraphConnection[]>} connections connections
  2506. * @returns {symbol | boolean} result
  2507. */
  2508. const reduceAffectType = (connections) => {
  2509. let affected = false;
  2510. for (const { dependency } of connections) {
  2511. if (!dependency) continue;
  2512. const type = dependency.couldAffectReferencingModule();
  2513. if (type === Dependency.TRANSITIVE) return Dependency.TRANSITIVE;
  2514. if (type === false) continue;
  2515. affected = true;
  2516. }
  2517. return affected;
  2518. };
  2519. const directOnlyInfectedModules = new Set();
  2520. for (const module of infectedModules) {
  2521. for (const [
  2522. referencingModule,
  2523. connections
  2524. ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) {
  2525. if (!referencingModule) continue;
  2526. if (infectedModules.has(referencingModule)) continue;
  2527. const type = reduceAffectType(connections);
  2528. if (!type) continue;
  2529. if (type === true) {
  2530. directOnlyInfectedModules.add(referencingModule);
  2531. } else {
  2532. infectedModules.add(referencingModule);
  2533. }
  2534. }
  2535. }
  2536. for (const module of directOnlyInfectedModules) infectedModules.add(module);
  2537. const directOnlyAffectModules = new Set();
  2538. for (const module of affectedModules) {
  2539. for (const [
  2540. referencingModule,
  2541. connections
  2542. ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) {
  2543. if (!referencingModule) continue;
  2544. if (infectedModules.has(referencingModule)) continue;
  2545. if (affectedModules.has(referencingModule)) continue;
  2546. const type = reduceAffectType(connections);
  2547. if (!type) continue;
  2548. if (type === true) {
  2549. directOnlyAffectModules.add(referencingModule);
  2550. } else {
  2551. affectedModules.add(referencingModule);
  2552. }
  2553. /** @type {MemCache} */
  2554. const memCache = new WeakTupleMap();
  2555. const cache =
  2556. /** @type {ModuleMemCachesItem} */
  2557. (moduleMemCacheCache.get(referencingModule));
  2558. cache.memCache = memCache;
  2559. moduleMemCaches.set(referencingModule, memCache);
  2560. }
  2561. }
  2562. for (const module of directOnlyAffectModules) affectedModules.add(module);
  2563. this.logger.log(
  2564. `${Math.round(
  2565. (100 * (affectedModules.size + infectedModules.size)) /
  2566. this.modules.size
  2567. )}% (${affectedModules.size} affected + ${
  2568. infectedModules.size
  2569. } infected of ${
  2570. this.modules.size
  2571. }) modules flagged as affected (${statNew} new modules, ${statChanged} changed, ${statReferencesChanged} references changed, ${statUnchanged} unchanged, ${statWithoutBuild} were not built)`
  2572. );
  2573. }
  2574. _computeAffectedModulesWithChunkGraph() {
  2575. const { moduleMemCaches } = this;
  2576. if (!moduleMemCaches) return;
  2577. const moduleMemCaches2 = (this.moduleMemCaches2 = new Map());
  2578. const { moduleGraph, chunkGraph } = this;
  2579. const key = "memCache2";
  2580. let statUnchanged = 0;
  2581. let statChanged = 0;
  2582. let statNew = 0;
  2583. /**
  2584. * @param {Module} module module
  2585. * @returns {References} references
  2586. */
  2587. const computeReferences = (module) => {
  2588. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
  2589. /** @type {Map<Module, ModuleId> | undefined} */
  2590. let modules;
  2591. /** @type {(ChunkId | null)[] | undefined} */
  2592. let blocks;
  2593. const outgoing = moduleGraph.getOutgoingConnectionsByModule(module);
  2594. if (outgoing !== undefined) {
  2595. for (const m of outgoing.keys()) {
  2596. if (!m) continue;
  2597. if (modules === undefined) modules = new Map();
  2598. modules.set(m, /** @type {ModuleId} */ (chunkGraph.getModuleId(m)));
  2599. }
  2600. }
  2601. if (module.blocks.length > 0) {
  2602. blocks = [];
  2603. const queue = [...module.blocks];
  2604. for (const block of queue) {
  2605. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  2606. if (chunkGroup) {
  2607. for (const chunk of chunkGroup.chunks) {
  2608. blocks.push(chunk.id);
  2609. }
  2610. } else {
  2611. blocks.push(null);
  2612. }
  2613. // eslint-disable-next-line prefer-spread
  2614. queue.push.apply(queue, block.blocks);
  2615. }
  2616. }
  2617. return { id, modules, blocks };
  2618. };
  2619. /**
  2620. * @param {Module} module module
  2621. * @param {object} references references
  2622. * @param {string | number} references.id id
  2623. * @param {Map<Module, string | number | undefined>=} references.modules modules
  2624. * @param {(string | number | null)[]=} references.blocks blocks
  2625. * @returns {boolean} ok?
  2626. */
  2627. const compareReferences = (module, { id, modules, blocks }) => {
  2628. if (id !== chunkGraph.getModuleId(module)) return false;
  2629. if (modules !== undefined) {
  2630. for (const [module, id] of modules) {
  2631. if (chunkGraph.getModuleId(module) !== id) return false;
  2632. }
  2633. }
  2634. if (blocks !== undefined) {
  2635. const queue = [...module.blocks];
  2636. let i = 0;
  2637. for (const block of queue) {
  2638. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  2639. if (chunkGroup) {
  2640. for (const chunk of chunkGroup.chunks) {
  2641. if (i >= blocks.length || blocks[i++] !== chunk.id) return false;
  2642. }
  2643. } else if (i >= blocks.length || blocks[i++] !== null) {
  2644. return false;
  2645. }
  2646. // eslint-disable-next-line prefer-spread
  2647. queue.push.apply(queue, block.blocks);
  2648. }
  2649. if (i !== blocks.length) return false;
  2650. }
  2651. return true;
  2652. };
  2653. for (const [module, memCache] of moduleMemCaches) {
  2654. /** @type {{ references: References, memCache: MemCache } | undefined} */
  2655. const cache = memCache.get(key);
  2656. if (cache === undefined) {
  2657. /** @type {WeakTupleMap<Module[], RuntimeRequirements | null> | undefined} */
  2658. const memCache2 = new WeakTupleMap();
  2659. memCache.set(key, {
  2660. references: computeReferences(module),
  2661. memCache: memCache2
  2662. });
  2663. moduleMemCaches2.set(module, memCache2);
  2664. statNew++;
  2665. } else if (!compareReferences(module, cache.references)) {
  2666. /** @type {WeakTupleMap<Module[], RuntimeRequirements | null> | undefined} */
  2667. const memCache = new WeakTupleMap();
  2668. cache.references = computeReferences(module);
  2669. cache.memCache = memCache;
  2670. moduleMemCaches2.set(module, memCache);
  2671. statChanged++;
  2672. } else {
  2673. moduleMemCaches2.set(module, cache.memCache);
  2674. statUnchanged++;
  2675. }
  2676. }
  2677. this.logger.log(
  2678. `${Math.round(
  2679. (100 * statChanged) / (statNew + statChanged + statUnchanged)
  2680. )}% modules flagged as affected by chunk graph (${statNew} new modules, ${statChanged} changed, ${statUnchanged} unchanged)`
  2681. );
  2682. }
  2683. /**
  2684. * @param {Callback} callback callback
  2685. */
  2686. finish(callback) {
  2687. this.factorizeQueue.clear();
  2688. if (this.profile) {
  2689. this.logger.time("finish module profiles");
  2690. const ParallelismFactorCalculator = require("./util/ParallelismFactorCalculator");
  2691. const p = new ParallelismFactorCalculator();
  2692. const moduleGraph = this.moduleGraph;
  2693. /** @type {Map<Module, ModuleProfile>} */
  2694. const modulesWithProfiles = new Map();
  2695. for (const module of this.modules) {
  2696. const profile = moduleGraph.getProfile(module);
  2697. if (!profile) continue;
  2698. modulesWithProfiles.set(module, profile);
  2699. p.range(
  2700. profile.buildingStartTime,
  2701. profile.buildingEndTime,
  2702. (f) => (profile.buildingParallelismFactor = f)
  2703. );
  2704. p.range(
  2705. profile.factoryStartTime,
  2706. profile.factoryEndTime,
  2707. (f) => (profile.factoryParallelismFactor = f)
  2708. );
  2709. p.range(
  2710. profile.integrationStartTime,
  2711. profile.integrationEndTime,
  2712. (f) => (profile.integrationParallelismFactor = f)
  2713. );
  2714. p.range(
  2715. profile.storingStartTime,
  2716. profile.storingEndTime,
  2717. (f) => (profile.storingParallelismFactor = f)
  2718. );
  2719. p.range(
  2720. profile.restoringStartTime,
  2721. profile.restoringEndTime,
  2722. (f) => (profile.restoringParallelismFactor = f)
  2723. );
  2724. if (profile.additionalFactoryTimes) {
  2725. for (const { start, end } of profile.additionalFactoryTimes) {
  2726. const influence = (end - start) / profile.additionalFactories;
  2727. p.range(
  2728. start,
  2729. end,
  2730. (f) =>
  2731. (profile.additionalFactoriesParallelismFactor += f * influence)
  2732. );
  2733. }
  2734. }
  2735. }
  2736. p.calculate();
  2737. const logger = this.getLogger("webpack.Compilation.ModuleProfile");
  2738. // Avoid coverage problems due indirect changes
  2739. /**
  2740. * @param {number} value value
  2741. * @param {string} msg message
  2742. */
  2743. /* istanbul ignore next */
  2744. const logByValue = (value, msg) => {
  2745. if (value > 1000) {
  2746. logger.error(msg);
  2747. } else if (value > 500) {
  2748. logger.warn(msg);
  2749. } else if (value > 200) {
  2750. logger.info(msg);
  2751. } else if (value > 30) {
  2752. logger.log(msg);
  2753. } else {
  2754. logger.debug(msg);
  2755. }
  2756. };
  2757. /**
  2758. * @param {string} category a category
  2759. * @param {(profile: ModuleProfile) => number} getDuration get duration callback
  2760. * @param {(profile: ModuleProfile) => number} getParallelism get parallelism callback
  2761. */
  2762. const logNormalSummary = (category, getDuration, getParallelism) => {
  2763. let sum = 0;
  2764. let max = 0;
  2765. for (const [module, profile] of modulesWithProfiles) {
  2766. const p = getParallelism(profile);
  2767. const d = getDuration(profile);
  2768. if (d === 0 || p === 0) continue;
  2769. const t = d / p;
  2770. sum += t;
  2771. if (t <= 10) continue;
  2772. logByValue(
  2773. t,
  2774. ` | ${Math.round(t)} ms${
  2775. p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : ""
  2776. } ${category} > ${module.readableIdentifier(this.requestShortener)}`
  2777. );
  2778. max = Math.max(max, t);
  2779. }
  2780. if (sum <= 10) return;
  2781. logByValue(
  2782. Math.max(sum / 10, max),
  2783. `${Math.round(sum)} ms ${category}`
  2784. );
  2785. };
  2786. /**
  2787. * @param {string} category a category
  2788. * @param {(profile: ModuleProfile) => number} getDuration get duration callback
  2789. * @param {(profile: ModuleProfile) => number} getParallelism get parallelism callback
  2790. */
  2791. const logByLoadersSummary = (category, getDuration, getParallelism) => {
  2792. const map = new Map();
  2793. for (const [module, profile] of modulesWithProfiles) {
  2794. const list = getOrInsert(
  2795. map,
  2796. `${module.type}!${module.identifier().replace(/(!|^)[^!]*$/, "")}`,
  2797. () => []
  2798. );
  2799. list.push({ module, profile });
  2800. }
  2801. let sum = 0;
  2802. let max = 0;
  2803. for (const [key, modules] of map) {
  2804. let innerSum = 0;
  2805. let innerMax = 0;
  2806. for (const { module, profile } of modules) {
  2807. const p = getParallelism(profile);
  2808. const d = getDuration(profile);
  2809. if (d === 0 || p === 0) continue;
  2810. const t = d / p;
  2811. innerSum += t;
  2812. if (t <= 10) continue;
  2813. logByValue(
  2814. t,
  2815. ` | | ${Math.round(t)} ms${
  2816. p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : ""
  2817. } ${category} > ${module.readableIdentifier(
  2818. this.requestShortener
  2819. )}`
  2820. );
  2821. innerMax = Math.max(innerMax, t);
  2822. }
  2823. sum += innerSum;
  2824. if (innerSum <= 10) continue;
  2825. const idx = key.indexOf("!");
  2826. const loaders = key.slice(idx + 1);
  2827. const moduleType = key.slice(0, idx);
  2828. const t = Math.max(innerSum / 10, innerMax);
  2829. logByValue(
  2830. t,
  2831. ` | ${Math.round(innerSum)} ms ${category} > ${
  2832. loaders
  2833. ? `${
  2834. modules.length
  2835. } x ${moduleType} with ${this.requestShortener.shorten(
  2836. loaders
  2837. )}`
  2838. : `${modules.length} x ${moduleType}`
  2839. }`
  2840. );
  2841. max = Math.max(max, t);
  2842. }
  2843. if (sum <= 10) return;
  2844. logByValue(
  2845. Math.max(sum / 10, max),
  2846. `${Math.round(sum)} ms ${category}`
  2847. );
  2848. };
  2849. logNormalSummary(
  2850. "resolve to new modules",
  2851. (p) => p.factory,
  2852. (p) => p.factoryParallelismFactor
  2853. );
  2854. logNormalSummary(
  2855. "resolve to existing modules",
  2856. (p) => p.additionalFactories,
  2857. (p) => p.additionalFactoriesParallelismFactor
  2858. );
  2859. logNormalSummary(
  2860. "integrate modules",
  2861. (p) => p.restoring,
  2862. (p) => p.restoringParallelismFactor
  2863. );
  2864. logByLoadersSummary(
  2865. "build modules",
  2866. (p) => p.building,
  2867. (p) => p.buildingParallelismFactor
  2868. );
  2869. logNormalSummary(
  2870. "store modules",
  2871. (p) => p.storing,
  2872. (p) => p.storingParallelismFactor
  2873. );
  2874. logNormalSummary(
  2875. "restore modules",
  2876. (p) => p.restoring,
  2877. (p) => p.restoringParallelismFactor
  2878. );
  2879. this.logger.timeEnd("finish module profiles");
  2880. }
  2881. this.logger.time("compute affected modules");
  2882. this._computeAffectedModules(this.modules);
  2883. this.logger.timeEnd("compute affected modules");
  2884. this.logger.time("finish modules");
  2885. const { modules, moduleMemCaches } = this;
  2886. this.hooks.finishModules.callAsync(modules, (err) => {
  2887. this.logger.timeEnd("finish modules");
  2888. if (err) return callback(/** @type {WebpackError} */ (err));
  2889. // extract warnings and errors from modules
  2890. this.moduleGraph.freeze("dependency errors");
  2891. // TODO keep a cacheToken (= {}) for each module in the graph
  2892. // create a new one per compilation and flag all updated files
  2893. // and parents with it
  2894. this.logger.time("report dependency errors and warnings");
  2895. for (const module of modules) {
  2896. // TODO only run for modules with changed cacheToken
  2897. // global WeakMap<CacheToken, WeakSet<Module>> to keep modules without errors/warnings
  2898. const memCache = moduleMemCaches && moduleMemCaches.get(module);
  2899. if (memCache && memCache.get("noWarningsOrErrors")) continue;
  2900. let hasProblems = this.reportDependencyErrorsAndWarnings(module, [
  2901. module
  2902. ]);
  2903. const errors = module.getErrors();
  2904. if (errors !== undefined) {
  2905. for (const error of errors) {
  2906. if (!error.module) {
  2907. error.module = module;
  2908. }
  2909. this.errors.push(error);
  2910. hasProblems = true;
  2911. }
  2912. }
  2913. const warnings = module.getWarnings();
  2914. if (warnings !== undefined) {
  2915. for (const warning of warnings) {
  2916. if (!warning.module) {
  2917. warning.module = module;
  2918. }
  2919. this.warnings.push(warning);
  2920. hasProblems = true;
  2921. }
  2922. }
  2923. if (!hasProblems && memCache) memCache.set("noWarningsOrErrors", true);
  2924. }
  2925. this.moduleGraph.unfreeze();
  2926. this.logger.timeEnd("report dependency errors and warnings");
  2927. callback();
  2928. });
  2929. }
  2930. unseal() {
  2931. this.hooks.unseal.call();
  2932. this.chunks.clear();
  2933. this.chunkGroups.length = 0;
  2934. this.namedChunks.clear();
  2935. this.namedChunkGroups.clear();
  2936. this.entrypoints.clear();
  2937. this.additionalChunkAssets.length = 0;
  2938. this.assets = {};
  2939. this.assetsInfo.clear();
  2940. this.moduleGraph.removeAllModuleAttributes();
  2941. this.moduleGraph.unfreeze();
  2942. this.moduleMemCaches2 = undefined;
  2943. }
  2944. /**
  2945. * @param {Callback} callback signals when the call finishes
  2946. * @returns {void}
  2947. */
  2948. seal(callback) {
  2949. /**
  2950. * @param {WebpackError=} err err
  2951. * @returns {void}
  2952. */
  2953. const finalCallback = (err) => {
  2954. this.factorizeQueue.clear();
  2955. this.buildQueue.clear();
  2956. this.rebuildQueue.clear();
  2957. this.processDependenciesQueue.clear();
  2958. this.addModuleQueue.clear();
  2959. return callback(err);
  2960. };
  2961. if (this._backCompat) {
  2962. for (const module of this.modules) {
  2963. ChunkGraph.setChunkGraphForModule(module, this.chunkGraph);
  2964. }
  2965. }
  2966. this.hooks.seal.call();
  2967. this.logger.time("optimize dependencies");
  2968. while (this.hooks.optimizeDependencies.call(this.modules)) {
  2969. /* empty */
  2970. }
  2971. this.hooks.afterOptimizeDependencies.call(this.modules);
  2972. this.logger.timeEnd("optimize dependencies");
  2973. this.logger.time("create chunks");
  2974. this.hooks.beforeChunks.call();
  2975. this.moduleGraph.freeze("seal");
  2976. /** @type {Map<Entrypoint, Module[]>} */
  2977. const chunkGraphInit = new Map();
  2978. for (const [name, { dependencies, includeDependencies, options }] of this
  2979. .entries) {
  2980. const chunk = this.addChunk(name);
  2981. if (options.filename) {
  2982. chunk.filenameTemplate = options.filename;
  2983. }
  2984. const entrypoint = new Entrypoint(options);
  2985. if (!options.dependOn && !options.runtime) {
  2986. entrypoint.setRuntimeChunk(chunk);
  2987. }
  2988. entrypoint.setEntrypointChunk(chunk);
  2989. this.namedChunkGroups.set(name, entrypoint);
  2990. this.entrypoints.set(name, entrypoint);
  2991. this.chunkGroups.push(entrypoint);
  2992. connectChunkGroupAndChunk(entrypoint, chunk);
  2993. const entryModules = new Set();
  2994. for (const dep of [...this.globalEntry.dependencies, ...dependencies]) {
  2995. entrypoint.addOrigin(
  2996. null,
  2997. { name },
  2998. /** @type {Dependency & { request: string }} */
  2999. (dep).request
  3000. );
  3001. const module = this.moduleGraph.getModule(dep);
  3002. if (module) {
  3003. this.chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint);
  3004. entryModules.add(module);
  3005. const modulesList = chunkGraphInit.get(entrypoint);
  3006. if (modulesList === undefined) {
  3007. chunkGraphInit.set(entrypoint, [module]);
  3008. } else {
  3009. modulesList.push(module);
  3010. }
  3011. }
  3012. }
  3013. this.assignDepths(entryModules);
  3014. /**
  3015. * @param {Dependency[]} deps deps
  3016. * @returns {Module[]} sorted deps
  3017. */
  3018. const mapAndSort = (deps) =>
  3019. /** @type {Module[]} */
  3020. (
  3021. deps.map((dep) => this.moduleGraph.getModule(dep)).filter(Boolean)
  3022. ).sort(compareModulesByIdentifier);
  3023. const includedModules = [
  3024. ...mapAndSort(this.globalEntry.includeDependencies),
  3025. ...mapAndSort(includeDependencies)
  3026. ];
  3027. let modulesList = chunkGraphInit.get(entrypoint);
  3028. if (modulesList === undefined) {
  3029. chunkGraphInit.set(entrypoint, (modulesList = []));
  3030. }
  3031. for (const module of includedModules) {
  3032. this.assignDepth(module);
  3033. modulesList.push(module);
  3034. }
  3035. }
  3036. const runtimeChunks = new Set();
  3037. outer: for (const [
  3038. name,
  3039. {
  3040. options: { dependOn, runtime }
  3041. }
  3042. ] of this.entries) {
  3043. if (dependOn && runtime) {
  3044. const err =
  3045. new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid.
  3046. Entrypoints that depend on other entrypoints do not have their own runtime.
  3047. They will use the runtime(s) from referenced entrypoints instead.
  3048. Remove the 'runtime' option from the entrypoint.`);
  3049. const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name));
  3050. err.chunk = entry.getEntrypointChunk();
  3051. this.errors.push(err);
  3052. }
  3053. if (dependOn) {
  3054. const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name));
  3055. const referencedChunks = entry
  3056. .getEntrypointChunk()
  3057. .getAllReferencedChunks();
  3058. for (const dep of dependOn) {
  3059. const dependency = this.entrypoints.get(dep);
  3060. if (!dependency) {
  3061. throw new Error(
  3062. `Entry ${name} depends on ${dep}, but this entry was not found`
  3063. );
  3064. }
  3065. if (referencedChunks.has(dependency.getEntrypointChunk())) {
  3066. const err = new WebpackError(
  3067. `Entrypoints '${name}' and '${dep}' use 'dependOn' to depend on each other in a circular way.`
  3068. );
  3069. const entryChunk = entry.getEntrypointChunk();
  3070. err.chunk = entryChunk;
  3071. this.errors.push(err);
  3072. entry.setRuntimeChunk(entryChunk);
  3073. continue outer;
  3074. }
  3075. connectEntrypointAndDependOn(entry, dependency);
  3076. connectChunkGroupParentAndChild(dependency, entry);
  3077. }
  3078. } else if (runtime) {
  3079. const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name));
  3080. let chunk = this.namedChunks.get(runtime);
  3081. if (chunk) {
  3082. if (!runtimeChunks.has(chunk)) {
  3083. const err =
  3084. new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'.
  3085. It's not valid to use other entrypoints as runtime chunk.
  3086. Did you mean to use 'dependOn: ${JSON.stringify(
  3087. runtime
  3088. )}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used.
  3089. Or do you want to use the entrypoints '${name}' and '${runtime}' independently on the same page with a shared runtime? In this case give them both the same value for the 'runtime' option. It must be a name not already used by an entrypoint.`);
  3090. const entryChunk =
  3091. /** @type {Chunk} */
  3092. (entry.getEntrypointChunk());
  3093. err.chunk = entryChunk;
  3094. this.errors.push(err);
  3095. entry.setRuntimeChunk(entryChunk);
  3096. continue;
  3097. }
  3098. } else {
  3099. chunk = this.addChunk(runtime);
  3100. chunk.preventIntegration = true;
  3101. runtimeChunks.add(chunk);
  3102. }
  3103. entry.unshiftChunk(chunk);
  3104. chunk.addGroup(entry);
  3105. entry.setRuntimeChunk(chunk);
  3106. }
  3107. }
  3108. buildChunkGraph(this, chunkGraphInit);
  3109. this.hooks.afterChunks.call(this.chunks);
  3110. this.logger.timeEnd("create chunks");
  3111. this.logger.time("optimize");
  3112. this.hooks.optimize.call();
  3113. while (this.hooks.optimizeModules.call(this.modules)) {
  3114. /* empty */
  3115. }
  3116. this.hooks.afterOptimizeModules.call(this.modules);
  3117. while (this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups)) {
  3118. /* empty */
  3119. }
  3120. this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups);
  3121. this.hooks.optimizeTree.callAsync(this.chunks, this.modules, (err) => {
  3122. if (err) {
  3123. return finalCallback(
  3124. makeWebpackError(err, "Compilation.hooks.optimizeTree")
  3125. );
  3126. }
  3127. this.hooks.afterOptimizeTree.call(this.chunks, this.modules);
  3128. this.hooks.optimizeChunkModules.callAsync(
  3129. this.chunks,
  3130. this.modules,
  3131. (err) => {
  3132. if (err) {
  3133. return finalCallback(
  3134. makeWebpackError(err, "Compilation.hooks.optimizeChunkModules")
  3135. );
  3136. }
  3137. this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules);
  3138. const shouldRecord = this.hooks.shouldRecord.call() !== false;
  3139. this.hooks.reviveModules.call(
  3140. this.modules,
  3141. /** @type {Records} */
  3142. (this.records)
  3143. );
  3144. this.hooks.beforeModuleIds.call(this.modules);
  3145. this.hooks.moduleIds.call(this.modules);
  3146. this.hooks.optimizeModuleIds.call(this.modules);
  3147. this.hooks.afterOptimizeModuleIds.call(this.modules);
  3148. this.hooks.reviveChunks.call(
  3149. this.chunks,
  3150. /** @type {Records} */
  3151. (this.records)
  3152. );
  3153. this.hooks.beforeChunkIds.call(this.chunks);
  3154. this.hooks.chunkIds.call(this.chunks);
  3155. this.hooks.optimizeChunkIds.call(this.chunks);
  3156. this.hooks.afterOptimizeChunkIds.call(this.chunks);
  3157. this.assignRuntimeIds();
  3158. this.logger.time("compute affected modules with chunk graph");
  3159. this._computeAffectedModulesWithChunkGraph();
  3160. this.logger.timeEnd("compute affected modules with chunk graph");
  3161. this.sortItemsWithChunkIds();
  3162. if (shouldRecord) {
  3163. this.hooks.recordModules.call(
  3164. this.modules,
  3165. /** @type {Records} */
  3166. (this.records)
  3167. );
  3168. this.hooks.recordChunks.call(
  3169. this.chunks,
  3170. /** @type {Records} */
  3171. (this.records)
  3172. );
  3173. }
  3174. this.hooks.optimizeCodeGeneration.call(this.modules);
  3175. this.logger.timeEnd("optimize");
  3176. this.logger.time("module hashing");
  3177. this.hooks.beforeModuleHash.call();
  3178. this.createModuleHashes();
  3179. this.hooks.afterModuleHash.call();
  3180. this.logger.timeEnd("module hashing");
  3181. this.logger.time("code generation");
  3182. this.hooks.beforeCodeGeneration.call();
  3183. this.codeGeneration((err) => {
  3184. if (err) {
  3185. return finalCallback(err);
  3186. }
  3187. this.hooks.afterCodeGeneration.call();
  3188. this.logger.timeEnd("code generation");
  3189. this.logger.time("runtime requirements");
  3190. this.hooks.beforeRuntimeRequirements.call();
  3191. this.processRuntimeRequirements();
  3192. this.hooks.afterRuntimeRequirements.call();
  3193. this.logger.timeEnd("runtime requirements");
  3194. this.logger.time("hashing");
  3195. this.hooks.beforeHash.call();
  3196. const codeGenerationJobs = this.createHash();
  3197. this.hooks.afterHash.call();
  3198. this.logger.timeEnd("hashing");
  3199. this._runCodeGenerationJobs(codeGenerationJobs, (err) => {
  3200. if (err) {
  3201. return finalCallback(err);
  3202. }
  3203. if (shouldRecord) {
  3204. this.logger.time("record hash");
  3205. this.hooks.recordHash.call(
  3206. /** @type {Records} */
  3207. (this.records)
  3208. );
  3209. this.logger.timeEnd("record hash");
  3210. }
  3211. this.logger.time("module assets");
  3212. this.clearAssets();
  3213. this.hooks.beforeModuleAssets.call();
  3214. this.createModuleAssets();
  3215. this.logger.timeEnd("module assets");
  3216. const cont = () => {
  3217. this.logger.time("process assets");
  3218. this.hooks.processAssets.callAsync(this.assets, (err) => {
  3219. if (err) {
  3220. return finalCallback(
  3221. makeWebpackError(err, "Compilation.hooks.processAssets")
  3222. );
  3223. }
  3224. this.hooks.afterProcessAssets.call(this.assets);
  3225. this.logger.timeEnd("process assets");
  3226. this.assets =
  3227. /** @type {CompilationAssets} */
  3228. (
  3229. this._backCompat
  3230. ? soonFrozenObjectDeprecation(
  3231. this.assets,
  3232. "Compilation.assets",
  3233. "DEP_WEBPACK_COMPILATION_ASSETS",
  3234. `BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
  3235. Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
  3236. Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.`
  3237. )
  3238. : Object.freeze(this.assets)
  3239. );
  3240. this.summarizeDependencies();
  3241. if (shouldRecord) {
  3242. this.hooks.record.call(
  3243. this,
  3244. /** @type {Records} */
  3245. (this.records)
  3246. );
  3247. }
  3248. if (this.hooks.needAdditionalSeal.call()) {
  3249. this.unseal();
  3250. return this.seal(callback);
  3251. }
  3252. return this.hooks.afterSeal.callAsync((err) => {
  3253. if (err) {
  3254. return finalCallback(
  3255. makeWebpackError(err, "Compilation.hooks.afterSeal")
  3256. );
  3257. }
  3258. this.fileSystemInfo.logStatistics();
  3259. finalCallback();
  3260. });
  3261. });
  3262. };
  3263. this.logger.time("create chunk assets");
  3264. if (this.hooks.shouldGenerateChunkAssets.call() !== false) {
  3265. this.hooks.beforeChunkAssets.call();
  3266. this.createChunkAssets((err) => {
  3267. this.logger.timeEnd("create chunk assets");
  3268. if (err) {
  3269. return finalCallback(err);
  3270. }
  3271. cont();
  3272. });
  3273. } else {
  3274. this.logger.timeEnd("create chunk assets");
  3275. cont();
  3276. }
  3277. });
  3278. });
  3279. }
  3280. );
  3281. });
  3282. }
  3283. /**
  3284. * @param {Module} module module to report from
  3285. * @param {DependenciesBlock[]} blocks blocks to report from
  3286. * @returns {boolean} true, when it has warnings or errors
  3287. */
  3288. reportDependencyErrorsAndWarnings(module, blocks) {
  3289. let hasProblems = false;
  3290. for (const block of blocks) {
  3291. const dependencies = block.dependencies;
  3292. for (const d of dependencies) {
  3293. const warnings = d.getWarnings(this.moduleGraph);
  3294. if (warnings) {
  3295. for (const w of warnings) {
  3296. const warning = new ModuleDependencyWarning(module, w, d.loc);
  3297. this.warnings.push(warning);
  3298. hasProblems = true;
  3299. }
  3300. }
  3301. const errors = d.getErrors(this.moduleGraph);
  3302. if (errors) {
  3303. for (const e of errors) {
  3304. const error = new ModuleDependencyError(module, e, d.loc);
  3305. this.errors.push(error);
  3306. hasProblems = true;
  3307. }
  3308. }
  3309. }
  3310. if (this.reportDependencyErrorsAndWarnings(module, block.blocks)) {
  3311. hasProblems = true;
  3312. }
  3313. }
  3314. return hasProblems;
  3315. }
  3316. /**
  3317. * @param {Callback} callback callback
  3318. */
  3319. codeGeneration(callback) {
  3320. const { chunkGraph } = this;
  3321. this.codeGenerationResults = new CodeGenerationResults(
  3322. this.outputOptions.hashFunction
  3323. );
  3324. /** @type {CodeGenerationJobs} */
  3325. const jobs = [];
  3326. for (const module of this.modules) {
  3327. const runtimes = chunkGraph.getModuleRuntimes(module);
  3328. if (runtimes.size === 1) {
  3329. for (const runtime of runtimes) {
  3330. const hash = chunkGraph.getModuleHash(module, runtime);
  3331. jobs.push({ module, hash, runtime, runtimes: [runtime] });
  3332. }
  3333. } else if (runtimes.size > 1) {
  3334. /** @type {Map<string, { runtimes: RuntimeSpec[] }>} */
  3335. const map = new Map();
  3336. for (const runtime of runtimes) {
  3337. const hash = chunkGraph.getModuleHash(module, runtime);
  3338. const job = map.get(hash);
  3339. if (job === undefined) {
  3340. const newJob = { module, hash, runtime, runtimes: [runtime] };
  3341. jobs.push(newJob);
  3342. map.set(hash, newJob);
  3343. } else {
  3344. job.runtimes.push(runtime);
  3345. }
  3346. }
  3347. }
  3348. }
  3349. this._runCodeGenerationJobs(jobs, callback);
  3350. }
  3351. /**
  3352. * @private
  3353. * @param {CodeGenerationJobs} jobs code generation jobs
  3354. * @param {Callback} callback callback
  3355. * @returns {void}
  3356. */
  3357. _runCodeGenerationJobs(jobs, callback) {
  3358. if (jobs.length === 0) {
  3359. return callback();
  3360. }
  3361. let statModulesFromCache = 0;
  3362. let statModulesGenerated = 0;
  3363. const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } =
  3364. this;
  3365. const results =
  3366. /** @type {CodeGenerationResults} */
  3367. (this.codeGenerationResults);
  3368. /** @type {WebpackError[]} */
  3369. const errors = [];
  3370. /** @type {NotCodeGeneratedModules | undefined} */
  3371. let notCodeGeneratedModules;
  3372. const runIteration = () => {
  3373. /** @type {CodeGenerationJobs} */
  3374. let delayedJobs = [];
  3375. let delayedModules = new Set();
  3376. asyncLib.eachLimit(
  3377. jobs,
  3378. this.options.parallelism,
  3379. (job, callback) => {
  3380. const { module } = job;
  3381. const { codeGenerationDependencies } = module;
  3382. if (
  3383. codeGenerationDependencies !== undefined &&
  3384. (notCodeGeneratedModules === undefined ||
  3385. codeGenerationDependencies.some((dep) => {
  3386. const referencedModule = /** @type {Module} */ (
  3387. moduleGraph.getModule(dep)
  3388. );
  3389. return /** @type {NotCodeGeneratedModules} */ (
  3390. notCodeGeneratedModules
  3391. ).has(referencedModule);
  3392. }))
  3393. ) {
  3394. delayedJobs.push(job);
  3395. delayedModules.add(module);
  3396. return callback();
  3397. }
  3398. const { hash, runtime, runtimes } = job;
  3399. this._codeGenerationModule(
  3400. module,
  3401. runtime,
  3402. runtimes,
  3403. hash,
  3404. dependencyTemplates,
  3405. chunkGraph,
  3406. moduleGraph,
  3407. runtimeTemplate,
  3408. errors,
  3409. results,
  3410. (err, codeGenerated) => {
  3411. if (codeGenerated) statModulesGenerated++;
  3412. else statModulesFromCache++;
  3413. callback(err);
  3414. }
  3415. );
  3416. },
  3417. (err) => {
  3418. if (err) return callback(err);
  3419. if (delayedJobs.length > 0) {
  3420. if (delayedJobs.length === jobs.length) {
  3421. return callback(
  3422. /** @type {WebpackError} */ (
  3423. new Error(
  3424. `Unable to make progress during code generation because of circular code generation dependency: ${Array.from(
  3425. delayedModules,
  3426. (m) => m.identifier()
  3427. ).join(", ")}`
  3428. )
  3429. )
  3430. );
  3431. }
  3432. jobs = delayedJobs;
  3433. delayedJobs = [];
  3434. notCodeGeneratedModules = delayedModules;
  3435. delayedModules = new Set();
  3436. return runIteration();
  3437. }
  3438. if (errors.length > 0) {
  3439. errors.sort(
  3440. compareSelect((err) => err.module, compareModulesByIdentifier)
  3441. );
  3442. for (const error of errors) {
  3443. this.errors.push(error);
  3444. }
  3445. }
  3446. this.logger.log(
  3447. `${Math.round(
  3448. (100 * statModulesGenerated) /
  3449. (statModulesGenerated + statModulesFromCache)
  3450. )}% code generated (${statModulesGenerated} generated, ${statModulesFromCache} from cache)`
  3451. );
  3452. callback();
  3453. }
  3454. );
  3455. };
  3456. runIteration();
  3457. }
  3458. /**
  3459. * @param {Module} module module
  3460. * @param {RuntimeSpec} runtime runtime
  3461. * @param {RuntimeSpec[]} runtimes runtimes
  3462. * @param {string} hash hash
  3463. * @param {DependencyTemplates} dependencyTemplates dependencyTemplates
  3464. * @param {ChunkGraph} chunkGraph chunkGraph
  3465. * @param {ModuleGraph} moduleGraph moduleGraph
  3466. * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate
  3467. * @param {WebpackError[]} errors errors
  3468. * @param {CodeGenerationResults} results results
  3469. * @param {(err?: WebpackError | null, result?: boolean) => void} callback callback
  3470. */
  3471. _codeGenerationModule(
  3472. module,
  3473. runtime,
  3474. runtimes,
  3475. hash,
  3476. dependencyTemplates,
  3477. chunkGraph,
  3478. moduleGraph,
  3479. runtimeTemplate,
  3480. errors,
  3481. results,
  3482. callback
  3483. ) {
  3484. let codeGenerated = false;
  3485. const cache = new MultiItemCache(
  3486. runtimes.map((runtime) =>
  3487. this._codeGenerationCache.getItemCache(
  3488. `${module.identifier()}|${getRuntimeKey(runtime)}`,
  3489. `${hash}|${dependencyTemplates.getHash()}`
  3490. )
  3491. )
  3492. );
  3493. cache.get((err, cachedResult) => {
  3494. if (err) return callback(/** @type {WebpackError} */ (err));
  3495. let result;
  3496. if (!cachedResult) {
  3497. try {
  3498. codeGenerated = true;
  3499. this.codeGeneratedModules.add(module);
  3500. result = module.codeGeneration({
  3501. chunkGraph,
  3502. moduleGraph,
  3503. dependencyTemplates,
  3504. runtimeTemplate,
  3505. runtime,
  3506. runtimes,
  3507. codeGenerationResults: results,
  3508. compilation: this
  3509. });
  3510. } catch (err) {
  3511. errors.push(
  3512. new CodeGenerationError(module, /** @type {Error} */ (err))
  3513. );
  3514. result = cachedResult = {
  3515. sources: new Map(),
  3516. runtimeRequirements: null
  3517. };
  3518. }
  3519. } else {
  3520. result = cachedResult;
  3521. }
  3522. for (const runtime of runtimes) {
  3523. results.add(module, runtime, result);
  3524. }
  3525. if (!cachedResult) {
  3526. cache.store(result, (err) =>
  3527. callback(/** @type {WebpackError} */ (err), codeGenerated)
  3528. );
  3529. } else {
  3530. callback(null, codeGenerated);
  3531. }
  3532. });
  3533. }
  3534. _getChunkGraphEntries() {
  3535. /** @type {Set<Chunk>} */
  3536. const treeEntries = new Set();
  3537. for (const ep of this.entrypoints.values()) {
  3538. const chunk = ep.getRuntimeChunk();
  3539. if (chunk) treeEntries.add(chunk);
  3540. }
  3541. for (const ep of this.asyncEntrypoints) {
  3542. const chunk = ep.getRuntimeChunk();
  3543. if (chunk) treeEntries.add(chunk);
  3544. }
  3545. return treeEntries;
  3546. }
  3547. /**
  3548. * @param {object} options options
  3549. * @param {ChunkGraph=} options.chunkGraph the chunk graph
  3550. * @param {Iterable<Module>=} options.modules modules
  3551. * @param {Iterable<Chunk>=} options.chunks chunks
  3552. * @param {CodeGenerationResults=} options.codeGenerationResults codeGenerationResults
  3553. * @param {Iterable<Chunk>=} options.chunkGraphEntries chunkGraphEntries
  3554. * @returns {void}
  3555. */
  3556. processRuntimeRequirements({
  3557. chunkGraph = this.chunkGraph,
  3558. modules = this.modules,
  3559. chunks = this.chunks,
  3560. codeGenerationResults = /** @type {CodeGenerationResults} */ (
  3561. this.codeGenerationResults
  3562. ),
  3563. chunkGraphEntries = this._getChunkGraphEntries()
  3564. } = {}) {
  3565. const context = { chunkGraph, codeGenerationResults };
  3566. const { moduleMemCaches2 } = this;
  3567. this.logger.time("runtime requirements.modules");
  3568. const additionalModuleRuntimeRequirements =
  3569. this.hooks.additionalModuleRuntimeRequirements;
  3570. const runtimeRequirementInModule = this.hooks.runtimeRequirementInModule;
  3571. for (const module of modules) {
  3572. if (chunkGraph.getNumberOfModuleChunks(module) > 0) {
  3573. const memCache = moduleMemCaches2 && moduleMemCaches2.get(module);
  3574. for (const runtime of chunkGraph.getModuleRuntimes(module)) {
  3575. if (memCache) {
  3576. const cached = memCache.get(
  3577. `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`
  3578. );
  3579. if (cached !== undefined) {
  3580. if (cached !== null) {
  3581. chunkGraph.addModuleRuntimeRequirements(
  3582. module,
  3583. runtime,
  3584. /** @type {RuntimeRequirements} */
  3585. (cached),
  3586. false
  3587. );
  3588. }
  3589. continue;
  3590. }
  3591. }
  3592. let set;
  3593. const runtimeRequirements =
  3594. codeGenerationResults.getRuntimeRequirements(module, runtime);
  3595. if (runtimeRequirements && runtimeRequirements.size > 0) {
  3596. set = new Set(runtimeRequirements);
  3597. } else if (additionalModuleRuntimeRequirements.isUsed()) {
  3598. set = new Set();
  3599. } else {
  3600. if (memCache) {
  3601. memCache.set(
  3602. `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`,
  3603. null
  3604. );
  3605. }
  3606. continue;
  3607. }
  3608. additionalModuleRuntimeRequirements.call(module, set, context);
  3609. for (const r of set) {
  3610. const hook = runtimeRequirementInModule.get(r);
  3611. if (hook !== undefined) hook.call(module, set, context);
  3612. }
  3613. if (set.size === 0) {
  3614. if (memCache) {
  3615. memCache.set(
  3616. `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`,
  3617. null
  3618. );
  3619. }
  3620. } else if (memCache) {
  3621. memCache.set(
  3622. `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`,
  3623. set
  3624. );
  3625. chunkGraph.addModuleRuntimeRequirements(
  3626. module,
  3627. runtime,
  3628. set,
  3629. false
  3630. );
  3631. } else {
  3632. chunkGraph.addModuleRuntimeRequirements(module, runtime, set);
  3633. }
  3634. }
  3635. }
  3636. }
  3637. this.logger.timeEnd("runtime requirements.modules");
  3638. this.logger.time("runtime requirements.chunks");
  3639. for (const chunk of chunks) {
  3640. /** @type {RuntimeRequirements} */
  3641. const set = new Set();
  3642. for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
  3643. const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements(
  3644. module,
  3645. chunk.runtime
  3646. );
  3647. for (const r of runtimeRequirements) set.add(r);
  3648. }
  3649. this.hooks.additionalChunkRuntimeRequirements.call(chunk, set, context);
  3650. for (const r of set) {
  3651. this.hooks.runtimeRequirementInChunk.for(r).call(chunk, set, context);
  3652. }
  3653. chunkGraph.addChunkRuntimeRequirements(chunk, set);
  3654. }
  3655. this.logger.timeEnd("runtime requirements.chunks");
  3656. this.logger.time("runtime requirements.entries");
  3657. for (const treeEntry of chunkGraphEntries) {
  3658. /** @type {RuntimeRequirements} */
  3659. const set = new Set();
  3660. for (const chunk of treeEntry.getAllReferencedChunks()) {
  3661. const runtimeRequirements =
  3662. chunkGraph.getChunkRuntimeRequirements(chunk);
  3663. for (const r of runtimeRequirements) set.add(r);
  3664. }
  3665. this.hooks.additionalTreeRuntimeRequirements.call(
  3666. treeEntry,
  3667. set,
  3668. context
  3669. );
  3670. for (const r of set) {
  3671. this.hooks.runtimeRequirementInTree
  3672. .for(r)
  3673. .call(treeEntry, set, context);
  3674. }
  3675. chunkGraph.addTreeRuntimeRequirements(treeEntry, set);
  3676. }
  3677. this.logger.timeEnd("runtime requirements.entries");
  3678. }
  3679. // TODO webpack 6 make chunkGraph argument non-optional
  3680. /**
  3681. * @param {Chunk} chunk target chunk
  3682. * @param {RuntimeModule} module runtime module
  3683. * @param {ChunkGraph} chunkGraph the chunk graph
  3684. * @returns {void}
  3685. */
  3686. addRuntimeModule(chunk, module, chunkGraph = this.chunkGraph) {
  3687. // Deprecated ModuleGraph association
  3688. if (this._backCompat) {
  3689. ModuleGraph.setModuleGraphForModule(module, this.moduleGraph);
  3690. }
  3691. // add it to the list
  3692. this.modules.add(module);
  3693. this._modules.set(module.identifier(), module);
  3694. // connect to the chunk graph
  3695. chunkGraph.connectChunkAndModule(chunk, module);
  3696. chunkGraph.connectChunkAndRuntimeModule(chunk, module);
  3697. if (module.fullHash) {
  3698. chunkGraph.addFullHashModuleToChunk(chunk, module);
  3699. } else if (module.dependentHash) {
  3700. chunkGraph.addDependentHashModuleToChunk(chunk, module);
  3701. }
  3702. // attach runtime module
  3703. module.attach(this, chunk, chunkGraph);
  3704. // Setup internals
  3705. const exportsInfo = this.moduleGraph.getExportsInfo(module);
  3706. exportsInfo.setHasProvideInfo();
  3707. if (typeof chunk.runtime === "string") {
  3708. exportsInfo.setUsedForSideEffectsOnly(chunk.runtime);
  3709. } else if (chunk.runtime === undefined) {
  3710. exportsInfo.setUsedForSideEffectsOnly(undefined);
  3711. } else {
  3712. for (const runtime of chunk.runtime) {
  3713. exportsInfo.setUsedForSideEffectsOnly(runtime);
  3714. }
  3715. }
  3716. chunkGraph.addModuleRuntimeRequirements(
  3717. module,
  3718. chunk.runtime,
  3719. new Set([RuntimeGlobals.requireScope])
  3720. );
  3721. // runtime modules don't need ids
  3722. chunkGraph.setModuleId(module, "");
  3723. // Call hook
  3724. this.hooks.runtimeModule.call(module, chunk);
  3725. }
  3726. /**
  3727. * If `module` is passed, `loc` and `request` must also be passed.
  3728. * @param {string | ChunkGroupOptions} groupOptions options for the chunk group
  3729. * @param {Module=} module the module the references the chunk group
  3730. * @param {DependencyLocation=} loc the location from with the chunk group is referenced (inside of module)
  3731. * @param {string=} request the request from which the the chunk group is referenced
  3732. * @returns {ChunkGroup} the new or existing chunk group
  3733. */
  3734. addChunkInGroup(groupOptions, module, loc, request) {
  3735. if (typeof groupOptions === "string") {
  3736. groupOptions = { name: groupOptions };
  3737. }
  3738. const name = groupOptions.name;
  3739. if (name) {
  3740. const chunkGroup = this.namedChunkGroups.get(name);
  3741. if (chunkGroup !== undefined) {
  3742. if (module) {
  3743. chunkGroup.addOrigin(
  3744. module,
  3745. /** @type {DependencyLocation} */
  3746. (loc),
  3747. /** @type {string} */
  3748. (request)
  3749. );
  3750. }
  3751. return chunkGroup;
  3752. }
  3753. }
  3754. const chunkGroup = new ChunkGroup(groupOptions);
  3755. if (module) {
  3756. chunkGroup.addOrigin(
  3757. module,
  3758. /** @type {DependencyLocation} */
  3759. (loc),
  3760. /** @type {string} */
  3761. (request)
  3762. );
  3763. }
  3764. const chunk = this.addChunk(name);
  3765. connectChunkGroupAndChunk(chunkGroup, chunk);
  3766. this.chunkGroups.push(chunkGroup);
  3767. if (name) {
  3768. this.namedChunkGroups.set(name, chunkGroup);
  3769. }
  3770. return chunkGroup;
  3771. }
  3772. /**
  3773. * @param {EntryOptions} options options for the entrypoint
  3774. * @param {Module} module the module the references the chunk group
  3775. * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module)
  3776. * @param {string} request the request from which the the chunk group is referenced
  3777. * @returns {Entrypoint} the new or existing entrypoint
  3778. */
  3779. addAsyncEntrypoint(options, module, loc, request) {
  3780. const name = options.name;
  3781. if (name) {
  3782. const entrypoint = this.namedChunkGroups.get(name);
  3783. if (entrypoint instanceof Entrypoint) {
  3784. if (module) {
  3785. entrypoint.addOrigin(module, loc, request);
  3786. }
  3787. return entrypoint;
  3788. } else if (entrypoint) {
  3789. throw new Error(
  3790. `Cannot add an async entrypoint with the name '${name}', because there is already an chunk group with this name`
  3791. );
  3792. }
  3793. }
  3794. const chunk = this.addChunk(name);
  3795. if (options.filename) {
  3796. chunk.filenameTemplate = options.filename;
  3797. }
  3798. const entrypoint = new Entrypoint(options, false);
  3799. entrypoint.setRuntimeChunk(chunk);
  3800. entrypoint.setEntrypointChunk(chunk);
  3801. if (name) {
  3802. this.namedChunkGroups.set(name, entrypoint);
  3803. }
  3804. this.chunkGroups.push(entrypoint);
  3805. this.asyncEntrypoints.push(entrypoint);
  3806. connectChunkGroupAndChunk(entrypoint, chunk);
  3807. if (module) {
  3808. entrypoint.addOrigin(module, loc, request);
  3809. }
  3810. return entrypoint;
  3811. }
  3812. /**
  3813. * This method first looks to see if a name is provided for a new chunk,
  3814. * and first looks to see if any named chunks already exist and reuse that chunk instead.
  3815. * @param {ChunkName=} name optional chunk name to be provided
  3816. * @returns {Chunk} create a chunk (invoked during seal event)
  3817. */
  3818. addChunk(name) {
  3819. if (name) {
  3820. const chunk = this.namedChunks.get(name);
  3821. if (chunk !== undefined) {
  3822. return chunk;
  3823. }
  3824. }
  3825. const chunk = new Chunk(name, this._backCompat);
  3826. this.chunks.add(chunk);
  3827. if (this._backCompat) {
  3828. ChunkGraph.setChunkGraphForChunk(chunk, this.chunkGraph);
  3829. }
  3830. if (name) {
  3831. this.namedChunks.set(name, chunk);
  3832. }
  3833. return chunk;
  3834. }
  3835. /**
  3836. * @deprecated
  3837. * @param {Module} module module to assign depth
  3838. * @returns {void}
  3839. */
  3840. assignDepth(module) {
  3841. const moduleGraph = this.moduleGraph;
  3842. const queue = new Set([module]);
  3843. /** @type {number} */
  3844. let depth;
  3845. moduleGraph.setDepth(module, 0);
  3846. /**
  3847. * @param {Module} module module for processing
  3848. * @returns {void}
  3849. */
  3850. const processModule = (module) => {
  3851. if (!moduleGraph.setDepthIfLower(module, depth)) return;
  3852. queue.add(module);
  3853. };
  3854. for (module of queue) {
  3855. queue.delete(module);
  3856. depth = /** @type {number} */ (moduleGraph.getDepth(module)) + 1;
  3857. for (const connection of moduleGraph.getOutgoingConnections(module)) {
  3858. const refModule = connection.module;
  3859. if (refModule) {
  3860. processModule(refModule);
  3861. }
  3862. }
  3863. }
  3864. }
  3865. /**
  3866. * @param {Set<Module>} modules module to assign depth
  3867. * @returns {void}
  3868. */
  3869. assignDepths(modules) {
  3870. const moduleGraph = this.moduleGraph;
  3871. /** @type {Set<Module>} */
  3872. const queue = new Set(modules);
  3873. // Track these in local variables so that queue only has one data type
  3874. let nextDepthAt = queue.size;
  3875. let depth = 0;
  3876. let i = 0;
  3877. for (const module of queue) {
  3878. moduleGraph.setDepth(module, depth);
  3879. // Some of these results come from cache, which speeds this up
  3880. const connections = moduleGraph.getOutgoingConnectionsByModule(module);
  3881. // connections will be undefined if there are no outgoing connections
  3882. if (connections) {
  3883. for (const refModule of connections.keys()) {
  3884. if (refModule) queue.add(refModule);
  3885. }
  3886. }
  3887. i++;
  3888. // Since this is a breadth-first search, all modules added to the queue
  3889. // while at depth N will be depth N+1
  3890. if (i >= nextDepthAt) {
  3891. depth++;
  3892. nextDepthAt = queue.size;
  3893. }
  3894. }
  3895. }
  3896. /**
  3897. * @param {Dependency} dependency the dependency
  3898. * @param {RuntimeSpec} runtime the runtime
  3899. * @returns {ReferencedExports} referenced exports
  3900. */
  3901. getDependencyReferencedExports(dependency, runtime) {
  3902. const referencedExports = dependency.getReferencedExports(
  3903. this.moduleGraph,
  3904. runtime
  3905. );
  3906. return this.hooks.dependencyReferencedExports.call(
  3907. referencedExports,
  3908. dependency,
  3909. runtime
  3910. );
  3911. }
  3912. /**
  3913. * @param {Module} module module relationship for removal
  3914. * @param {DependenciesBlockLike} block dependencies block
  3915. * @returns {void}
  3916. */
  3917. removeReasonsOfDependencyBlock(module, block) {
  3918. if (block.blocks) {
  3919. for (const b of block.blocks) {
  3920. this.removeReasonsOfDependencyBlock(module, b);
  3921. }
  3922. }
  3923. if (block.dependencies) {
  3924. for (const dep of block.dependencies) {
  3925. const originalModule = this.moduleGraph.getModule(dep);
  3926. if (originalModule) {
  3927. this.moduleGraph.removeConnection(dep);
  3928. if (this.chunkGraph) {
  3929. for (const chunk of this.chunkGraph.getModuleChunks(
  3930. originalModule
  3931. )) {
  3932. this.patchChunksAfterReasonRemoval(originalModule, chunk);
  3933. }
  3934. }
  3935. }
  3936. }
  3937. }
  3938. }
  3939. /**
  3940. * @param {Module} module module to patch tie
  3941. * @param {Chunk} chunk chunk to patch tie
  3942. * @returns {void}
  3943. */
  3944. patchChunksAfterReasonRemoval(module, chunk) {
  3945. if (!module.hasReasons(this.moduleGraph, chunk.runtime)) {
  3946. this.removeReasonsOfDependencyBlock(module, module);
  3947. }
  3948. if (
  3949. !module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph) &&
  3950. this.chunkGraph.isModuleInChunk(module, chunk)
  3951. ) {
  3952. this.chunkGraph.disconnectChunkAndModule(chunk, module);
  3953. this.removeChunkFromDependencies(module, chunk);
  3954. }
  3955. }
  3956. /**
  3957. * @param {DependenciesBlock} block block tie for Chunk
  3958. * @param {Chunk} chunk chunk to remove from dep
  3959. * @returns {void}
  3960. */
  3961. removeChunkFromDependencies(block, chunk) {
  3962. /**
  3963. * @param {Dependency} d dependency to (maybe) patch up
  3964. */
  3965. const iteratorDependency = (d) => {
  3966. const depModule = this.moduleGraph.getModule(d);
  3967. if (!depModule) {
  3968. return;
  3969. }
  3970. this.patchChunksAfterReasonRemoval(depModule, chunk);
  3971. };
  3972. const blocks = block.blocks;
  3973. for (const asyncBlock of blocks) {
  3974. const chunkGroup =
  3975. /** @type {ChunkGroup} */
  3976. (this.chunkGraph.getBlockChunkGroup(asyncBlock));
  3977. // Grab all chunks from the first Block's AsyncDepBlock
  3978. const chunks = chunkGroup.chunks;
  3979. // For each chunk in chunkGroup
  3980. for (const iteratedChunk of chunks) {
  3981. chunkGroup.removeChunk(iteratedChunk);
  3982. // Recurse
  3983. this.removeChunkFromDependencies(block, iteratedChunk);
  3984. }
  3985. }
  3986. if (block.dependencies) {
  3987. for (const dep of block.dependencies) iteratorDependency(dep);
  3988. }
  3989. }
  3990. assignRuntimeIds() {
  3991. const { chunkGraph } = this;
  3992. /**
  3993. * @param {Entrypoint} ep an entrypoint
  3994. */
  3995. const processEntrypoint = (ep) => {
  3996. const runtime = /** @type {string} */ (ep.options.runtime || ep.name);
  3997. const chunk = /** @type {Chunk} */ (ep.getRuntimeChunk());
  3998. chunkGraph.setRuntimeId(runtime, /** @type {ChunkId} */ (chunk.id));
  3999. };
  4000. for (const ep of this.entrypoints.values()) {
  4001. processEntrypoint(ep);
  4002. }
  4003. for (const ep of this.asyncEntrypoints) {
  4004. processEntrypoint(ep);
  4005. }
  4006. }
  4007. sortItemsWithChunkIds() {
  4008. for (const chunkGroup of this.chunkGroups) {
  4009. chunkGroup.sortItems();
  4010. }
  4011. this.errors.sort(compareErrors);
  4012. this.warnings.sort(compareErrors);
  4013. this.children.sort(byNameOrHash);
  4014. }
  4015. summarizeDependencies() {
  4016. for (const child of this.children) {
  4017. this.fileDependencies.addAll(child.fileDependencies);
  4018. this.contextDependencies.addAll(child.contextDependencies);
  4019. this.missingDependencies.addAll(child.missingDependencies);
  4020. this.buildDependencies.addAll(child.buildDependencies);
  4021. }
  4022. for (const module of this.modules) {
  4023. module.addCacheDependencies(
  4024. this.fileDependencies,
  4025. this.contextDependencies,
  4026. this.missingDependencies,
  4027. this.buildDependencies
  4028. );
  4029. }
  4030. }
  4031. createModuleHashes() {
  4032. let statModulesHashed = 0;
  4033. let statModulesFromCache = 0;
  4034. const { chunkGraph, runtimeTemplate, moduleMemCaches2 } = this;
  4035. const { hashFunction, hashDigest, hashDigestLength } = this.outputOptions;
  4036. /** @type {WebpackError[]} */
  4037. const errors = [];
  4038. for (const module of this.modules) {
  4039. const memCache = moduleMemCaches2 && moduleMemCaches2.get(module);
  4040. for (const runtime of chunkGraph.getModuleRuntimes(module)) {
  4041. if (memCache) {
  4042. const digest =
  4043. /** @type {string} */
  4044. (memCache.get(`moduleHash-${getRuntimeKey(runtime)}`));
  4045. if (digest !== undefined) {
  4046. chunkGraph.setModuleHashes(
  4047. module,
  4048. runtime,
  4049. digest,
  4050. digest.slice(0, hashDigestLength)
  4051. );
  4052. statModulesFromCache++;
  4053. continue;
  4054. }
  4055. }
  4056. statModulesHashed++;
  4057. const digest = this._createModuleHash(
  4058. module,
  4059. chunkGraph,
  4060. runtime,
  4061. hashFunction,
  4062. runtimeTemplate,
  4063. hashDigest,
  4064. hashDigestLength,
  4065. errors
  4066. );
  4067. if (memCache) {
  4068. memCache.set(`moduleHash-${getRuntimeKey(runtime)}`, digest);
  4069. }
  4070. }
  4071. }
  4072. if (errors.length > 0) {
  4073. errors.sort(
  4074. compareSelect((err) => err.module, compareModulesByIdentifier)
  4075. );
  4076. for (const error of errors) {
  4077. this.errors.push(error);
  4078. }
  4079. }
  4080. this.logger.log(
  4081. `${statModulesHashed} modules hashed, ${statModulesFromCache} from cache (${
  4082. Math.round(
  4083. (100 * (statModulesHashed + statModulesFromCache)) / this.modules.size
  4084. ) / 100
  4085. } variants per module in average)`
  4086. );
  4087. }
  4088. /**
  4089. * @private
  4090. * @param {Module} module module
  4091. * @param {ChunkGraph} chunkGraph the chunk graph
  4092. * @param {RuntimeSpec} runtime runtime
  4093. * @param {HashFunction} hashFunction hash function
  4094. * @param {RuntimeTemplate} runtimeTemplate runtime template
  4095. * @param {HashDigest} hashDigest hash digest
  4096. * @param {HashDigestLength} hashDigestLength hash digest length
  4097. * @param {WebpackError[]} errors errors
  4098. * @returns {string} module hash digest
  4099. */
  4100. _createModuleHash(
  4101. module,
  4102. chunkGraph,
  4103. runtime,
  4104. hashFunction,
  4105. runtimeTemplate,
  4106. hashDigest,
  4107. hashDigestLength,
  4108. errors
  4109. ) {
  4110. let moduleHashDigest;
  4111. try {
  4112. const moduleHash = createHash(hashFunction);
  4113. module.updateHash(moduleHash, {
  4114. chunkGraph,
  4115. runtime,
  4116. runtimeTemplate
  4117. });
  4118. moduleHashDigest = moduleHash.digest(hashDigest);
  4119. } catch (err) {
  4120. errors.push(new ModuleHashingError(module, /** @type {Error} */ (err)));
  4121. moduleHashDigest = "XXXXXX";
  4122. }
  4123. chunkGraph.setModuleHashes(
  4124. module,
  4125. runtime,
  4126. moduleHashDigest,
  4127. moduleHashDigest.slice(0, hashDigestLength)
  4128. );
  4129. return moduleHashDigest;
  4130. }
  4131. createHash() {
  4132. this.logger.time("hashing: initialize hash");
  4133. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  4134. const runtimeTemplate = this.runtimeTemplate;
  4135. const outputOptions = this.outputOptions;
  4136. const hashFunction = outputOptions.hashFunction;
  4137. const hashDigest = outputOptions.hashDigest;
  4138. const hashDigestLength = outputOptions.hashDigestLength;
  4139. const hash = createHash(hashFunction);
  4140. if (outputOptions.hashSalt) {
  4141. hash.update(outputOptions.hashSalt);
  4142. }
  4143. this.logger.timeEnd("hashing: initialize hash");
  4144. if (this.children.length > 0) {
  4145. this.logger.time("hashing: hash child compilations");
  4146. for (const child of this.children) {
  4147. hash.update(/** @type {string} */ (child.hash));
  4148. }
  4149. this.logger.timeEnd("hashing: hash child compilations");
  4150. }
  4151. if (this.warnings.length > 0) {
  4152. this.logger.time("hashing: hash warnings");
  4153. for (const warning of this.warnings) {
  4154. hash.update(`${warning.message}`);
  4155. }
  4156. this.logger.timeEnd("hashing: hash warnings");
  4157. }
  4158. if (this.errors.length > 0) {
  4159. this.logger.time("hashing: hash errors");
  4160. for (const error of this.errors) {
  4161. hash.update(`${error.message}`);
  4162. }
  4163. this.logger.timeEnd("hashing: hash errors");
  4164. }
  4165. this.logger.time("hashing: sort chunks");
  4166. /*
  4167. * all non-runtime chunks need to be hashes first,
  4168. * since runtime chunk might use their hashes.
  4169. * runtime chunks need to be hashed in the correct order
  4170. * since they may depend on each other (for async entrypoints).
  4171. * So we put all non-runtime chunks first and hash them in any order.
  4172. * And order runtime chunks according to referenced between each other.
  4173. * Chunks need to be in deterministic order since we add hashes to full chunk
  4174. * during these hashing.
  4175. */
  4176. /** @type {Chunk[]} */
  4177. const unorderedRuntimeChunks = [];
  4178. /** @type {Chunk[]} */
  4179. const initialChunks = [];
  4180. /** @type {Chunk[]} */
  4181. const asyncChunks = [];
  4182. for (const c of this.chunks) {
  4183. if (c.hasRuntime()) {
  4184. unorderedRuntimeChunks.push(c);
  4185. } else if (c.canBeInitial()) {
  4186. initialChunks.push(c);
  4187. } else {
  4188. asyncChunks.push(c);
  4189. }
  4190. }
  4191. unorderedRuntimeChunks.sort(byId);
  4192. initialChunks.sort(byId);
  4193. asyncChunks.sort(byId);
  4194. /** @typedef {{ chunk: Chunk, referencedBy: RuntimeChunkInfo[], remaining: number }} RuntimeChunkInfo */
  4195. /** @type {Map<Chunk, RuntimeChunkInfo>} */
  4196. const runtimeChunksMap = new Map();
  4197. for (const chunk of unorderedRuntimeChunks) {
  4198. runtimeChunksMap.set(chunk, {
  4199. chunk,
  4200. referencedBy: [],
  4201. remaining: 0
  4202. });
  4203. }
  4204. let remaining = 0;
  4205. for (const info of runtimeChunksMap.values()) {
  4206. for (const other of new Set(
  4207. [...info.chunk.getAllReferencedAsyncEntrypoints()].map(
  4208. (e) => e.chunks[e.chunks.length - 1]
  4209. )
  4210. )) {
  4211. const otherInfo =
  4212. /** @type {RuntimeChunkInfo} */
  4213. (runtimeChunksMap.get(other));
  4214. otherInfo.referencedBy.push(info);
  4215. info.remaining++;
  4216. remaining++;
  4217. }
  4218. }
  4219. /** @type {Chunk[]} */
  4220. const runtimeChunks = [];
  4221. for (const info of runtimeChunksMap.values()) {
  4222. if (info.remaining === 0) {
  4223. runtimeChunks.push(info.chunk);
  4224. }
  4225. }
  4226. // If there are any references between chunks
  4227. // make sure to follow these chains
  4228. if (remaining > 0) {
  4229. const readyChunks = [];
  4230. for (const chunk of runtimeChunks) {
  4231. const hasFullHashModules =
  4232. chunkGraph.getNumberOfChunkFullHashModules(chunk) !== 0;
  4233. const info =
  4234. /** @type {RuntimeChunkInfo} */
  4235. (runtimeChunksMap.get(chunk));
  4236. for (const otherInfo of info.referencedBy) {
  4237. if (hasFullHashModules) {
  4238. chunkGraph.upgradeDependentToFullHashModules(otherInfo.chunk);
  4239. }
  4240. remaining--;
  4241. if (--otherInfo.remaining === 0) {
  4242. readyChunks.push(otherInfo.chunk);
  4243. }
  4244. }
  4245. if (readyChunks.length > 0) {
  4246. // This ensures deterministic ordering, since referencedBy is non-deterministic
  4247. readyChunks.sort(byId);
  4248. for (const c of readyChunks) runtimeChunks.push(c);
  4249. readyChunks.length = 0;
  4250. }
  4251. }
  4252. }
  4253. // If there are still remaining references we have cycles and want to create a warning
  4254. if (remaining > 0) {
  4255. const circularRuntimeChunkInfo = [];
  4256. for (const info of runtimeChunksMap.values()) {
  4257. if (info.remaining !== 0) {
  4258. circularRuntimeChunkInfo.push(info);
  4259. }
  4260. }
  4261. circularRuntimeChunkInfo.sort(compareSelect((i) => i.chunk, byId));
  4262. const err =
  4263. new WebpackError(`Circular dependency between chunks with runtime (${Array.from(
  4264. circularRuntimeChunkInfo,
  4265. (c) => c.chunk.name || c.chunk.id
  4266. ).join(", ")})
  4267. This prevents using hashes of each other and should be avoided.`);
  4268. err.chunk = circularRuntimeChunkInfo[0].chunk;
  4269. this.warnings.push(err);
  4270. for (const i of circularRuntimeChunkInfo) runtimeChunks.push(i.chunk);
  4271. }
  4272. this.logger.timeEnd("hashing: sort chunks");
  4273. const fullHashChunks = new Set();
  4274. /** @type {CodeGenerationJobs} */
  4275. const codeGenerationJobs = [];
  4276. /** @type {Map<string, Map<Module, CodeGenerationJob>>} */
  4277. const codeGenerationJobsMap = new Map();
  4278. /** @type {WebpackError[]} */
  4279. const errors = [];
  4280. /**
  4281. * @param {Chunk} chunk chunk
  4282. */
  4283. const processChunk = (chunk) => {
  4284. // Last minute module hash generation for modules that depend on chunk hashes
  4285. this.logger.time("hashing: hash runtime modules");
  4286. const runtime = chunk.runtime;
  4287. for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
  4288. if (!chunkGraph.hasModuleHashes(module, runtime)) {
  4289. const hash = this._createModuleHash(
  4290. module,
  4291. chunkGraph,
  4292. runtime,
  4293. hashFunction,
  4294. runtimeTemplate,
  4295. hashDigest,
  4296. hashDigestLength,
  4297. errors
  4298. );
  4299. let hashMap = codeGenerationJobsMap.get(hash);
  4300. if (hashMap) {
  4301. const moduleJob = hashMap.get(module);
  4302. if (moduleJob) {
  4303. moduleJob.runtimes.push(runtime);
  4304. continue;
  4305. }
  4306. } else {
  4307. hashMap = new Map();
  4308. codeGenerationJobsMap.set(hash, hashMap);
  4309. }
  4310. const job = {
  4311. module,
  4312. hash,
  4313. runtime,
  4314. runtimes: [runtime]
  4315. };
  4316. hashMap.set(module, job);
  4317. codeGenerationJobs.push(job);
  4318. }
  4319. }
  4320. this.logger.timeAggregate("hashing: hash runtime modules");
  4321. try {
  4322. this.logger.time("hashing: hash chunks");
  4323. const chunkHash = createHash(hashFunction);
  4324. if (outputOptions.hashSalt) {
  4325. chunkHash.update(outputOptions.hashSalt);
  4326. }
  4327. chunk.updateHash(chunkHash, chunkGraph);
  4328. this.hooks.chunkHash.call(chunk, chunkHash, {
  4329. chunkGraph,
  4330. codeGenerationResults:
  4331. /** @type {CodeGenerationResults} */
  4332. (this.codeGenerationResults),
  4333. moduleGraph: this.moduleGraph,
  4334. runtimeTemplate: this.runtimeTemplate
  4335. });
  4336. const chunkHashDigest = chunkHash.digest(hashDigest);
  4337. hash.update(chunkHashDigest);
  4338. chunk.hash = chunkHashDigest;
  4339. chunk.renderedHash = chunk.hash.slice(0, hashDigestLength);
  4340. const fullHashModules =
  4341. chunkGraph.getChunkFullHashModulesIterable(chunk);
  4342. if (fullHashModules) {
  4343. fullHashChunks.add(chunk);
  4344. } else {
  4345. this.hooks.contentHash.call(chunk);
  4346. }
  4347. } catch (err) {
  4348. this.errors.push(
  4349. new ChunkRenderError(chunk, "", /** @type {Error} */ (err))
  4350. );
  4351. }
  4352. this.logger.timeAggregate("hashing: hash chunks");
  4353. };
  4354. for (const chunk of asyncChunks) processChunk(chunk);
  4355. for (const chunk of runtimeChunks) processChunk(chunk);
  4356. for (const chunk of initialChunks) processChunk(chunk);
  4357. if (errors.length > 0) {
  4358. errors.sort(
  4359. compareSelect((err) => err.module, compareModulesByIdentifier)
  4360. );
  4361. for (const error of errors) {
  4362. this.errors.push(error);
  4363. }
  4364. }
  4365. this.logger.timeAggregateEnd("hashing: hash runtime modules");
  4366. this.logger.timeAggregateEnd("hashing: hash chunks");
  4367. this.logger.time("hashing: hash digest");
  4368. this.hooks.fullHash.call(hash);
  4369. this.fullHash = hash.digest(hashDigest);
  4370. this.hash = this.fullHash.slice(0, hashDigestLength);
  4371. this.logger.timeEnd("hashing: hash digest");
  4372. this.logger.time("hashing: process full hash modules");
  4373. for (const chunk of fullHashChunks) {
  4374. for (const module of /** @type {Iterable<RuntimeModule>} */ (
  4375. chunkGraph.getChunkFullHashModulesIterable(chunk)
  4376. )) {
  4377. const moduleHash = createHash(hashFunction);
  4378. module.updateHash(moduleHash, {
  4379. chunkGraph,
  4380. runtime: chunk.runtime,
  4381. runtimeTemplate
  4382. });
  4383. const moduleHashDigest = moduleHash.digest(hashDigest);
  4384. const oldHash = chunkGraph.getModuleHash(module, chunk.runtime);
  4385. chunkGraph.setModuleHashes(
  4386. module,
  4387. chunk.runtime,
  4388. moduleHashDigest,
  4389. moduleHashDigest.slice(0, hashDigestLength)
  4390. );
  4391. /** @type {CodeGenerationJob} */
  4392. (
  4393. /** @type {Map<Module, CodeGenerationJob>} */
  4394. (codeGenerationJobsMap.get(oldHash)).get(module)
  4395. ).hash = moduleHashDigest;
  4396. }
  4397. const chunkHash = createHash(hashFunction);
  4398. chunkHash.update(chunk.hash);
  4399. chunkHash.update(this.hash);
  4400. const chunkHashDigest = chunkHash.digest(hashDigest);
  4401. chunk.hash = chunkHashDigest;
  4402. chunk.renderedHash = chunk.hash.slice(0, hashDigestLength);
  4403. this.hooks.contentHash.call(chunk);
  4404. }
  4405. this.logger.timeEnd("hashing: process full hash modules");
  4406. return codeGenerationJobs;
  4407. }
  4408. /**
  4409. * @param {string} file file name
  4410. * @param {Source} source asset source
  4411. * @param {AssetInfo} assetInfo extra asset information
  4412. * @returns {void}
  4413. */
  4414. emitAsset(file, source, assetInfo = {}) {
  4415. if (this.assets[file]) {
  4416. if (!isSourceEqual(this.assets[file], source)) {
  4417. this.errors.push(
  4418. new WebpackError(
  4419. `Conflict: Multiple assets emit different content to the same filename ${file}${
  4420. assetInfo.sourceFilename
  4421. ? `. Original source ${assetInfo.sourceFilename}`
  4422. : ""
  4423. }`
  4424. )
  4425. );
  4426. this.assets[file] = source;
  4427. this._setAssetInfo(file, assetInfo);
  4428. return;
  4429. }
  4430. const oldInfo = this.assetsInfo.get(file);
  4431. const newInfo = { ...oldInfo, ...assetInfo };
  4432. this._setAssetInfo(file, newInfo, oldInfo);
  4433. return;
  4434. }
  4435. this.assets[file] = source;
  4436. this._setAssetInfo(file, assetInfo, undefined);
  4437. }
  4438. /**
  4439. * @private
  4440. * @param {string} file file name
  4441. * @param {AssetInfo=} newInfo new asset information
  4442. * @param {AssetInfo=} oldInfo old asset information
  4443. */
  4444. _setAssetInfo(file, newInfo, oldInfo = this.assetsInfo.get(file)) {
  4445. if (newInfo === undefined) {
  4446. this.assetsInfo.delete(file);
  4447. } else {
  4448. this.assetsInfo.set(file, newInfo);
  4449. }
  4450. const oldRelated = oldInfo && oldInfo.related;
  4451. const newRelated = newInfo && newInfo.related;
  4452. if (oldRelated) {
  4453. for (const key of Object.keys(oldRelated)) {
  4454. /**
  4455. * @param {string} name name
  4456. */
  4457. const remove = (name) => {
  4458. const relatedIn = this._assetsRelatedIn.get(name);
  4459. if (relatedIn === undefined) return;
  4460. const entry = relatedIn.get(key);
  4461. if (entry === undefined) return;
  4462. entry.delete(file);
  4463. if (entry.size !== 0) return;
  4464. relatedIn.delete(key);
  4465. if (relatedIn.size === 0) this._assetsRelatedIn.delete(name);
  4466. };
  4467. const entry = oldRelated[key];
  4468. if (Array.isArray(entry)) {
  4469. for (const name of entry) {
  4470. remove(name);
  4471. }
  4472. } else if (entry) {
  4473. remove(entry);
  4474. }
  4475. }
  4476. }
  4477. if (newRelated) {
  4478. for (const key of Object.keys(newRelated)) {
  4479. /**
  4480. * @param {string} name name
  4481. */
  4482. const add = (name) => {
  4483. let relatedIn = this._assetsRelatedIn.get(name);
  4484. if (relatedIn === undefined) {
  4485. this._assetsRelatedIn.set(name, (relatedIn = new Map()));
  4486. }
  4487. let entry = relatedIn.get(key);
  4488. if (entry === undefined) {
  4489. relatedIn.set(key, (entry = new Set()));
  4490. }
  4491. entry.add(file);
  4492. };
  4493. const entry = newRelated[key];
  4494. if (Array.isArray(entry)) {
  4495. for (const name of entry) {
  4496. add(name);
  4497. }
  4498. } else if (entry) {
  4499. add(entry);
  4500. }
  4501. }
  4502. }
  4503. }
  4504. /**
  4505. * @param {string} file file name
  4506. * @param {Source | ((source: Source) => Source)} newSourceOrFunction new asset source or function converting old to new
  4507. * @param {(AssetInfo | ((assetInfo?: AssetInfo) => AssetInfo | undefined)) | undefined} assetInfoUpdateOrFunction new asset info or function converting old to new
  4508. */
  4509. updateAsset(
  4510. file,
  4511. newSourceOrFunction,
  4512. assetInfoUpdateOrFunction = undefined
  4513. ) {
  4514. if (!this.assets[file]) {
  4515. throw new Error(
  4516. `Called Compilation.updateAsset for not existing filename ${file}`
  4517. );
  4518. }
  4519. this.assets[file] =
  4520. typeof newSourceOrFunction === "function"
  4521. ? newSourceOrFunction(this.assets[file])
  4522. : newSourceOrFunction;
  4523. if (assetInfoUpdateOrFunction !== undefined) {
  4524. const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO;
  4525. if (typeof assetInfoUpdateOrFunction === "function") {
  4526. this._setAssetInfo(file, assetInfoUpdateOrFunction(oldInfo), oldInfo);
  4527. } else {
  4528. this._setAssetInfo(
  4529. file,
  4530. cachedCleverMerge(oldInfo, assetInfoUpdateOrFunction),
  4531. oldInfo
  4532. );
  4533. }
  4534. }
  4535. }
  4536. /**
  4537. * @param {string} file file name
  4538. * @param {string} newFile the new name of file
  4539. */
  4540. renameAsset(file, newFile) {
  4541. const source = this.assets[file];
  4542. if (!source) {
  4543. throw new Error(
  4544. `Called Compilation.renameAsset for not existing filename ${file}`
  4545. );
  4546. }
  4547. if (this.assets[newFile] && !isSourceEqual(this.assets[file], source)) {
  4548. this.errors.push(
  4549. new WebpackError(
  4550. `Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content`
  4551. )
  4552. );
  4553. }
  4554. const assetInfo = this.assetsInfo.get(file);
  4555. // Update related in all other assets
  4556. const relatedInInfo = this._assetsRelatedIn.get(file);
  4557. if (relatedInInfo) {
  4558. for (const [key, assets] of relatedInInfo) {
  4559. for (const name of assets) {
  4560. const info = this.assetsInfo.get(name);
  4561. if (!info) continue;
  4562. const related = info.related;
  4563. if (!related) continue;
  4564. const entry = related[key];
  4565. let newEntry;
  4566. if (Array.isArray(entry)) {
  4567. newEntry = entry.map((x) => (x === file ? newFile : x));
  4568. } else if (entry === file) {
  4569. newEntry = newFile;
  4570. } else {
  4571. continue;
  4572. }
  4573. this.assetsInfo.set(name, {
  4574. ...info,
  4575. related: {
  4576. ...related,
  4577. [key]: newEntry
  4578. }
  4579. });
  4580. }
  4581. }
  4582. }
  4583. this._setAssetInfo(file, undefined, assetInfo);
  4584. this._setAssetInfo(newFile, assetInfo);
  4585. delete this.assets[file];
  4586. this.assets[newFile] = source;
  4587. for (const chunk of this.chunks) {
  4588. {
  4589. const size = chunk.files.size;
  4590. chunk.files.delete(file);
  4591. if (size !== chunk.files.size) {
  4592. chunk.files.add(newFile);
  4593. }
  4594. }
  4595. {
  4596. const size = chunk.auxiliaryFiles.size;
  4597. chunk.auxiliaryFiles.delete(file);
  4598. if (size !== chunk.auxiliaryFiles.size) {
  4599. chunk.auxiliaryFiles.add(newFile);
  4600. }
  4601. }
  4602. }
  4603. }
  4604. /**
  4605. * @param {string} file file name
  4606. */
  4607. deleteAsset(file) {
  4608. if (!this.assets[file]) {
  4609. return;
  4610. }
  4611. delete this.assets[file];
  4612. const assetInfo = this.assetsInfo.get(file);
  4613. this._setAssetInfo(file, undefined, assetInfo);
  4614. const related = assetInfo && assetInfo.related;
  4615. if (related) {
  4616. for (const key of Object.keys(related)) {
  4617. /**
  4618. * @param {string} file file
  4619. */
  4620. const checkUsedAndDelete = (file) => {
  4621. if (!this._assetsRelatedIn.has(file)) {
  4622. this.deleteAsset(file);
  4623. }
  4624. };
  4625. const items = related[key];
  4626. if (Array.isArray(items)) {
  4627. for (const file of items) {
  4628. checkUsedAndDelete(file);
  4629. }
  4630. } else if (items) {
  4631. checkUsedAndDelete(items);
  4632. }
  4633. }
  4634. }
  4635. // TODO If this becomes a performance problem
  4636. // store a reverse mapping from asset to chunk
  4637. for (const chunk of this.chunks) {
  4638. chunk.files.delete(file);
  4639. chunk.auxiliaryFiles.delete(file);
  4640. }
  4641. }
  4642. getAssets() {
  4643. /** @type {Readonly<Asset>[]} */
  4644. const array = [];
  4645. for (const assetName of Object.keys(this.assets)) {
  4646. if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) {
  4647. array.push({
  4648. name: assetName,
  4649. source: this.assets[assetName],
  4650. info: this.assetsInfo.get(assetName) || EMPTY_ASSET_INFO
  4651. });
  4652. }
  4653. }
  4654. return array;
  4655. }
  4656. /**
  4657. * @param {string} name the name of the asset
  4658. * @returns {Readonly<Asset> | undefined} the asset or undefined when not found
  4659. */
  4660. getAsset(name) {
  4661. if (!Object.prototype.hasOwnProperty.call(this.assets, name)) return;
  4662. return {
  4663. name,
  4664. source: this.assets[name],
  4665. info: this.assetsInfo.get(name) || EMPTY_ASSET_INFO
  4666. };
  4667. }
  4668. clearAssets() {
  4669. for (const chunk of this.chunks) {
  4670. chunk.files.clear();
  4671. chunk.auxiliaryFiles.clear();
  4672. }
  4673. }
  4674. createModuleAssets() {
  4675. const { chunkGraph } = this;
  4676. for (const module of this.modules) {
  4677. const buildInfo = /** @type {BuildInfo} */ (module.buildInfo);
  4678. if (buildInfo.assets) {
  4679. const assetsInfo = buildInfo.assetsInfo;
  4680. for (const assetName of Object.keys(buildInfo.assets)) {
  4681. const fileName = this.getPath(assetName, {
  4682. chunkGraph: this.chunkGraph,
  4683. module
  4684. });
  4685. for (const chunk of chunkGraph.getModuleChunksIterable(module)) {
  4686. chunk.auxiliaryFiles.add(fileName);
  4687. }
  4688. this.emitAsset(
  4689. fileName,
  4690. buildInfo.assets[assetName],
  4691. assetsInfo ? assetsInfo.get(assetName) : undefined
  4692. );
  4693. this.hooks.moduleAsset.call(module, fileName);
  4694. }
  4695. }
  4696. }
  4697. }
  4698. /**
  4699. * @param {RenderManifestOptions} options options object
  4700. * @returns {RenderManifestEntry[]} manifest entries
  4701. */
  4702. getRenderManifest(options) {
  4703. return this.hooks.renderManifest.call([], options);
  4704. }
  4705. /**
  4706. * @param {Callback} callback signals when the call finishes
  4707. * @returns {void}
  4708. */
  4709. createChunkAssets(callback) {
  4710. const outputOptions = this.outputOptions;
  4711. const cachedSourceMap = new WeakMap();
  4712. /** @type {Map<string, {hash: string, source: Source, chunk: Chunk}>} */
  4713. const alreadyWrittenFiles = new Map();
  4714. asyncLib.forEachLimit(
  4715. this.chunks,
  4716. 15,
  4717. (chunk, callback) => {
  4718. /** @type {RenderManifestEntry[]} */
  4719. let manifest;
  4720. try {
  4721. manifest = this.getRenderManifest({
  4722. chunk,
  4723. hash: /** @type {string} */ (this.hash),
  4724. fullHash: /** @type {string} */ (this.fullHash),
  4725. outputOptions,
  4726. codeGenerationResults:
  4727. /** @type {CodeGenerationResults} */
  4728. (this.codeGenerationResults),
  4729. moduleTemplates: this.moduleTemplates,
  4730. dependencyTemplates: this.dependencyTemplates,
  4731. chunkGraph: this.chunkGraph,
  4732. moduleGraph: this.moduleGraph,
  4733. runtimeTemplate: this.runtimeTemplate
  4734. });
  4735. } catch (err) {
  4736. this.errors.push(
  4737. new ChunkRenderError(chunk, "", /** @type {Error} */ (err))
  4738. );
  4739. return callback();
  4740. }
  4741. asyncLib.each(
  4742. manifest,
  4743. (fileManifest, callback) => {
  4744. const ident = fileManifest.identifier;
  4745. const usedHash = /** @type {string} */ (fileManifest.hash);
  4746. const assetCacheItem = this._assetsCache.getItemCache(
  4747. ident,
  4748. usedHash
  4749. );
  4750. assetCacheItem.get((err, sourceFromCache) => {
  4751. /** @type {TemplatePath} */
  4752. let filenameTemplate;
  4753. /** @type {string} */
  4754. let file;
  4755. /** @type {AssetInfo} */
  4756. let assetInfo;
  4757. let inTry = true;
  4758. /**
  4759. * @param {Error} err error
  4760. * @returns {void}
  4761. */
  4762. const errorAndCallback = (err) => {
  4763. const filename =
  4764. file ||
  4765. (typeof file === "string"
  4766. ? file
  4767. : typeof filenameTemplate === "string"
  4768. ? filenameTemplate
  4769. : "");
  4770. this.errors.push(new ChunkRenderError(chunk, filename, err));
  4771. inTry = false;
  4772. return callback();
  4773. };
  4774. try {
  4775. if ("filename" in fileManifest) {
  4776. file = fileManifest.filename;
  4777. assetInfo = fileManifest.info;
  4778. } else {
  4779. filenameTemplate = fileManifest.filenameTemplate;
  4780. const pathAndInfo = this.getPathWithInfo(
  4781. filenameTemplate,
  4782. fileManifest.pathOptions
  4783. );
  4784. file = pathAndInfo.path;
  4785. assetInfo = fileManifest.info
  4786. ? {
  4787. ...pathAndInfo.info,
  4788. ...fileManifest.info
  4789. }
  4790. : pathAndInfo.info;
  4791. }
  4792. if (err) {
  4793. return errorAndCallback(err);
  4794. }
  4795. let source = sourceFromCache;
  4796. // check if the same filename was already written by another chunk
  4797. const alreadyWritten = alreadyWrittenFiles.get(file);
  4798. if (alreadyWritten !== undefined) {
  4799. if (alreadyWritten.hash !== usedHash) {
  4800. inTry = false;
  4801. return callback(
  4802. new WebpackError(
  4803. `Conflict: Multiple chunks emit assets to the same filename ${file}` +
  4804. ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})`
  4805. )
  4806. );
  4807. }
  4808. source = alreadyWritten.source;
  4809. } else if (!source) {
  4810. // render the asset
  4811. source = fileManifest.render();
  4812. // Ensure that source is a cached source to avoid additional cost because of repeated access
  4813. if (!(source instanceof CachedSource)) {
  4814. const cacheEntry = cachedSourceMap.get(source);
  4815. if (cacheEntry) {
  4816. source = cacheEntry;
  4817. } else {
  4818. const cachedSource = new CachedSource(source);
  4819. cachedSourceMap.set(source, cachedSource);
  4820. source = cachedSource;
  4821. }
  4822. }
  4823. }
  4824. this.emitAsset(file, source, assetInfo);
  4825. if (fileManifest.auxiliary) {
  4826. chunk.auxiliaryFiles.add(file);
  4827. } else {
  4828. chunk.files.add(file);
  4829. }
  4830. this.hooks.chunkAsset.call(chunk, file);
  4831. alreadyWrittenFiles.set(file, {
  4832. hash: usedHash,
  4833. source,
  4834. chunk
  4835. });
  4836. if (source !== sourceFromCache) {
  4837. assetCacheItem.store(source, (err) => {
  4838. if (err) return errorAndCallback(err);
  4839. inTry = false;
  4840. return callback();
  4841. });
  4842. } else {
  4843. inTry = false;
  4844. callback();
  4845. }
  4846. } catch (err) {
  4847. if (!inTry) throw err;
  4848. errorAndCallback(/** @type {Error} */ (err));
  4849. }
  4850. });
  4851. },
  4852. callback
  4853. );
  4854. },
  4855. callback
  4856. );
  4857. }
  4858. /**
  4859. * @param {TemplatePath} filename used to get asset path with hash
  4860. * @param {PathData} data context data
  4861. * @returns {string} interpolated path
  4862. */
  4863. getPath(filename, data = {}) {
  4864. if (!data.hash) {
  4865. data = {
  4866. hash: this.hash,
  4867. ...data
  4868. };
  4869. }
  4870. return this.getAssetPath(filename, data);
  4871. }
  4872. /**
  4873. * @param {TemplatePath} filename used to get asset path with hash
  4874. * @param {PathData} data context data
  4875. * @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info
  4876. */
  4877. getPathWithInfo(filename, data = {}) {
  4878. if (!data.hash) {
  4879. data = {
  4880. hash: this.hash,
  4881. ...data
  4882. };
  4883. }
  4884. return this.getAssetPathWithInfo(filename, data);
  4885. }
  4886. /**
  4887. * @param {TemplatePath} filename used to get asset path with hash
  4888. * @param {PathData} data context data
  4889. * @returns {string} interpolated path
  4890. */
  4891. getAssetPath(filename, data) {
  4892. return this.hooks.assetPath.call(
  4893. typeof filename === "function" ? filename(data) : filename,
  4894. data,
  4895. undefined
  4896. );
  4897. }
  4898. /**
  4899. * @param {TemplatePath} filename used to get asset path with hash
  4900. * @param {PathData} data context data
  4901. * @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info
  4902. */
  4903. getAssetPathWithInfo(filename, data) {
  4904. const assetInfo = {};
  4905. // TODO webpack 5: refactor assetPath hook to receive { path, info } object
  4906. const newPath = this.hooks.assetPath.call(
  4907. typeof filename === "function" ? filename(data, assetInfo) : filename,
  4908. data,
  4909. assetInfo
  4910. );
  4911. return { path: newPath, info: assetInfo };
  4912. }
  4913. getWarnings() {
  4914. return this.hooks.processWarnings.call(this.warnings);
  4915. }
  4916. getErrors() {
  4917. return this.hooks.processErrors.call(this.errors);
  4918. }
  4919. /**
  4920. * This function allows you to run another instance of webpack inside of webpack however as
  4921. * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins
  4922. * from parent (or top level compiler) and creates a child Compilation
  4923. * @param {string} name name of the child compiler
  4924. * @param {Partial<OutputOptions>=} outputOptions // Need to convert config schema to types for this
  4925. * @param {Plugins=} plugins webpack plugins that will be applied
  4926. * @returns {Compiler} creates a child Compiler instance
  4927. */
  4928. createChildCompiler(name, outputOptions, plugins) {
  4929. const idx = this.childrenCounters[name] || 0;
  4930. this.childrenCounters[name] = idx + 1;
  4931. return this.compiler.createChildCompiler(
  4932. this,
  4933. name,
  4934. idx,
  4935. outputOptions,
  4936. plugins
  4937. );
  4938. }
  4939. /**
  4940. * @param {Module} module the module
  4941. * @param {ExecuteModuleOptions} options options
  4942. * @param {ExecuteModuleCallback} callback callback
  4943. */
  4944. executeModule(module, options, callback) {
  4945. // Aggregate all referenced modules and ensure they are ready
  4946. const modules = new Set([module]);
  4947. processAsyncTree(
  4948. modules,
  4949. 10,
  4950. (module, push, callback) => {
  4951. this.buildQueue.waitFor(module, (err) => {
  4952. if (err) return callback(err);
  4953. this.processDependenciesQueue.waitFor(module, (err) => {
  4954. if (err) return callback(err);
  4955. for (const { module: m } of this.moduleGraph.getOutgoingConnections(
  4956. module
  4957. )) {
  4958. const size = modules.size;
  4959. modules.add(m);
  4960. if (modules.size !== size) push(m);
  4961. }
  4962. callback();
  4963. });
  4964. });
  4965. },
  4966. (err) => {
  4967. if (err) return callback(/** @type {WebpackError} */ (err));
  4968. // Create new chunk graph, chunk and entrypoint for the build time execution
  4969. const chunkGraph = new ChunkGraph(
  4970. this.moduleGraph,
  4971. this.outputOptions.hashFunction
  4972. );
  4973. const runtime = "build time";
  4974. const { hashFunction, hashDigest, hashDigestLength } =
  4975. this.outputOptions;
  4976. const runtimeTemplate = this.runtimeTemplate;
  4977. const chunk = new Chunk("build time chunk", this._backCompat);
  4978. chunk.id = /** @type {ChunkId} */ (chunk.name);
  4979. chunk.ids = [chunk.id];
  4980. chunk.runtime = runtime;
  4981. const entrypoint = new Entrypoint({
  4982. runtime,
  4983. chunkLoading: false,
  4984. ...options.entryOptions
  4985. });
  4986. chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint);
  4987. connectChunkGroupAndChunk(entrypoint, chunk);
  4988. entrypoint.setRuntimeChunk(chunk);
  4989. entrypoint.setEntrypointChunk(chunk);
  4990. const chunks = new Set([chunk]);
  4991. // Assign ids to modules and modules to the chunk
  4992. for (const module of modules) {
  4993. const id = module.identifier();
  4994. chunkGraph.setModuleId(module, id);
  4995. chunkGraph.connectChunkAndModule(chunk, module);
  4996. }
  4997. /** @type {WebpackError[]} */
  4998. const errors = [];
  4999. // Hash modules
  5000. for (const module of modules) {
  5001. this._createModuleHash(
  5002. module,
  5003. chunkGraph,
  5004. runtime,
  5005. hashFunction,
  5006. runtimeTemplate,
  5007. hashDigest,
  5008. hashDigestLength,
  5009. errors
  5010. );
  5011. }
  5012. const codeGenerationResults = new CodeGenerationResults(
  5013. this.outputOptions.hashFunction
  5014. );
  5015. /**
  5016. * @param {Module} module the module
  5017. * @param {Callback} callback callback
  5018. * @returns {void}
  5019. */
  5020. const codeGen = (module, callback) => {
  5021. this._codeGenerationModule(
  5022. module,
  5023. runtime,
  5024. [runtime],
  5025. chunkGraph.getModuleHash(module, runtime),
  5026. this.dependencyTemplates,
  5027. chunkGraph,
  5028. this.moduleGraph,
  5029. runtimeTemplate,
  5030. errors,
  5031. codeGenerationResults,
  5032. (err, _codeGenerated) => {
  5033. callback(err);
  5034. }
  5035. );
  5036. };
  5037. const reportErrors = () => {
  5038. if (errors.length > 0) {
  5039. errors.sort(
  5040. compareSelect((err) => err.module, compareModulesByIdentifier)
  5041. );
  5042. for (const error of errors) {
  5043. this.errors.push(error);
  5044. }
  5045. errors.length = 0;
  5046. }
  5047. };
  5048. // Generate code for all aggregated modules
  5049. asyncLib.eachLimit(modules, 10, codeGen, (err) => {
  5050. if (err) return callback(err);
  5051. reportErrors();
  5052. // for backward-compat temporary set the chunk graph
  5053. // TODO webpack 6
  5054. const old = this.chunkGraph;
  5055. this.chunkGraph = chunkGraph;
  5056. this.processRuntimeRequirements({
  5057. chunkGraph,
  5058. modules,
  5059. chunks,
  5060. codeGenerationResults,
  5061. chunkGraphEntries: chunks
  5062. });
  5063. this.chunkGraph = old;
  5064. const runtimeModules =
  5065. chunkGraph.getChunkRuntimeModulesIterable(chunk);
  5066. // Hash runtime modules
  5067. for (const module of runtimeModules) {
  5068. modules.add(module);
  5069. this._createModuleHash(
  5070. module,
  5071. chunkGraph,
  5072. runtime,
  5073. hashFunction,
  5074. runtimeTemplate,
  5075. hashDigest,
  5076. hashDigestLength,
  5077. errors
  5078. );
  5079. }
  5080. // Generate code for all runtime modules
  5081. asyncLib.eachLimit(runtimeModules, 10, codeGen, (err) => {
  5082. if (err) return callback(err);
  5083. reportErrors();
  5084. /** @type {Map<Module, ExecuteModuleArgument>} */
  5085. const moduleArgumentsMap = new Map();
  5086. /** @type {Map<string, ExecuteModuleArgument>} */
  5087. const moduleArgumentsById = new Map();
  5088. /** @type {ExecuteModuleResult["fileDependencies"]} */
  5089. const fileDependencies = new LazySet();
  5090. /** @type {ExecuteModuleResult["contextDependencies"]} */
  5091. const contextDependencies = new LazySet();
  5092. /** @type {ExecuteModuleResult["missingDependencies"]} */
  5093. const missingDependencies = new LazySet();
  5094. /** @type {ExecuteModuleResult["buildDependencies"]} */
  5095. const buildDependencies = new LazySet();
  5096. /** @type {ExecuteModuleResult["assets"]} */
  5097. const assets = new Map();
  5098. let cacheable = true;
  5099. /** @type {ExecuteModuleContext} */
  5100. const context = {
  5101. assets,
  5102. __webpack_require__: undefined,
  5103. chunk,
  5104. chunkGraph
  5105. };
  5106. // Prepare execution
  5107. asyncLib.eachLimit(
  5108. modules,
  5109. 10,
  5110. (module, callback) => {
  5111. const codeGenerationResult = codeGenerationResults.get(
  5112. module,
  5113. runtime
  5114. );
  5115. /** @type {ExecuteModuleArgument} */
  5116. const moduleArgument = {
  5117. module,
  5118. codeGenerationResult,
  5119. moduleObject: undefined
  5120. };
  5121. moduleArgumentsMap.set(module, moduleArgument);
  5122. moduleArgumentsById.set(module.identifier(), moduleArgument);
  5123. module.addCacheDependencies(
  5124. fileDependencies,
  5125. contextDependencies,
  5126. missingDependencies,
  5127. buildDependencies
  5128. );
  5129. if (
  5130. /** @type {BuildInfo} */ (module.buildInfo).cacheable ===
  5131. false
  5132. ) {
  5133. cacheable = false;
  5134. }
  5135. if (module.buildInfo && module.buildInfo.assets) {
  5136. const { assets: moduleAssets, assetsInfo } = module.buildInfo;
  5137. for (const assetName of Object.keys(moduleAssets)) {
  5138. assets.set(assetName, {
  5139. source: moduleAssets[assetName],
  5140. info: assetsInfo ? assetsInfo.get(assetName) : undefined
  5141. });
  5142. }
  5143. }
  5144. this.hooks.prepareModuleExecution.callAsync(
  5145. moduleArgument,
  5146. context,
  5147. callback
  5148. );
  5149. },
  5150. (err) => {
  5151. if (err) return callback(err);
  5152. /** @type {ExecuteModuleExports | undefined} */
  5153. let exports;
  5154. try {
  5155. const {
  5156. strictModuleErrorHandling,
  5157. strictModuleExceptionHandling
  5158. } = this.outputOptions;
  5159. /** @type {WebpackRequire} */
  5160. const __webpack_require__ = (id) => {
  5161. const cached = moduleCache[id];
  5162. if (cached !== undefined) {
  5163. if (cached.error) throw cached.error;
  5164. return cached.exports;
  5165. }
  5166. const moduleArgument = moduleArgumentsById.get(id);
  5167. return __webpack_require_module__(
  5168. /** @type {ExecuteModuleArgument} */
  5169. (moduleArgument),
  5170. id
  5171. );
  5172. };
  5173. const interceptModuleExecution = (__webpack_require__[
  5174. /** @type {"i"} */
  5175. (
  5176. RuntimeGlobals.interceptModuleExecution.replace(
  5177. `${RuntimeGlobals.require}.`,
  5178. ""
  5179. )
  5180. )
  5181. ] = /** @type {NonNullable<WebpackRequire["i"]>} */ ([]));
  5182. const moduleCache = (__webpack_require__[
  5183. /** @type {"c"} */ (
  5184. RuntimeGlobals.moduleCache.replace(
  5185. `${RuntimeGlobals.require}.`,
  5186. ""
  5187. )
  5188. )
  5189. ] = /** @type {NonNullable<WebpackRequire["c"]>} */ ({}));
  5190. context.__webpack_require__ = __webpack_require__;
  5191. /**
  5192. * @param {ExecuteModuleArgument} moduleArgument the module argument
  5193. * @param {string=} id id
  5194. * @returns {ExecuteModuleExports} exports
  5195. */
  5196. const __webpack_require_module__ = (moduleArgument, id) => {
  5197. /** @type {ExecuteOptions} */
  5198. const execOptions = {
  5199. id,
  5200. module: {
  5201. id,
  5202. exports: {},
  5203. loaded: false,
  5204. error: undefined
  5205. },
  5206. require: __webpack_require__
  5207. };
  5208. for (const handler of interceptModuleExecution) {
  5209. handler(execOptions);
  5210. }
  5211. const module = moduleArgument.module;
  5212. this.buildTimeExecutedModules.add(module);
  5213. const moduleObject = execOptions.module;
  5214. moduleArgument.moduleObject = moduleObject;
  5215. try {
  5216. if (id) moduleCache[id] = moduleObject;
  5217. tryRunOrWebpackError(
  5218. () =>
  5219. this.hooks.executeModule.call(
  5220. moduleArgument,
  5221. context
  5222. ),
  5223. "Compilation.hooks.executeModule"
  5224. );
  5225. moduleObject.loaded = true;
  5226. return moduleObject.exports;
  5227. } catch (execErr) {
  5228. if (strictModuleExceptionHandling) {
  5229. if (id) delete moduleCache[id];
  5230. } else if (strictModuleErrorHandling) {
  5231. moduleObject.error =
  5232. /** @type {WebpackError} */
  5233. (execErr);
  5234. }
  5235. if (!(/** @type {WebpackError} */ (execErr).module)) {
  5236. /** @type {WebpackError} */
  5237. (execErr).module = module;
  5238. }
  5239. throw execErr;
  5240. }
  5241. };
  5242. for (const runtimeModule of chunkGraph.getChunkRuntimeModulesInOrder(
  5243. chunk
  5244. )) {
  5245. __webpack_require_module__(
  5246. /** @type {ExecuteModuleArgument} */
  5247. (moduleArgumentsMap.get(runtimeModule))
  5248. );
  5249. }
  5250. exports = __webpack_require__(module.identifier());
  5251. } catch (execErr) {
  5252. const { message, stack, module } =
  5253. /** @type {WebpackError} */
  5254. (execErr);
  5255. const err = new WebpackError(
  5256. `Execution of module code from module graph (${
  5257. /** @type {Module} */
  5258. (module).readableIdentifier(this.requestShortener)
  5259. }) failed: ${message}`,
  5260. { cause: execErr }
  5261. );
  5262. err.stack = stack;
  5263. err.module = module;
  5264. return callback(err);
  5265. }
  5266. callback(null, {
  5267. exports,
  5268. assets,
  5269. cacheable,
  5270. fileDependencies,
  5271. contextDependencies,
  5272. missingDependencies,
  5273. buildDependencies
  5274. });
  5275. }
  5276. );
  5277. });
  5278. });
  5279. }
  5280. );
  5281. }
  5282. checkConstraints() {
  5283. const chunkGraph = this.chunkGraph;
  5284. /** @type {Set<ModuleId>} */
  5285. const usedIds = new Set();
  5286. for (const module of this.modules) {
  5287. if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) continue;
  5288. const moduleId = chunkGraph.getModuleId(module);
  5289. if (moduleId === null) continue;
  5290. if (usedIds.has(moduleId)) {
  5291. throw new Error(`checkConstraints: duplicate module id ${moduleId}`);
  5292. }
  5293. usedIds.add(moduleId);
  5294. }
  5295. for (const chunk of this.chunks) {
  5296. for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
  5297. if (!this.modules.has(module)) {
  5298. throw new Error(
  5299. "checkConstraints: module in chunk but not in compilation " +
  5300. ` ${chunk.debugId} ${module.debugId}`
  5301. );
  5302. }
  5303. }
  5304. for (const module of chunkGraph.getChunkEntryModulesIterable(chunk)) {
  5305. if (!this.modules.has(module)) {
  5306. throw new Error(
  5307. "checkConstraints: entry module in chunk but not in compilation " +
  5308. ` ${chunk.debugId} ${module.debugId}`
  5309. );
  5310. }
  5311. }
  5312. }
  5313. for (const chunkGroup of this.chunkGroups) {
  5314. chunkGroup.checkConstraints();
  5315. }
  5316. }
  5317. }
  5318. /**
  5319. * @typedef {object} FactorizeModuleOptions
  5320. * @property {ModuleProfile=} currentProfile
  5321. * @property {ModuleFactory} factory
  5322. * @property {Dependency[]} dependencies
  5323. * @property {boolean=} factoryResult return full ModuleFactoryResult instead of only module
  5324. * @property {Module | null} originModule
  5325. * @property {Partial<ModuleFactoryCreateDataContextInfo>=} contextInfo
  5326. * @property {string=} context
  5327. */
  5328. /**
  5329. * @param {FactorizeModuleOptions} options options object
  5330. * @param {ModuleCallback | ModuleFactoryResultCallback} callback callback
  5331. * @returns {void}
  5332. */
  5333. // Hide from typescript
  5334. const compilationPrototype = Compilation.prototype;
  5335. // TODO webpack 6 remove
  5336. Object.defineProperty(compilationPrototype, "modifyHash", {
  5337. writable: false,
  5338. enumerable: false,
  5339. configurable: false,
  5340. value: () => {
  5341. throw new Error(
  5342. "Compilation.modifyHash was removed in favor of Compilation.hooks.fullHash"
  5343. );
  5344. }
  5345. });
  5346. // TODO webpack 6 remove
  5347. Object.defineProperty(compilationPrototype, "cache", {
  5348. enumerable: false,
  5349. configurable: false,
  5350. get: util.deprecate(
  5351. /**
  5352. * @this {Compilation} the compilation
  5353. * @returns {Cache} the cache
  5354. */
  5355. function cache() {
  5356. return this.compiler.cache;
  5357. },
  5358. "Compilation.cache was removed in favor of Compilation.getCache()",
  5359. "DEP_WEBPACK_COMPILATION_CACHE"
  5360. ),
  5361. set: util.deprecate(
  5362. /**
  5363. * @param {EXPECTED_ANY} _v value
  5364. */
  5365. (_v) => {},
  5366. "Compilation.cache was removed in favor of Compilation.getCache()",
  5367. "DEP_WEBPACK_COMPILATION_CACHE"
  5368. )
  5369. });
  5370. /**
  5371. * Add additional assets to the compilation.
  5372. */
  5373. Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL = -2000;
  5374. /**
  5375. * Basic preprocessing of assets.
  5376. */
  5377. Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS = -1000;
  5378. /**
  5379. * Derive new assets from existing assets.
  5380. * Existing assets should not be treated as complete.
  5381. */
  5382. Compilation.PROCESS_ASSETS_STAGE_DERIVED = -200;
  5383. /**
  5384. * Add additional sections to existing assets, like a banner or initialization code.
  5385. */
  5386. Compilation.PROCESS_ASSETS_STAGE_ADDITIONS = -100;
  5387. /**
  5388. * Optimize existing assets in a general way.
  5389. */
  5390. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE = 100;
  5391. /**
  5392. * Optimize the count of existing assets, e. g. by merging them.
  5393. * Only assets of the same type should be merged.
  5394. * For assets of different types see PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE.
  5395. */
  5396. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT = 200;
  5397. /**
  5398. * Optimize the compatibility of existing assets, e. g. add polyfills or vendor-prefixes.
  5399. */
  5400. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY = 300;
  5401. /**
  5402. * Optimize the size of existing assets, e. g. by minimizing or omitting whitespace.
  5403. */
  5404. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE = 400;
  5405. /**
  5406. * Add development tooling to assets, e. g. by extracting a SourceMap.
  5407. */
  5408. Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING = 500;
  5409. /**
  5410. * Optimize the count of existing assets, e. g. by inlining assets of into other assets.
  5411. * Only assets of different types should be inlined.
  5412. * For assets of the same type see PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT.
  5413. */
  5414. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE = 700;
  5415. /**
  5416. * Summarize the list of existing assets
  5417. * e. g. creating an assets manifest of Service Workers.
  5418. */
  5419. Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE = 1000;
  5420. /**
  5421. * Optimize the hashes of the assets, e. g. by generating real hashes of the asset content.
  5422. */
  5423. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH = 2500;
  5424. /**
  5425. * Optimize the transfer of existing assets, e. g. by preparing a compressed (gzip) file as separate asset.
  5426. */
  5427. Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER = 3000;
  5428. /**
  5429. * Analyse existing assets.
  5430. */
  5431. Compilation.PROCESS_ASSETS_STAGE_ANALYSE = 4000;
  5432. /**
  5433. * Creating assets for reporting purposes.
  5434. */
  5435. Compilation.PROCESS_ASSETS_STAGE_REPORT = 5000;
  5436. module.exports = Compilation;