Compilation.js 171 KB

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