Compilation.js 164 KB

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