dep-934dbc7c.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488
  1. import fs$l, { promises as promises$2 } from 'node:fs';
  2. import fsp from 'node:fs/promises';
  3. import path$o, { dirname as dirname$2, join as join$2, posix as posix$1, isAbsolute as isAbsolute$2, relative as relative$2, basename as basename$2, extname as extname$1 } from 'node:path';
  4. import { fileURLToPath, URL as URL$3, URLSearchParams, parse as parse$i, pathToFileURL } from 'node:url';
  5. import { promisify as promisify$4, format as format$2, inspect } from 'node:util';
  6. import { performance as performance$1 } from 'node:perf_hooks';
  7. import { createRequire as createRequire$1, builtinModules } from 'node:module';
  8. import require$$0$3 from 'tty';
  9. import esbuild, { transform as transform$2, formatMessages, build as build$3 } from 'esbuild';
  10. import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep as sep$1, normalize } from 'path';
  11. import * as require$$0$2 from 'fs';
  12. import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, promises as promises$1, readdir as readdir$4, readdirSync } from 'fs';
  13. import require$$0$5 from 'events';
  14. import require$$5 from 'assert';
  15. import require$$0$6 from 'util';
  16. import require$$3$2 from 'net';
  17. import require$$0$9 from 'url';
  18. import require$$1$1 from 'http';
  19. import require$$0$7 from 'stream';
  20. import require$$2 from 'os';
  21. import require$$2$1 from 'child_process';
  22. import os$3 from 'node:os';
  23. import { exec } from 'node:child_process';
  24. import { createHash as createHash$2 } from 'node:crypto';
  25. import { promises } from 'node:dns';
  26. import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEFAULT_MAIN_FIELDS, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, SPECIAL_QUERY_RE, DEP_VERSION_RE, CSS_LANGS_RE, KNOWN_ASSET_TYPES, CLIENT_DIR, JS_TYPES_RE, ESBUILD_MODULES_TARGET, VERSION as VERSION$1, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
  27. import require$$5$1 from 'crypto';
  28. import { Buffer as Buffer$1 } from 'node:buffer';
  29. import require$$0$8, { createRequire as createRequire$2 } from 'module';
  30. import assert$1 from 'node:assert';
  31. import process$1 from 'node:process';
  32. import v8 from 'node:v8';
  33. import require$$1 from 'worker_threads';
  34. import require$$0$a from 'zlib';
  35. import require$$0$b from 'buffer';
  36. import require$$1$2 from 'https';
  37. import require$$4 from 'tls';
  38. import { createServer as createServer$3, STATUS_CODES } from 'node:http';
  39. import { createServer as createServer$2 } from 'node:https';
  40. import { VERSION } from 'rollup';
  41. import * as qs from 'querystring';
  42. import readline from 'node:readline';
  43. import zlib$1, { gzip } from 'node:zlib';
  44. import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
  45. import { dirname as __cjs_dirname } from 'node:path';
  46. import { createRequire as __cjs_createRequire } from 'node:module';
  47. const __filename = __cjs_fileURLToPath(import.meta.url);
  48. const __dirname = __cjs_dirname(__filename);
  49. const require = __cjs_createRequire(import.meta.url);
  50. const __require = require;
  51. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  52. function getDefaultExportFromCjs (x) {
  53. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  54. }
  55. function getAugmentedNamespace(n) {
  56. if (n.__esModule) return n;
  57. var f = n.default;
  58. if (typeof f == "function") {
  59. var a = function a () {
  60. if (this instanceof a) {
  61. var args = [null];
  62. args.push.apply(args, arguments);
  63. var Ctor = Function.bind.apply(f, args);
  64. return new Ctor();
  65. }
  66. return f.apply(this, arguments);
  67. };
  68. a.prototype = f.prototype;
  69. } else a = {};
  70. Object.defineProperty(a, '__esModule', {value: true});
  71. Object.keys(n).forEach(function (k) {
  72. var d = Object.getOwnPropertyDescriptor(n, k);
  73. Object.defineProperty(a, k, d.get ? d : {
  74. enumerable: true,
  75. get: function () {
  76. return n[k];
  77. }
  78. });
  79. });
  80. return a;
  81. }
  82. var picocolors = {exports: {}};
  83. let tty = require$$0$3;
  84. let isColorSupported =
  85. !("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
  86. ("FORCE_COLOR" in process.env ||
  87. process.argv.includes("--color") ||
  88. process.platform === "win32" ||
  89. (tty.isatty(1) && process.env.TERM !== "dumb") ||
  90. "CI" in process.env);
  91. let formatter =
  92. (open, close, replace = open) =>
  93. input => {
  94. let string = "" + input;
  95. let index = string.indexOf(close, open.length);
  96. return ~index
  97. ? open + replaceClose(string, close, replace, index) + close
  98. : open + string + close
  99. };
  100. let replaceClose = (string, close, replace, index) => {
  101. let start = string.substring(0, index) + replace;
  102. let end = string.substring(index + close.length);
  103. let nextIndex = end.indexOf(close);
  104. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  105. };
  106. let createColors = (enabled = isColorSupported) => ({
  107. isColorSupported: enabled,
  108. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  109. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  110. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  111. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  112. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  113. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  114. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  115. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  116. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  117. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  118. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  119. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  120. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  121. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  122. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  123. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  124. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  125. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  126. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  127. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  128. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  129. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  130. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  131. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  132. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  133. });
  134. picocolors.exports = createColors();
  135. picocolors.exports.createColors = createColors;
  136. var picocolorsExports = picocolors.exports;
  137. var colors$1 = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  138. function matches$1(pattern, importee) {
  139. if (pattern instanceof RegExp) {
  140. return pattern.test(importee);
  141. }
  142. if (importee.length < pattern.length) {
  143. return false;
  144. }
  145. if (importee === pattern) {
  146. return true;
  147. }
  148. // eslint-disable-next-line prefer-template
  149. return importee.startsWith(pattern + '/');
  150. }
  151. function getEntries({ entries, customResolver }) {
  152. if (!entries) {
  153. return [];
  154. }
  155. const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
  156. if (Array.isArray(entries)) {
  157. return entries.map((entry) => {
  158. return {
  159. find: entry.find,
  160. replacement: entry.replacement,
  161. resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
  162. };
  163. });
  164. }
  165. return Object.entries(entries).map(([key, value]) => {
  166. return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
  167. });
  168. }
  169. function getHookFunction(hook) {
  170. if (typeof hook === 'function') {
  171. return hook;
  172. }
  173. if (hook && 'handler' in hook && typeof hook.handler === 'function') {
  174. return hook.handler;
  175. }
  176. return null;
  177. }
  178. function resolveCustomResolver(customResolver) {
  179. if (typeof customResolver === 'function') {
  180. return customResolver;
  181. }
  182. if (customResolver) {
  183. return getHookFunction(customResolver.resolveId);
  184. }
  185. return null;
  186. }
  187. function alias$1(options = {}) {
  188. const entries = getEntries(options);
  189. if (entries.length === 0) {
  190. return {
  191. name: 'alias',
  192. resolveId: () => null
  193. };
  194. }
  195. return {
  196. name: 'alias',
  197. async buildStart(inputOptions) {
  198. await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); }));
  199. },
  200. resolveId(importee, importer, resolveOptions) {
  201. if (!importer) {
  202. return null;
  203. }
  204. // First match is supposed to be the correct one
  205. const matchedEntry = entries.find((entry) => matches$1(entry.find, importee));
  206. if (!matchedEntry) {
  207. return null;
  208. }
  209. const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
  210. if (matchedEntry.resolverFunction) {
  211. return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
  212. }
  213. return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => resolved || { id: updatedId });
  214. }
  215. };
  216. }
  217. // @ts-check
  218. /** @typedef { import('estree').BaseNode} BaseNode */
  219. /** @typedef {{
  220. skip: () => void;
  221. remove: () => void;
  222. replace: (node: BaseNode) => void;
  223. }} WalkerContext */
  224. let WalkerBase$1 = class WalkerBase {
  225. constructor() {
  226. /** @type {boolean} */
  227. this.should_skip = false;
  228. /** @type {boolean} */
  229. this.should_remove = false;
  230. /** @type {BaseNode | null} */
  231. this.replacement = null;
  232. /** @type {WalkerContext} */
  233. this.context = {
  234. skip: () => (this.should_skip = true),
  235. remove: () => (this.should_remove = true),
  236. replace: (node) => (this.replacement = node)
  237. };
  238. }
  239. /**
  240. *
  241. * @param {any} parent
  242. * @param {string} prop
  243. * @param {number} index
  244. * @param {BaseNode} node
  245. */
  246. replace(parent, prop, index, node) {
  247. if (parent) {
  248. if (index !== null) {
  249. parent[prop][index] = node;
  250. } else {
  251. parent[prop] = node;
  252. }
  253. }
  254. }
  255. /**
  256. *
  257. * @param {any} parent
  258. * @param {string} prop
  259. * @param {number} index
  260. */
  261. remove(parent, prop, index) {
  262. if (parent) {
  263. if (index !== null) {
  264. parent[prop].splice(index, 1);
  265. } else {
  266. delete parent[prop];
  267. }
  268. }
  269. }
  270. };
  271. // @ts-check
  272. /** @typedef { import('estree').BaseNode} BaseNode */
  273. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  274. /** @typedef {(
  275. * this: WalkerContext,
  276. * node: BaseNode,
  277. * parent: BaseNode,
  278. * key: string,
  279. * index: number
  280. * ) => void} SyncHandler */
  281. let SyncWalker$1 = class SyncWalker extends WalkerBase$1 {
  282. /**
  283. *
  284. * @param {SyncHandler} enter
  285. * @param {SyncHandler} leave
  286. */
  287. constructor(enter, leave) {
  288. super();
  289. /** @type {SyncHandler} */
  290. this.enter = enter;
  291. /** @type {SyncHandler} */
  292. this.leave = leave;
  293. }
  294. /**
  295. *
  296. * @param {BaseNode} node
  297. * @param {BaseNode} parent
  298. * @param {string} [prop]
  299. * @param {number} [index]
  300. * @returns {BaseNode}
  301. */
  302. visit(node, parent, prop, index) {
  303. if (node) {
  304. if (this.enter) {
  305. const _should_skip = this.should_skip;
  306. const _should_remove = this.should_remove;
  307. const _replacement = this.replacement;
  308. this.should_skip = false;
  309. this.should_remove = false;
  310. this.replacement = null;
  311. this.enter.call(this.context, node, parent, prop, index);
  312. if (this.replacement) {
  313. node = this.replacement;
  314. this.replace(parent, prop, index, node);
  315. }
  316. if (this.should_remove) {
  317. this.remove(parent, prop, index);
  318. }
  319. const skipped = this.should_skip;
  320. const removed = this.should_remove;
  321. this.should_skip = _should_skip;
  322. this.should_remove = _should_remove;
  323. this.replacement = _replacement;
  324. if (skipped) return node;
  325. if (removed) return null;
  326. }
  327. for (const key in node) {
  328. const value = node[key];
  329. if (typeof value !== "object") {
  330. continue;
  331. } else if (Array.isArray(value)) {
  332. for (let i = 0; i < value.length; i += 1) {
  333. if (value[i] !== null && typeof value[i].type === 'string') {
  334. if (!this.visit(value[i], node, key, i)) {
  335. // removed
  336. i--;
  337. }
  338. }
  339. }
  340. } else if (value !== null && typeof value.type === "string") {
  341. this.visit(value, node, key, null);
  342. }
  343. }
  344. if (this.leave) {
  345. const _replacement = this.replacement;
  346. const _should_remove = this.should_remove;
  347. this.replacement = null;
  348. this.should_remove = false;
  349. this.leave.call(this.context, node, parent, prop, index);
  350. if (this.replacement) {
  351. node = this.replacement;
  352. this.replace(parent, prop, index, node);
  353. }
  354. if (this.should_remove) {
  355. this.remove(parent, prop, index);
  356. }
  357. const removed = this.should_remove;
  358. this.replacement = _replacement;
  359. this.should_remove = _should_remove;
  360. if (removed) return null;
  361. }
  362. }
  363. return node;
  364. }
  365. };
  366. // @ts-check
  367. /** @typedef { import('estree').BaseNode} BaseNode */
  368. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  369. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  370. /**
  371. *
  372. * @param {BaseNode} ast
  373. * @param {{
  374. * enter?: SyncHandler
  375. * leave?: SyncHandler
  376. * }} walker
  377. * @returns {BaseNode}
  378. */
  379. function walk$4(ast, { enter, leave }) {
  380. const instance = new SyncWalker$1(enter, leave);
  381. return instance.visit(ast, null);
  382. }
  383. var utils$k = {};
  384. const path$n = require$$0$4;
  385. const WIN_SLASH = '\\\\/';
  386. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  387. /**
  388. * Posix glob regex
  389. */
  390. const DOT_LITERAL = '\\.';
  391. const PLUS_LITERAL = '\\+';
  392. const QMARK_LITERAL = '\\?';
  393. const SLASH_LITERAL = '\\/';
  394. const ONE_CHAR = '(?=.)';
  395. const QMARK = '[^/]';
  396. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  397. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  398. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  399. const NO_DOT = `(?!${DOT_LITERAL})`;
  400. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  401. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  402. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  403. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  404. const STAR$1 = `${QMARK}*?`;
  405. const POSIX_CHARS = {
  406. DOT_LITERAL,
  407. PLUS_LITERAL,
  408. QMARK_LITERAL,
  409. SLASH_LITERAL,
  410. ONE_CHAR,
  411. QMARK,
  412. END_ANCHOR,
  413. DOTS_SLASH,
  414. NO_DOT,
  415. NO_DOTS,
  416. NO_DOT_SLASH,
  417. NO_DOTS_SLASH,
  418. QMARK_NO_DOT,
  419. STAR: STAR$1,
  420. START_ANCHOR
  421. };
  422. /**
  423. * Windows glob regex
  424. */
  425. const WINDOWS_CHARS = {
  426. ...POSIX_CHARS,
  427. SLASH_LITERAL: `[${WIN_SLASH}]`,
  428. QMARK: WIN_NO_SLASH,
  429. STAR: `${WIN_NO_SLASH}*?`,
  430. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  431. NO_DOT: `(?!${DOT_LITERAL})`,
  432. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  433. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  434. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  435. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  436. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  437. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  438. };
  439. /**
  440. * POSIX Bracket Regex
  441. */
  442. const POSIX_REGEX_SOURCE$1 = {
  443. alnum: 'a-zA-Z0-9',
  444. alpha: 'a-zA-Z',
  445. ascii: '\\x00-\\x7F',
  446. blank: ' \\t',
  447. cntrl: '\\x00-\\x1F\\x7F',
  448. digit: '0-9',
  449. graph: '\\x21-\\x7E',
  450. lower: 'a-z',
  451. print: '\\x20-\\x7E ',
  452. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  453. space: ' \\t\\r\\n\\v\\f',
  454. upper: 'A-Z',
  455. word: 'A-Za-z0-9_',
  456. xdigit: 'A-Fa-f0-9'
  457. };
  458. var constants$6 = {
  459. MAX_LENGTH: 1024 * 64,
  460. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  461. // regular expressions
  462. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  463. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  464. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  465. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  466. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  467. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  468. // Replace globs with equivalent patterns to reduce parsing time.
  469. REPLACEMENTS: {
  470. '***': '*',
  471. '**/**': '**',
  472. '**/**/**': '**'
  473. },
  474. // Digits
  475. CHAR_0: 48, /* 0 */
  476. CHAR_9: 57, /* 9 */
  477. // Alphabet chars.
  478. CHAR_UPPERCASE_A: 65, /* A */
  479. CHAR_LOWERCASE_A: 97, /* a */
  480. CHAR_UPPERCASE_Z: 90, /* Z */
  481. CHAR_LOWERCASE_Z: 122, /* z */
  482. CHAR_LEFT_PARENTHESES: 40, /* ( */
  483. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  484. CHAR_ASTERISK: 42, /* * */
  485. // Non-alphabetic chars.
  486. CHAR_AMPERSAND: 38, /* & */
  487. CHAR_AT: 64, /* @ */
  488. CHAR_BACKWARD_SLASH: 92, /* \ */
  489. CHAR_CARRIAGE_RETURN: 13, /* \r */
  490. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  491. CHAR_COLON: 58, /* : */
  492. CHAR_COMMA: 44, /* , */
  493. CHAR_DOT: 46, /* . */
  494. CHAR_DOUBLE_QUOTE: 34, /* " */
  495. CHAR_EQUAL: 61, /* = */
  496. CHAR_EXCLAMATION_MARK: 33, /* ! */
  497. CHAR_FORM_FEED: 12, /* \f */
  498. CHAR_FORWARD_SLASH: 47, /* / */
  499. CHAR_GRAVE_ACCENT: 96, /* ` */
  500. CHAR_HASH: 35, /* # */
  501. CHAR_HYPHEN_MINUS: 45, /* - */
  502. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  503. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  504. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  505. CHAR_LINE_FEED: 10, /* \n */
  506. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  507. CHAR_PERCENT: 37, /* % */
  508. CHAR_PLUS: 43, /* + */
  509. CHAR_QUESTION_MARK: 63, /* ? */
  510. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  511. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  512. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  513. CHAR_SEMICOLON: 59, /* ; */
  514. CHAR_SINGLE_QUOTE: 39, /* ' */
  515. CHAR_SPACE: 32, /* */
  516. CHAR_TAB: 9, /* \t */
  517. CHAR_UNDERSCORE: 95, /* _ */
  518. CHAR_VERTICAL_LINE: 124, /* | */
  519. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  520. SEP: path$n.sep,
  521. /**
  522. * Create EXTGLOB_CHARS
  523. */
  524. extglobChars(chars) {
  525. return {
  526. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  527. '?': { type: 'qmark', open: '(?:', close: ')?' },
  528. '+': { type: 'plus', open: '(?:', close: ')+' },
  529. '*': { type: 'star', open: '(?:', close: ')*' },
  530. '@': { type: 'at', open: '(?:', close: ')' }
  531. };
  532. },
  533. /**
  534. * Create GLOB_CHARS
  535. */
  536. globChars(win32) {
  537. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  538. }
  539. };
  540. (function (exports) {
  541. const path = require$$0$4;
  542. const win32 = process.platform === 'win32';
  543. const {
  544. REGEX_BACKSLASH,
  545. REGEX_REMOVE_BACKSLASH,
  546. REGEX_SPECIAL_CHARS,
  547. REGEX_SPECIAL_CHARS_GLOBAL
  548. } = constants$6;
  549. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  550. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  551. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  552. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  553. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  554. exports.removeBackslashes = str => {
  555. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  556. return match === '\\' ? '' : match;
  557. });
  558. };
  559. exports.supportsLookbehinds = () => {
  560. const segs = process.version.slice(1).split('.').map(Number);
  561. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  562. return true;
  563. }
  564. return false;
  565. };
  566. exports.isWindows = options => {
  567. if (options && typeof options.windows === 'boolean') {
  568. return options.windows;
  569. }
  570. return win32 === true || path.sep === '\\';
  571. };
  572. exports.escapeLast = (input, char, lastIdx) => {
  573. const idx = input.lastIndexOf(char, lastIdx);
  574. if (idx === -1) return input;
  575. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  576. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  577. };
  578. exports.removePrefix = (input, state = {}) => {
  579. let output = input;
  580. if (output.startsWith('./')) {
  581. output = output.slice(2);
  582. state.prefix = './';
  583. }
  584. return output;
  585. };
  586. exports.wrapOutput = (input, state = {}, options = {}) => {
  587. const prepend = options.contains ? '' : '^';
  588. const append = options.contains ? '' : '$';
  589. let output = `${prepend}(?:${input})${append}`;
  590. if (state.negated === true) {
  591. output = `(?:^(?!${output}).*$)`;
  592. }
  593. return output;
  594. };
  595. } (utils$k));
  596. const utils$j = utils$k;
  597. const {
  598. CHAR_ASTERISK, /* * */
  599. CHAR_AT, /* @ */
  600. CHAR_BACKWARD_SLASH, /* \ */
  601. CHAR_COMMA: CHAR_COMMA$1, /* , */
  602. CHAR_DOT: CHAR_DOT$1, /* . */
  603. CHAR_EXCLAMATION_MARK, /* ! */
  604. CHAR_FORWARD_SLASH, /* / */
  605. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */
  606. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */
  607. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
  608. CHAR_PLUS, /* + */
  609. CHAR_QUESTION_MARK, /* ? */
  610. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */
  611. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */
  612. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */
  613. } = constants$6;
  614. const isPathSeparator = code => {
  615. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  616. };
  617. const depth = token => {
  618. if (token.isPrefix !== true) {
  619. token.depth = token.isGlobstar ? Infinity : 1;
  620. }
  621. };
  622. /**
  623. * Quickly scans a glob pattern and returns an object with a handful of
  624. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  625. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  626. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  627. *
  628. * ```js
  629. * const pm = require('picomatch');
  630. * console.log(pm.scan('foo/bar/*.js'));
  631. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  632. * ```
  633. * @param {String} `str`
  634. * @param {Object} `options`
  635. * @return {Object} Returns an object with tokens and regex source string.
  636. * @api public
  637. */
  638. const scan$2 = (input, options) => {
  639. const opts = options || {};
  640. const length = input.length - 1;
  641. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  642. const slashes = [];
  643. const tokens = [];
  644. const parts = [];
  645. let str = input;
  646. let index = -1;
  647. let start = 0;
  648. let lastIndex = 0;
  649. let isBrace = false;
  650. let isBracket = false;
  651. let isGlob = false;
  652. let isExtglob = false;
  653. let isGlobstar = false;
  654. let braceEscaped = false;
  655. let backslashes = false;
  656. let negated = false;
  657. let negatedExtglob = false;
  658. let finished = false;
  659. let braces = 0;
  660. let prev;
  661. let code;
  662. let token = { value: '', depth: 0, isGlob: false };
  663. const eos = () => index >= length;
  664. const peek = () => str.charCodeAt(index + 1);
  665. const advance = () => {
  666. prev = code;
  667. return str.charCodeAt(++index);
  668. };
  669. while (index < length) {
  670. code = advance();
  671. let next;
  672. if (code === CHAR_BACKWARD_SLASH) {
  673. backslashes = token.backslashes = true;
  674. code = advance();
  675. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  676. braceEscaped = true;
  677. }
  678. continue;
  679. }
  680. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
  681. braces++;
  682. while (eos() !== true && (code = advance())) {
  683. if (code === CHAR_BACKWARD_SLASH) {
  684. backslashes = token.backslashes = true;
  685. advance();
  686. continue;
  687. }
  688. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  689. braces++;
  690. continue;
  691. }
  692. if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
  693. isBrace = token.isBrace = true;
  694. isGlob = token.isGlob = true;
  695. finished = true;
  696. if (scanToEnd === true) {
  697. continue;
  698. }
  699. break;
  700. }
  701. if (braceEscaped !== true && code === CHAR_COMMA$1) {
  702. isBrace = token.isBrace = true;
  703. isGlob = token.isGlob = true;
  704. finished = true;
  705. if (scanToEnd === true) {
  706. continue;
  707. }
  708. break;
  709. }
  710. if (code === CHAR_RIGHT_CURLY_BRACE$1) {
  711. braces--;
  712. if (braces === 0) {
  713. braceEscaped = false;
  714. isBrace = token.isBrace = true;
  715. finished = true;
  716. break;
  717. }
  718. }
  719. }
  720. if (scanToEnd === true) {
  721. continue;
  722. }
  723. break;
  724. }
  725. if (code === CHAR_FORWARD_SLASH) {
  726. slashes.push(index);
  727. tokens.push(token);
  728. token = { value: '', depth: 0, isGlob: false };
  729. if (finished === true) continue;
  730. if (prev === CHAR_DOT$1 && index === (start + 1)) {
  731. start += 2;
  732. continue;
  733. }
  734. lastIndex = index + 1;
  735. continue;
  736. }
  737. if (opts.noext !== true) {
  738. const isExtglobChar = code === CHAR_PLUS
  739. || code === CHAR_AT
  740. || code === CHAR_ASTERISK
  741. || code === CHAR_QUESTION_MARK
  742. || code === CHAR_EXCLAMATION_MARK;
  743. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
  744. isGlob = token.isGlob = true;
  745. isExtglob = token.isExtglob = true;
  746. finished = true;
  747. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  748. negatedExtglob = true;
  749. }
  750. if (scanToEnd === true) {
  751. while (eos() !== true && (code = advance())) {
  752. if (code === CHAR_BACKWARD_SLASH) {
  753. backslashes = token.backslashes = true;
  754. code = advance();
  755. continue;
  756. }
  757. if (code === CHAR_RIGHT_PARENTHESES$1) {
  758. isGlob = token.isGlob = true;
  759. finished = true;
  760. break;
  761. }
  762. }
  763. continue;
  764. }
  765. break;
  766. }
  767. }
  768. if (code === CHAR_ASTERISK) {
  769. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  770. isGlob = token.isGlob = true;
  771. finished = true;
  772. if (scanToEnd === true) {
  773. continue;
  774. }
  775. break;
  776. }
  777. if (code === CHAR_QUESTION_MARK) {
  778. isGlob = token.isGlob = true;
  779. finished = true;
  780. if (scanToEnd === true) {
  781. continue;
  782. }
  783. break;
  784. }
  785. if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
  786. while (eos() !== true && (next = advance())) {
  787. if (next === CHAR_BACKWARD_SLASH) {
  788. backslashes = token.backslashes = true;
  789. advance();
  790. continue;
  791. }
  792. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  793. isBracket = token.isBracket = true;
  794. isGlob = token.isGlob = true;
  795. finished = true;
  796. break;
  797. }
  798. }
  799. if (scanToEnd === true) {
  800. continue;
  801. }
  802. break;
  803. }
  804. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  805. negated = token.negated = true;
  806. start++;
  807. continue;
  808. }
  809. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
  810. isGlob = token.isGlob = true;
  811. if (scanToEnd === true) {
  812. while (eos() !== true && (code = advance())) {
  813. if (code === CHAR_LEFT_PARENTHESES$1) {
  814. backslashes = token.backslashes = true;
  815. code = advance();
  816. continue;
  817. }
  818. if (code === CHAR_RIGHT_PARENTHESES$1) {
  819. finished = true;
  820. break;
  821. }
  822. }
  823. continue;
  824. }
  825. break;
  826. }
  827. if (isGlob === true) {
  828. finished = true;
  829. if (scanToEnd === true) {
  830. continue;
  831. }
  832. break;
  833. }
  834. }
  835. if (opts.noext === true) {
  836. isExtglob = false;
  837. isGlob = false;
  838. }
  839. let base = str;
  840. let prefix = '';
  841. let glob = '';
  842. if (start > 0) {
  843. prefix = str.slice(0, start);
  844. str = str.slice(start);
  845. lastIndex -= start;
  846. }
  847. if (base && isGlob === true && lastIndex > 0) {
  848. base = str.slice(0, lastIndex);
  849. glob = str.slice(lastIndex);
  850. } else if (isGlob === true) {
  851. base = '';
  852. glob = str;
  853. } else {
  854. base = str;
  855. }
  856. if (base && base !== '' && base !== '/' && base !== str) {
  857. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  858. base = base.slice(0, -1);
  859. }
  860. }
  861. if (opts.unescape === true) {
  862. if (glob) glob = utils$j.removeBackslashes(glob);
  863. if (base && backslashes === true) {
  864. base = utils$j.removeBackslashes(base);
  865. }
  866. }
  867. const state = {
  868. prefix,
  869. input,
  870. start,
  871. base,
  872. glob,
  873. isBrace,
  874. isBracket,
  875. isGlob,
  876. isExtglob,
  877. isGlobstar,
  878. negated,
  879. negatedExtglob
  880. };
  881. if (opts.tokens === true) {
  882. state.maxDepth = 0;
  883. if (!isPathSeparator(code)) {
  884. tokens.push(token);
  885. }
  886. state.tokens = tokens;
  887. }
  888. if (opts.parts === true || opts.tokens === true) {
  889. let prevIndex;
  890. for (let idx = 0; idx < slashes.length; idx++) {
  891. const n = prevIndex ? prevIndex + 1 : start;
  892. const i = slashes[idx];
  893. const value = input.slice(n, i);
  894. if (opts.tokens) {
  895. if (idx === 0 && start !== 0) {
  896. tokens[idx].isPrefix = true;
  897. tokens[idx].value = prefix;
  898. } else {
  899. tokens[idx].value = value;
  900. }
  901. depth(tokens[idx]);
  902. state.maxDepth += tokens[idx].depth;
  903. }
  904. if (idx !== 0 || value !== '') {
  905. parts.push(value);
  906. }
  907. prevIndex = i;
  908. }
  909. if (prevIndex && prevIndex + 1 < input.length) {
  910. const value = input.slice(prevIndex + 1);
  911. parts.push(value);
  912. if (opts.tokens) {
  913. tokens[tokens.length - 1].value = value;
  914. depth(tokens[tokens.length - 1]);
  915. state.maxDepth += tokens[tokens.length - 1].depth;
  916. }
  917. }
  918. state.slashes = slashes;
  919. state.parts = parts;
  920. }
  921. return state;
  922. };
  923. var scan_1 = scan$2;
  924. const constants$5 = constants$6;
  925. const utils$i = utils$k;
  926. /**
  927. * Constants
  928. */
  929. const {
  930. MAX_LENGTH: MAX_LENGTH$1,
  931. POSIX_REGEX_SOURCE,
  932. REGEX_NON_SPECIAL_CHARS,
  933. REGEX_SPECIAL_CHARS_BACKREF,
  934. REPLACEMENTS
  935. } = constants$5;
  936. /**
  937. * Helpers
  938. */
  939. const expandRange = (args, options) => {
  940. if (typeof options.expandRange === 'function') {
  941. return options.expandRange(...args, options);
  942. }
  943. args.sort();
  944. const value = `[${args.join('-')}]`;
  945. return value;
  946. };
  947. /**
  948. * Create the message for a syntax error
  949. */
  950. const syntaxError = (type, char) => {
  951. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  952. };
  953. /**
  954. * Parse the given input string.
  955. * @param {String} input
  956. * @param {Object} options
  957. * @return {Object}
  958. */
  959. const parse$h = (input, options) => {
  960. if (typeof input !== 'string') {
  961. throw new TypeError('Expected a string');
  962. }
  963. input = REPLACEMENTS[input] || input;
  964. const opts = { ...options };
  965. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  966. let len = input.length;
  967. if (len > max) {
  968. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  969. }
  970. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  971. const tokens = [bos];
  972. const capture = opts.capture ? '' : '?:';
  973. const win32 = utils$i.isWindows(options);
  974. // create constants based on platform, for windows or posix
  975. const PLATFORM_CHARS = constants$5.globChars(win32);
  976. const EXTGLOB_CHARS = constants$5.extglobChars(PLATFORM_CHARS);
  977. const {
  978. DOT_LITERAL,
  979. PLUS_LITERAL,
  980. SLASH_LITERAL,
  981. ONE_CHAR,
  982. DOTS_SLASH,
  983. NO_DOT,
  984. NO_DOT_SLASH,
  985. NO_DOTS_SLASH,
  986. QMARK,
  987. QMARK_NO_DOT,
  988. STAR,
  989. START_ANCHOR
  990. } = PLATFORM_CHARS;
  991. const globstar = opts => {
  992. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  993. };
  994. const nodot = opts.dot ? '' : NO_DOT;
  995. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  996. let star = opts.bash === true ? globstar(opts) : STAR;
  997. if (opts.capture) {
  998. star = `(${star})`;
  999. }
  1000. // minimatch options support
  1001. if (typeof opts.noext === 'boolean') {
  1002. opts.noextglob = opts.noext;
  1003. }
  1004. const state = {
  1005. input,
  1006. index: -1,
  1007. start: 0,
  1008. dot: opts.dot === true,
  1009. consumed: '',
  1010. output: '',
  1011. prefix: '',
  1012. backtrack: false,
  1013. negated: false,
  1014. brackets: 0,
  1015. braces: 0,
  1016. parens: 0,
  1017. quotes: 0,
  1018. globstar: false,
  1019. tokens
  1020. };
  1021. input = utils$i.removePrefix(input, state);
  1022. len = input.length;
  1023. const extglobs = [];
  1024. const braces = [];
  1025. const stack = [];
  1026. let prev = bos;
  1027. let value;
  1028. /**
  1029. * Tokenizing helpers
  1030. */
  1031. const eos = () => state.index === len - 1;
  1032. const peek = state.peek = (n = 1) => input[state.index + n];
  1033. const advance = state.advance = () => input[++state.index] || '';
  1034. const remaining = () => input.slice(state.index + 1);
  1035. const consume = (value = '', num = 0) => {
  1036. state.consumed += value;
  1037. state.index += num;
  1038. };
  1039. const append = token => {
  1040. state.output += token.output != null ? token.output : token.value;
  1041. consume(token.value);
  1042. };
  1043. const negate = () => {
  1044. let count = 1;
  1045. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1046. advance();
  1047. state.start++;
  1048. count++;
  1049. }
  1050. if (count % 2 === 0) {
  1051. return false;
  1052. }
  1053. state.negated = true;
  1054. state.start++;
  1055. return true;
  1056. };
  1057. const increment = type => {
  1058. state[type]++;
  1059. stack.push(type);
  1060. };
  1061. const decrement = type => {
  1062. state[type]--;
  1063. stack.pop();
  1064. };
  1065. /**
  1066. * Push tokens onto the tokens array. This helper speeds up
  1067. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1068. * and 2) helping us avoid creating extra tokens when consecutive
  1069. * characters are plain text. This improves performance and simplifies
  1070. * lookbehinds.
  1071. */
  1072. const push = tok => {
  1073. if (prev.type === 'globstar') {
  1074. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1075. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1076. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1077. state.output = state.output.slice(0, -prev.output.length);
  1078. prev.type = 'star';
  1079. prev.value = '*';
  1080. prev.output = star;
  1081. state.output += prev.output;
  1082. }
  1083. }
  1084. if (extglobs.length && tok.type !== 'paren') {
  1085. extglobs[extglobs.length - 1].inner += tok.value;
  1086. }
  1087. if (tok.value || tok.output) append(tok);
  1088. if (prev && prev.type === 'text' && tok.type === 'text') {
  1089. prev.value += tok.value;
  1090. prev.output = (prev.output || '') + tok.value;
  1091. return;
  1092. }
  1093. tok.prev = prev;
  1094. tokens.push(tok);
  1095. prev = tok;
  1096. };
  1097. const extglobOpen = (type, value) => {
  1098. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1099. token.prev = prev;
  1100. token.parens = state.parens;
  1101. token.output = state.output;
  1102. const output = (opts.capture ? '(' : '') + token.open;
  1103. increment('parens');
  1104. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1105. push({ type: 'paren', extglob: true, value: advance(), output });
  1106. extglobs.push(token);
  1107. };
  1108. const extglobClose = token => {
  1109. let output = token.close + (opts.capture ? ')' : '');
  1110. let rest;
  1111. if (token.type === 'negate') {
  1112. let extglobStar = star;
  1113. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1114. extglobStar = globstar(opts);
  1115. }
  1116. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1117. output = token.close = `)$))${extglobStar}`;
  1118. }
  1119. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1120. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1121. // In this case, we need to parse the string and use it in the output of the original pattern.
  1122. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1123. //
  1124. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1125. const expression = parse$h(rest, { ...options, fastpaths: false }).output;
  1126. output = token.close = `)${expression})${extglobStar})`;
  1127. }
  1128. if (token.prev.type === 'bos') {
  1129. state.negatedExtglob = true;
  1130. }
  1131. }
  1132. push({ type: 'paren', extglob: true, value, output });
  1133. decrement('parens');
  1134. };
  1135. /**
  1136. * Fast paths
  1137. */
  1138. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1139. let backslashes = false;
  1140. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1141. if (first === '\\') {
  1142. backslashes = true;
  1143. return m;
  1144. }
  1145. if (first === '?') {
  1146. if (esc) {
  1147. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1148. }
  1149. if (index === 0) {
  1150. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1151. }
  1152. return QMARK.repeat(chars.length);
  1153. }
  1154. if (first === '.') {
  1155. return DOT_LITERAL.repeat(chars.length);
  1156. }
  1157. if (first === '*') {
  1158. if (esc) {
  1159. return esc + first + (rest ? star : '');
  1160. }
  1161. return star;
  1162. }
  1163. return esc ? m : `\\${m}`;
  1164. });
  1165. if (backslashes === true) {
  1166. if (opts.unescape === true) {
  1167. output = output.replace(/\\/g, '');
  1168. } else {
  1169. output = output.replace(/\\+/g, m => {
  1170. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1171. });
  1172. }
  1173. }
  1174. if (output === input && opts.contains === true) {
  1175. state.output = input;
  1176. return state;
  1177. }
  1178. state.output = utils$i.wrapOutput(output, state, options);
  1179. return state;
  1180. }
  1181. /**
  1182. * Tokenize input until we reach end-of-string
  1183. */
  1184. while (!eos()) {
  1185. value = advance();
  1186. if (value === '\u0000') {
  1187. continue;
  1188. }
  1189. /**
  1190. * Escaped characters
  1191. */
  1192. if (value === '\\') {
  1193. const next = peek();
  1194. if (next === '/' && opts.bash !== true) {
  1195. continue;
  1196. }
  1197. if (next === '.' || next === ';') {
  1198. continue;
  1199. }
  1200. if (!next) {
  1201. value += '\\';
  1202. push({ type: 'text', value });
  1203. continue;
  1204. }
  1205. // collapse slashes to reduce potential for exploits
  1206. const match = /^\\+/.exec(remaining());
  1207. let slashes = 0;
  1208. if (match && match[0].length > 2) {
  1209. slashes = match[0].length;
  1210. state.index += slashes;
  1211. if (slashes % 2 !== 0) {
  1212. value += '\\';
  1213. }
  1214. }
  1215. if (opts.unescape === true) {
  1216. value = advance();
  1217. } else {
  1218. value += advance();
  1219. }
  1220. if (state.brackets === 0) {
  1221. push({ type: 'text', value });
  1222. continue;
  1223. }
  1224. }
  1225. /**
  1226. * If we're inside a regex character class, continue
  1227. * until we reach the closing bracket.
  1228. */
  1229. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1230. if (opts.posix !== false && value === ':') {
  1231. const inner = prev.value.slice(1);
  1232. if (inner.includes('[')) {
  1233. prev.posix = true;
  1234. if (inner.includes(':')) {
  1235. const idx = prev.value.lastIndexOf('[');
  1236. const pre = prev.value.slice(0, idx);
  1237. const rest = prev.value.slice(idx + 2);
  1238. const posix = POSIX_REGEX_SOURCE[rest];
  1239. if (posix) {
  1240. prev.value = pre + posix;
  1241. state.backtrack = true;
  1242. advance();
  1243. if (!bos.output && tokens.indexOf(prev) === 1) {
  1244. bos.output = ONE_CHAR;
  1245. }
  1246. continue;
  1247. }
  1248. }
  1249. }
  1250. }
  1251. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1252. value = `\\${value}`;
  1253. }
  1254. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1255. value = `\\${value}`;
  1256. }
  1257. if (opts.posix === true && value === '!' && prev.value === '[') {
  1258. value = '^';
  1259. }
  1260. prev.value += value;
  1261. append({ value });
  1262. continue;
  1263. }
  1264. /**
  1265. * If we're inside a quoted string, continue
  1266. * until we reach the closing double quote.
  1267. */
  1268. if (state.quotes === 1 && value !== '"') {
  1269. value = utils$i.escapeRegex(value);
  1270. prev.value += value;
  1271. append({ value });
  1272. continue;
  1273. }
  1274. /**
  1275. * Double quotes
  1276. */
  1277. if (value === '"') {
  1278. state.quotes = state.quotes === 1 ? 0 : 1;
  1279. if (opts.keepQuotes === true) {
  1280. push({ type: 'text', value });
  1281. }
  1282. continue;
  1283. }
  1284. /**
  1285. * Parentheses
  1286. */
  1287. if (value === '(') {
  1288. increment('parens');
  1289. push({ type: 'paren', value });
  1290. continue;
  1291. }
  1292. if (value === ')') {
  1293. if (state.parens === 0 && opts.strictBrackets === true) {
  1294. throw new SyntaxError(syntaxError('opening', '('));
  1295. }
  1296. const extglob = extglobs[extglobs.length - 1];
  1297. if (extglob && state.parens === extglob.parens + 1) {
  1298. extglobClose(extglobs.pop());
  1299. continue;
  1300. }
  1301. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1302. decrement('parens');
  1303. continue;
  1304. }
  1305. /**
  1306. * Square brackets
  1307. */
  1308. if (value === '[') {
  1309. if (opts.nobracket === true || !remaining().includes(']')) {
  1310. if (opts.nobracket !== true && opts.strictBrackets === true) {
  1311. throw new SyntaxError(syntaxError('closing', ']'));
  1312. }
  1313. value = `\\${value}`;
  1314. } else {
  1315. increment('brackets');
  1316. }
  1317. push({ type: 'bracket', value });
  1318. continue;
  1319. }
  1320. if (value === ']') {
  1321. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  1322. push({ type: 'text', value, output: `\\${value}` });
  1323. continue;
  1324. }
  1325. if (state.brackets === 0) {
  1326. if (opts.strictBrackets === true) {
  1327. throw new SyntaxError(syntaxError('opening', '['));
  1328. }
  1329. push({ type: 'text', value, output: `\\${value}` });
  1330. continue;
  1331. }
  1332. decrement('brackets');
  1333. const prevValue = prev.value.slice(1);
  1334. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  1335. value = `/${value}`;
  1336. }
  1337. prev.value += value;
  1338. append({ value });
  1339. // when literal brackets are explicitly disabled
  1340. // assume we should match with a regex character class
  1341. if (opts.literalBrackets === false || utils$i.hasRegexChars(prevValue)) {
  1342. continue;
  1343. }
  1344. const escaped = utils$i.escapeRegex(prev.value);
  1345. state.output = state.output.slice(0, -prev.value.length);
  1346. // when literal brackets are explicitly enabled
  1347. // assume we should escape the brackets to match literal characters
  1348. if (opts.literalBrackets === true) {
  1349. state.output += escaped;
  1350. prev.value = escaped;
  1351. continue;
  1352. }
  1353. // when the user specifies nothing, try to match both
  1354. prev.value = `(${capture}${escaped}|${prev.value})`;
  1355. state.output += prev.value;
  1356. continue;
  1357. }
  1358. /**
  1359. * Braces
  1360. */
  1361. if (value === '{' && opts.nobrace !== true) {
  1362. increment('braces');
  1363. const open = {
  1364. type: 'brace',
  1365. value,
  1366. output: '(',
  1367. outputIndex: state.output.length,
  1368. tokensIndex: state.tokens.length
  1369. };
  1370. braces.push(open);
  1371. push(open);
  1372. continue;
  1373. }
  1374. if (value === '}') {
  1375. const brace = braces[braces.length - 1];
  1376. if (opts.nobrace === true || !brace) {
  1377. push({ type: 'text', value, output: value });
  1378. continue;
  1379. }
  1380. let output = ')';
  1381. if (brace.dots === true) {
  1382. const arr = tokens.slice();
  1383. const range = [];
  1384. for (let i = arr.length - 1; i >= 0; i--) {
  1385. tokens.pop();
  1386. if (arr[i].type === 'brace') {
  1387. break;
  1388. }
  1389. if (arr[i].type !== 'dots') {
  1390. range.unshift(arr[i].value);
  1391. }
  1392. }
  1393. output = expandRange(range, opts);
  1394. state.backtrack = true;
  1395. }
  1396. if (brace.comma !== true && brace.dots !== true) {
  1397. const out = state.output.slice(0, brace.outputIndex);
  1398. const toks = state.tokens.slice(brace.tokensIndex);
  1399. brace.value = brace.output = '\\{';
  1400. value = output = '\\}';
  1401. state.output = out;
  1402. for (const t of toks) {
  1403. state.output += (t.output || t.value);
  1404. }
  1405. }
  1406. push({ type: 'brace', value, output });
  1407. decrement('braces');
  1408. braces.pop();
  1409. continue;
  1410. }
  1411. /**
  1412. * Pipes
  1413. */
  1414. if (value === '|') {
  1415. if (extglobs.length > 0) {
  1416. extglobs[extglobs.length - 1].conditions++;
  1417. }
  1418. push({ type: 'text', value });
  1419. continue;
  1420. }
  1421. /**
  1422. * Commas
  1423. */
  1424. if (value === ',') {
  1425. let output = value;
  1426. const brace = braces[braces.length - 1];
  1427. if (brace && stack[stack.length - 1] === 'braces') {
  1428. brace.comma = true;
  1429. output = '|';
  1430. }
  1431. push({ type: 'comma', value, output });
  1432. continue;
  1433. }
  1434. /**
  1435. * Slashes
  1436. */
  1437. if (value === '/') {
  1438. // if the beginning of the glob is "./", advance the start
  1439. // to the current index, and don't add the "./" characters
  1440. // to the state. This greatly simplifies lookbehinds when
  1441. // checking for BOS characters like "!" and "." (not "./")
  1442. if (prev.type === 'dot' && state.index === state.start + 1) {
  1443. state.start = state.index + 1;
  1444. state.consumed = '';
  1445. state.output = '';
  1446. tokens.pop();
  1447. prev = bos; // reset "prev" to the first token
  1448. continue;
  1449. }
  1450. push({ type: 'slash', value, output: SLASH_LITERAL });
  1451. continue;
  1452. }
  1453. /**
  1454. * Dots
  1455. */
  1456. if (value === '.') {
  1457. if (state.braces > 0 && prev.type === 'dot') {
  1458. if (prev.value === '.') prev.output = DOT_LITERAL;
  1459. const brace = braces[braces.length - 1];
  1460. prev.type = 'dots';
  1461. prev.output += value;
  1462. prev.value += value;
  1463. brace.dots = true;
  1464. continue;
  1465. }
  1466. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  1467. push({ type: 'text', value, output: DOT_LITERAL });
  1468. continue;
  1469. }
  1470. push({ type: 'dot', value, output: DOT_LITERAL });
  1471. continue;
  1472. }
  1473. /**
  1474. * Question marks
  1475. */
  1476. if (value === '?') {
  1477. const isGroup = prev && prev.value === '(';
  1478. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1479. extglobOpen('qmark', value);
  1480. continue;
  1481. }
  1482. if (prev && prev.type === 'paren') {
  1483. const next = peek();
  1484. let output = value;
  1485. if (next === '<' && !utils$i.supportsLookbehinds()) {
  1486. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  1487. }
  1488. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  1489. output = `\\${value}`;
  1490. }
  1491. push({ type: 'text', value, output });
  1492. continue;
  1493. }
  1494. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  1495. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  1496. continue;
  1497. }
  1498. push({ type: 'qmark', value, output: QMARK });
  1499. continue;
  1500. }
  1501. /**
  1502. * Exclamation
  1503. */
  1504. if (value === '!') {
  1505. if (opts.noextglob !== true && peek() === '(') {
  1506. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  1507. extglobOpen('negate', value);
  1508. continue;
  1509. }
  1510. }
  1511. if (opts.nonegate !== true && state.index === 0) {
  1512. negate();
  1513. continue;
  1514. }
  1515. }
  1516. /**
  1517. * Plus
  1518. */
  1519. if (value === '+') {
  1520. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1521. extglobOpen('plus', value);
  1522. continue;
  1523. }
  1524. if ((prev && prev.value === '(') || opts.regex === false) {
  1525. push({ type: 'plus', value, output: PLUS_LITERAL });
  1526. continue;
  1527. }
  1528. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  1529. push({ type: 'plus', value });
  1530. continue;
  1531. }
  1532. push({ type: 'plus', value: PLUS_LITERAL });
  1533. continue;
  1534. }
  1535. /**
  1536. * Plain text
  1537. */
  1538. if (value === '@') {
  1539. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1540. push({ type: 'at', extglob: true, value, output: '' });
  1541. continue;
  1542. }
  1543. push({ type: 'text', value });
  1544. continue;
  1545. }
  1546. /**
  1547. * Plain text
  1548. */
  1549. if (value !== '*') {
  1550. if (value === '$' || value === '^') {
  1551. value = `\\${value}`;
  1552. }
  1553. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  1554. if (match) {
  1555. value += match[0];
  1556. state.index += match[0].length;
  1557. }
  1558. push({ type: 'text', value });
  1559. continue;
  1560. }
  1561. /**
  1562. * Stars
  1563. */
  1564. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  1565. prev.type = 'star';
  1566. prev.star = true;
  1567. prev.value += value;
  1568. prev.output = star;
  1569. state.backtrack = true;
  1570. state.globstar = true;
  1571. consume(value);
  1572. continue;
  1573. }
  1574. let rest = remaining();
  1575. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  1576. extglobOpen('star', value);
  1577. continue;
  1578. }
  1579. if (prev.type === 'star') {
  1580. if (opts.noglobstar === true) {
  1581. consume(value);
  1582. continue;
  1583. }
  1584. const prior = prev.prev;
  1585. const before = prior.prev;
  1586. const isStart = prior.type === 'slash' || prior.type === 'bos';
  1587. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  1588. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  1589. push({ type: 'star', value, output: '' });
  1590. continue;
  1591. }
  1592. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  1593. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  1594. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  1595. push({ type: 'star', value, output: '' });
  1596. continue;
  1597. }
  1598. // strip consecutive `/**/`
  1599. while (rest.slice(0, 3) === '/**') {
  1600. const after = input[state.index + 4];
  1601. if (after && after !== '/') {
  1602. break;
  1603. }
  1604. rest = rest.slice(3);
  1605. consume('/**', 3);
  1606. }
  1607. if (prior.type === 'bos' && eos()) {
  1608. prev.type = 'globstar';
  1609. prev.value += value;
  1610. prev.output = globstar(opts);
  1611. state.output = prev.output;
  1612. state.globstar = true;
  1613. consume(value);
  1614. continue;
  1615. }
  1616. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  1617. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1618. prior.output = `(?:${prior.output}`;
  1619. prev.type = 'globstar';
  1620. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  1621. prev.value += value;
  1622. state.globstar = true;
  1623. state.output += prior.output + prev.output;
  1624. consume(value);
  1625. continue;
  1626. }
  1627. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  1628. const end = rest[1] !== void 0 ? '|$' : '';
  1629. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1630. prior.output = `(?:${prior.output}`;
  1631. prev.type = 'globstar';
  1632. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  1633. prev.value += value;
  1634. state.output += prior.output + prev.output;
  1635. state.globstar = true;
  1636. consume(value + advance());
  1637. push({ type: 'slash', value: '/', output: '' });
  1638. continue;
  1639. }
  1640. if (prior.type === 'bos' && rest[0] === '/') {
  1641. prev.type = 'globstar';
  1642. prev.value += value;
  1643. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  1644. state.output = prev.output;
  1645. state.globstar = true;
  1646. consume(value + advance());
  1647. push({ type: 'slash', value: '/', output: '' });
  1648. continue;
  1649. }
  1650. // remove single star from output
  1651. state.output = state.output.slice(0, -prev.output.length);
  1652. // reset previous token to globstar
  1653. prev.type = 'globstar';
  1654. prev.output = globstar(opts);
  1655. prev.value += value;
  1656. // reset output with globstar
  1657. state.output += prev.output;
  1658. state.globstar = true;
  1659. consume(value);
  1660. continue;
  1661. }
  1662. const token = { type: 'star', value, output: star };
  1663. if (opts.bash === true) {
  1664. token.output = '.*?';
  1665. if (prev.type === 'bos' || prev.type === 'slash') {
  1666. token.output = nodot + token.output;
  1667. }
  1668. push(token);
  1669. continue;
  1670. }
  1671. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  1672. token.output = value;
  1673. push(token);
  1674. continue;
  1675. }
  1676. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  1677. if (prev.type === 'dot') {
  1678. state.output += NO_DOT_SLASH;
  1679. prev.output += NO_DOT_SLASH;
  1680. } else if (opts.dot === true) {
  1681. state.output += NO_DOTS_SLASH;
  1682. prev.output += NO_DOTS_SLASH;
  1683. } else {
  1684. state.output += nodot;
  1685. prev.output += nodot;
  1686. }
  1687. if (peek() !== '*') {
  1688. state.output += ONE_CHAR;
  1689. prev.output += ONE_CHAR;
  1690. }
  1691. }
  1692. push(token);
  1693. }
  1694. while (state.brackets > 0) {
  1695. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  1696. state.output = utils$i.escapeLast(state.output, '[');
  1697. decrement('brackets');
  1698. }
  1699. while (state.parens > 0) {
  1700. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  1701. state.output = utils$i.escapeLast(state.output, '(');
  1702. decrement('parens');
  1703. }
  1704. while (state.braces > 0) {
  1705. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  1706. state.output = utils$i.escapeLast(state.output, '{');
  1707. decrement('braces');
  1708. }
  1709. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  1710. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  1711. }
  1712. // rebuild the output if we had to backtrack at any point
  1713. if (state.backtrack === true) {
  1714. state.output = '';
  1715. for (const token of state.tokens) {
  1716. state.output += token.output != null ? token.output : token.value;
  1717. if (token.suffix) {
  1718. state.output += token.suffix;
  1719. }
  1720. }
  1721. }
  1722. return state;
  1723. };
  1724. /**
  1725. * Fast paths for creating regular expressions for common glob patterns.
  1726. * This can significantly speed up processing and has very little downside
  1727. * impact when none of the fast paths match.
  1728. */
  1729. parse$h.fastpaths = (input, options) => {
  1730. const opts = { ...options };
  1731. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  1732. const len = input.length;
  1733. if (len > max) {
  1734. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1735. }
  1736. input = REPLACEMENTS[input] || input;
  1737. const win32 = utils$i.isWindows(options);
  1738. // create constants based on platform, for windows or posix
  1739. const {
  1740. DOT_LITERAL,
  1741. SLASH_LITERAL,
  1742. ONE_CHAR,
  1743. DOTS_SLASH,
  1744. NO_DOT,
  1745. NO_DOTS,
  1746. NO_DOTS_SLASH,
  1747. STAR,
  1748. START_ANCHOR
  1749. } = constants$5.globChars(win32);
  1750. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  1751. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  1752. const capture = opts.capture ? '' : '?:';
  1753. const state = { negated: false, prefix: '' };
  1754. let star = opts.bash === true ? '.*?' : STAR;
  1755. if (opts.capture) {
  1756. star = `(${star})`;
  1757. }
  1758. const globstar = opts => {
  1759. if (opts.noglobstar === true) return star;
  1760. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1761. };
  1762. const create = str => {
  1763. switch (str) {
  1764. case '*':
  1765. return `${nodot}${ONE_CHAR}${star}`;
  1766. case '.*':
  1767. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  1768. case '*.*':
  1769. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1770. case '*/*':
  1771. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  1772. case '**':
  1773. return nodot + globstar(opts);
  1774. case '**/*':
  1775. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  1776. case '**/*.*':
  1777. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1778. case '**/.*':
  1779. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  1780. default: {
  1781. const match = /^(.*?)\.(\w+)$/.exec(str);
  1782. if (!match) return;
  1783. const source = create(match[1]);
  1784. if (!source) return;
  1785. return source + DOT_LITERAL + match[2];
  1786. }
  1787. }
  1788. };
  1789. const output = utils$i.removePrefix(input, state);
  1790. let source = create(output);
  1791. if (source && opts.strictSlashes !== true) {
  1792. source += `${SLASH_LITERAL}?`;
  1793. }
  1794. return source;
  1795. };
  1796. var parse_1$3 = parse$h;
  1797. const path$m = require$$0$4;
  1798. const scan$1 = scan_1;
  1799. const parse$g = parse_1$3;
  1800. const utils$h = utils$k;
  1801. const constants$4 = constants$6;
  1802. const isObject$4 = val => val && typeof val === 'object' && !Array.isArray(val);
  1803. /**
  1804. * Creates a matcher function from one or more glob patterns. The
  1805. * returned function takes a string to match as its first argument,
  1806. * and returns true if the string is a match. The returned matcher
  1807. * function also takes a boolean as the second argument that, when true,
  1808. * returns an object with additional information.
  1809. *
  1810. * ```js
  1811. * const picomatch = require('picomatch');
  1812. * // picomatch(glob[, options]);
  1813. *
  1814. * const isMatch = picomatch('*.!(*a)');
  1815. * console.log(isMatch('a.a')); //=> false
  1816. * console.log(isMatch('a.b')); //=> true
  1817. * ```
  1818. * @name picomatch
  1819. * @param {String|Array} `globs` One or more glob patterns.
  1820. * @param {Object=} `options`
  1821. * @return {Function=} Returns a matcher function.
  1822. * @api public
  1823. */
  1824. const picomatch$5 = (glob, options, returnState = false) => {
  1825. if (Array.isArray(glob)) {
  1826. const fns = glob.map(input => picomatch$5(input, options, returnState));
  1827. const arrayMatcher = str => {
  1828. for (const isMatch of fns) {
  1829. const state = isMatch(str);
  1830. if (state) return state;
  1831. }
  1832. return false;
  1833. };
  1834. return arrayMatcher;
  1835. }
  1836. const isState = isObject$4(glob) && glob.tokens && glob.input;
  1837. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  1838. throw new TypeError('Expected pattern to be a non-empty string');
  1839. }
  1840. const opts = options || {};
  1841. const posix = utils$h.isWindows(options);
  1842. const regex = isState
  1843. ? picomatch$5.compileRe(glob, options)
  1844. : picomatch$5.makeRe(glob, options, false, true);
  1845. const state = regex.state;
  1846. delete regex.state;
  1847. let isIgnored = () => false;
  1848. if (opts.ignore) {
  1849. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  1850. isIgnored = picomatch$5(opts.ignore, ignoreOpts, returnState);
  1851. }
  1852. const matcher = (input, returnObject = false) => {
  1853. const { isMatch, match, output } = picomatch$5.test(input, regex, options, { glob, posix });
  1854. const result = { glob, state, regex, posix, input, output, match, isMatch };
  1855. if (typeof opts.onResult === 'function') {
  1856. opts.onResult(result);
  1857. }
  1858. if (isMatch === false) {
  1859. result.isMatch = false;
  1860. return returnObject ? result : false;
  1861. }
  1862. if (isIgnored(input)) {
  1863. if (typeof opts.onIgnore === 'function') {
  1864. opts.onIgnore(result);
  1865. }
  1866. result.isMatch = false;
  1867. return returnObject ? result : false;
  1868. }
  1869. if (typeof opts.onMatch === 'function') {
  1870. opts.onMatch(result);
  1871. }
  1872. return returnObject ? result : true;
  1873. };
  1874. if (returnState) {
  1875. matcher.state = state;
  1876. }
  1877. return matcher;
  1878. };
  1879. /**
  1880. * Test `input` with the given `regex`. This is used by the main
  1881. * `picomatch()` function to test the input string.
  1882. *
  1883. * ```js
  1884. * const picomatch = require('picomatch');
  1885. * // picomatch.test(input, regex[, options]);
  1886. *
  1887. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  1888. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  1889. * ```
  1890. * @param {String} `input` String to test.
  1891. * @param {RegExp} `regex`
  1892. * @return {Object} Returns an object with matching info.
  1893. * @api public
  1894. */
  1895. picomatch$5.test = (input, regex, options, { glob, posix } = {}) => {
  1896. if (typeof input !== 'string') {
  1897. throw new TypeError('Expected input to be a string');
  1898. }
  1899. if (input === '') {
  1900. return { isMatch: false, output: '' };
  1901. }
  1902. const opts = options || {};
  1903. const format = opts.format || (posix ? utils$h.toPosixSlashes : null);
  1904. let match = input === glob;
  1905. let output = (match && format) ? format(input) : input;
  1906. if (match === false) {
  1907. output = format ? format(input) : input;
  1908. match = output === glob;
  1909. }
  1910. if (match === false || opts.capture === true) {
  1911. if (opts.matchBase === true || opts.basename === true) {
  1912. match = picomatch$5.matchBase(input, regex, options, posix);
  1913. } else {
  1914. match = regex.exec(output);
  1915. }
  1916. }
  1917. return { isMatch: Boolean(match), match, output };
  1918. };
  1919. /**
  1920. * Match the basename of a filepath.
  1921. *
  1922. * ```js
  1923. * const picomatch = require('picomatch');
  1924. * // picomatch.matchBase(input, glob[, options]);
  1925. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  1926. * ```
  1927. * @param {String} `input` String to test.
  1928. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  1929. * @return {Boolean}
  1930. * @api public
  1931. */
  1932. picomatch$5.matchBase = (input, glob, options, posix = utils$h.isWindows(options)) => {
  1933. const regex = glob instanceof RegExp ? glob : picomatch$5.makeRe(glob, options);
  1934. return regex.test(path$m.basename(input));
  1935. };
  1936. /**
  1937. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  1938. *
  1939. * ```js
  1940. * const picomatch = require('picomatch');
  1941. * // picomatch.isMatch(string, patterns[, options]);
  1942. *
  1943. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  1944. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  1945. * ```
  1946. * @param {String|Array} str The string to test.
  1947. * @param {String|Array} patterns One or more glob patterns to use for matching.
  1948. * @param {Object} [options] See available [options](#options).
  1949. * @return {Boolean} Returns true if any patterns match `str`
  1950. * @api public
  1951. */
  1952. picomatch$5.isMatch = (str, patterns, options) => picomatch$5(patterns, options)(str);
  1953. /**
  1954. * Parse a glob pattern to create the source string for a regular
  1955. * expression.
  1956. *
  1957. * ```js
  1958. * const picomatch = require('picomatch');
  1959. * const result = picomatch.parse(pattern[, options]);
  1960. * ```
  1961. * @param {String} `pattern`
  1962. * @param {Object} `options`
  1963. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  1964. * @api public
  1965. */
  1966. picomatch$5.parse = (pattern, options) => {
  1967. if (Array.isArray(pattern)) return pattern.map(p => picomatch$5.parse(p, options));
  1968. return parse$g(pattern, { ...options, fastpaths: false });
  1969. };
  1970. /**
  1971. * Scan a glob pattern to separate the pattern into segments.
  1972. *
  1973. * ```js
  1974. * const picomatch = require('picomatch');
  1975. * // picomatch.scan(input[, options]);
  1976. *
  1977. * const result = picomatch.scan('!./foo/*.js');
  1978. * console.log(result);
  1979. * { prefix: '!./',
  1980. * input: '!./foo/*.js',
  1981. * start: 3,
  1982. * base: 'foo',
  1983. * glob: '*.js',
  1984. * isBrace: false,
  1985. * isBracket: false,
  1986. * isGlob: true,
  1987. * isExtglob: false,
  1988. * isGlobstar: false,
  1989. * negated: true }
  1990. * ```
  1991. * @param {String} `input` Glob pattern to scan.
  1992. * @param {Object} `options`
  1993. * @return {Object} Returns an object with
  1994. * @api public
  1995. */
  1996. picomatch$5.scan = (input, options) => scan$1(input, options);
  1997. /**
  1998. * Compile a regular expression from the `state` object returned by the
  1999. * [parse()](#parse) method.
  2000. *
  2001. * @param {Object} `state`
  2002. * @param {Object} `options`
  2003. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  2004. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  2005. * @return {RegExp}
  2006. * @api public
  2007. */
  2008. picomatch$5.compileRe = (state, options, returnOutput = false, returnState = false) => {
  2009. if (returnOutput === true) {
  2010. return state.output;
  2011. }
  2012. const opts = options || {};
  2013. const prepend = opts.contains ? '' : '^';
  2014. const append = opts.contains ? '' : '$';
  2015. let source = `${prepend}(?:${state.output})${append}`;
  2016. if (state && state.negated === true) {
  2017. source = `^(?!${source}).*$`;
  2018. }
  2019. const regex = picomatch$5.toRegex(source, options);
  2020. if (returnState === true) {
  2021. regex.state = state;
  2022. }
  2023. return regex;
  2024. };
  2025. /**
  2026. * Create a regular expression from a parsed glob pattern.
  2027. *
  2028. * ```js
  2029. * const picomatch = require('picomatch');
  2030. * const state = picomatch.parse('*.js');
  2031. * // picomatch.compileRe(state[, options]);
  2032. *
  2033. * console.log(picomatch.compileRe(state));
  2034. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2035. * ```
  2036. * @param {String} `state` The object returned from the `.parse` method.
  2037. * @param {Object} `options`
  2038. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  2039. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  2040. * @return {RegExp} Returns a regex created from the given pattern.
  2041. * @api public
  2042. */
  2043. picomatch$5.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  2044. if (!input || typeof input !== 'string') {
  2045. throw new TypeError('Expected a non-empty string');
  2046. }
  2047. let parsed = { negated: false, fastpaths: true };
  2048. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2049. parsed.output = parse$g.fastpaths(input, options);
  2050. }
  2051. if (!parsed.output) {
  2052. parsed = parse$g(input, options);
  2053. }
  2054. return picomatch$5.compileRe(parsed, options, returnOutput, returnState);
  2055. };
  2056. /**
  2057. * Create a regular expression from the given regex source string.
  2058. *
  2059. * ```js
  2060. * const picomatch = require('picomatch');
  2061. * // picomatch.toRegex(source[, options]);
  2062. *
  2063. * const { output } = picomatch.parse('*.js');
  2064. * console.log(picomatch.toRegex(output));
  2065. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2066. * ```
  2067. * @param {String} `source` Regular expression source string.
  2068. * @param {Object} `options`
  2069. * @return {RegExp}
  2070. * @api public
  2071. */
  2072. picomatch$5.toRegex = (source, options) => {
  2073. try {
  2074. const opts = options || {};
  2075. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2076. } catch (err) {
  2077. if (options && options.debug === true) throw err;
  2078. return /$^/;
  2079. }
  2080. };
  2081. /**
  2082. * Picomatch constants.
  2083. * @return {Object}
  2084. */
  2085. picomatch$5.constants = constants$4;
  2086. /**
  2087. * Expose "picomatch"
  2088. */
  2089. var picomatch_1 = picomatch$5;
  2090. var picomatch$3 = picomatch_1;
  2091. var picomatch$4 = /*@__PURE__*/getDefaultExportFromCjs(picomatch$3);
  2092. const extractors = {
  2093. ArrayPattern(names, param) {
  2094. for (const element of param.elements) {
  2095. if (element)
  2096. extractors[element.type](names, element);
  2097. }
  2098. },
  2099. AssignmentPattern(names, param) {
  2100. extractors[param.left.type](names, param.left);
  2101. },
  2102. Identifier(names, param) {
  2103. names.push(param.name);
  2104. },
  2105. MemberExpression() { },
  2106. ObjectPattern(names, param) {
  2107. for (const prop of param.properties) {
  2108. // @ts-ignore Typescript reports that this is not a valid type
  2109. if (prop.type === 'RestElement') {
  2110. extractors.RestElement(names, prop);
  2111. }
  2112. else {
  2113. extractors[prop.value.type](names, prop.value);
  2114. }
  2115. }
  2116. },
  2117. RestElement(names, param) {
  2118. extractors[param.argument.type](names, param.argument);
  2119. }
  2120. };
  2121. const extractAssignedNames = function extractAssignedNames(param) {
  2122. const names = [];
  2123. extractors[param.type](names, param);
  2124. return names;
  2125. };
  2126. const blockDeclarations = {
  2127. const: true,
  2128. let: true
  2129. };
  2130. let Scope$1 = class Scope {
  2131. constructor(options = {}) {
  2132. this.parent = options.parent;
  2133. this.isBlockScope = !!options.block;
  2134. this.declarations = Object.create(null);
  2135. if (options.params) {
  2136. options.params.forEach((param) => {
  2137. extractAssignedNames(param).forEach((name) => {
  2138. this.declarations[name] = true;
  2139. });
  2140. });
  2141. }
  2142. }
  2143. addDeclaration(node, isBlockDeclaration, isVar) {
  2144. if (!isBlockDeclaration && this.isBlockScope) {
  2145. // it's a `var` or function node, and this
  2146. // is a block scope, so we need to go up
  2147. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  2148. }
  2149. else if (node.id) {
  2150. extractAssignedNames(node.id).forEach((name) => {
  2151. this.declarations[name] = true;
  2152. });
  2153. }
  2154. }
  2155. contains(name) {
  2156. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  2157. }
  2158. };
  2159. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  2160. let scope = new Scope$1();
  2161. walk$4(ast, {
  2162. enter(n, parent) {
  2163. const node = n;
  2164. // function foo () {...}
  2165. // class Foo {...}
  2166. if (/(Function|Class)Declaration/.test(node.type)) {
  2167. scope.addDeclaration(node, false, false);
  2168. }
  2169. // var foo = 1
  2170. if (node.type === 'VariableDeclaration') {
  2171. const { kind } = node;
  2172. const isBlockDeclaration = blockDeclarations[kind];
  2173. node.declarations.forEach((declaration) => {
  2174. scope.addDeclaration(declaration, isBlockDeclaration, true);
  2175. });
  2176. }
  2177. let newScope;
  2178. // create new function scope
  2179. if (/Function/.test(node.type)) {
  2180. const func = node;
  2181. newScope = new Scope$1({
  2182. parent: scope,
  2183. block: false,
  2184. params: func.params
  2185. });
  2186. // named function expressions - the name is considered
  2187. // part of the function's scope
  2188. if (func.type === 'FunctionExpression' && func.id) {
  2189. newScope.addDeclaration(func, false, false);
  2190. }
  2191. }
  2192. // create new for scope
  2193. if (/For(In|Of)?Statement/.test(node.type)) {
  2194. newScope = new Scope$1({
  2195. parent: scope,
  2196. block: true
  2197. });
  2198. }
  2199. // create new block scope
  2200. if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
  2201. newScope = new Scope$1({
  2202. parent: scope,
  2203. block: true
  2204. });
  2205. }
  2206. // catch clause has its own block scope
  2207. if (node.type === 'CatchClause') {
  2208. newScope = new Scope$1({
  2209. parent: scope,
  2210. params: node.param ? [node.param] : [],
  2211. block: true
  2212. });
  2213. }
  2214. if (newScope) {
  2215. Object.defineProperty(node, propertyName, {
  2216. value: newScope,
  2217. configurable: true
  2218. });
  2219. scope = newScope;
  2220. }
  2221. },
  2222. leave(n) {
  2223. const node = n;
  2224. if (node[propertyName])
  2225. scope = scope.parent;
  2226. }
  2227. });
  2228. return scope;
  2229. };
  2230. // Helper since Typescript can't detect readonly arrays with Array.isArray
  2231. function isArray$2(arg) {
  2232. return Array.isArray(arg);
  2233. }
  2234. function ensureArray(thing) {
  2235. if (isArray$2(thing))
  2236. return thing;
  2237. if (thing == null)
  2238. return [];
  2239. return [thing];
  2240. }
  2241. const normalizePath$5 = function normalizePath(filename) {
  2242. return filename.split(win32.sep).join(posix.sep);
  2243. };
  2244. function getMatcherString(id, resolutionBase) {
  2245. if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('*')) {
  2246. return normalizePath$5(id);
  2247. }
  2248. // resolve('') is valid and will default to process.cwd()
  2249. const basePath = normalizePath$5(resolve$3(resolutionBase || ''))
  2250. // escape all possible (posix + win) path characters that might interfere with regex
  2251. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  2252. // Note that we use posix.join because:
  2253. // 1. the basePath has been normalized to use /
  2254. // 2. the incoming glob (id) matcher, also uses /
  2255. // otherwise Node will force backslash (\) on windows
  2256. return posix.join(basePath, normalizePath$5(id));
  2257. }
  2258. const createFilter$1 = function createFilter(include, exclude, options) {
  2259. const resolutionBase = options && options.resolve;
  2260. const getMatcher = (id) => id instanceof RegExp
  2261. ? id
  2262. : {
  2263. test: (what) => {
  2264. // this refactor is a tad overly verbose but makes for easy debugging
  2265. const pattern = getMatcherString(id, resolutionBase);
  2266. const fn = picomatch$4(pattern, { dot: true });
  2267. const result = fn(what);
  2268. return result;
  2269. }
  2270. };
  2271. const includeMatchers = ensureArray(include).map(getMatcher);
  2272. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  2273. return function result(id) {
  2274. if (typeof id !== 'string')
  2275. return false;
  2276. if (/\0/.test(id))
  2277. return false;
  2278. const pathId = normalizePath$5(id);
  2279. for (let i = 0; i < excludeMatchers.length; ++i) {
  2280. const matcher = excludeMatchers[i];
  2281. if (matcher.test(pathId))
  2282. return false;
  2283. }
  2284. for (let i = 0; i < includeMatchers.length; ++i) {
  2285. const matcher = includeMatchers[i];
  2286. if (matcher.test(pathId))
  2287. return true;
  2288. }
  2289. return !includeMatchers.length;
  2290. };
  2291. };
  2292. const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  2293. const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  2294. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
  2295. forbiddenIdentifiers.add('');
  2296. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  2297. let identifier = str
  2298. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2299. .replace(/[^$_a-zA-Z0-9]/g, '_');
  2300. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
  2301. identifier = `_${identifier}`;
  2302. }
  2303. return identifier || '_';
  2304. };
  2305. function stringify$8(obj) {
  2306. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  2307. }
  2308. function serializeArray(arr, indent, baseIndent) {
  2309. let output = '[';
  2310. const separator = indent ? `\n${baseIndent}${indent}` : '';
  2311. for (let i = 0; i < arr.length; i++) {
  2312. const key = arr[i];
  2313. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  2314. }
  2315. return `${output}${indent ? `\n${baseIndent}` : ''}]`;
  2316. }
  2317. function serializeObject(obj, indent, baseIndent) {
  2318. let output = '{';
  2319. const separator = indent ? `\n${baseIndent}${indent}` : '';
  2320. const entries = Object.entries(obj);
  2321. for (let i = 0; i < entries.length; i++) {
  2322. const [key, value] = entries[i];
  2323. const stringKey = makeLegalIdentifier(key) === key ? key : stringify$8(key);
  2324. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
  2325. }
  2326. return `${output}${indent ? `\n${baseIndent}` : ''}}`;
  2327. }
  2328. function serialize(obj, indent, baseIndent) {
  2329. if (typeof obj === 'object' && obj !== null) {
  2330. if (Array.isArray(obj))
  2331. return serializeArray(obj, indent, baseIndent);
  2332. if (obj instanceof Date)
  2333. return `new Date(${obj.getTime()})`;
  2334. if (obj instanceof RegExp)
  2335. return obj.toString();
  2336. return serializeObject(obj, indent, baseIndent);
  2337. }
  2338. if (typeof obj === 'number') {
  2339. if (obj === Infinity)
  2340. return 'Infinity';
  2341. if (obj === -Infinity)
  2342. return '-Infinity';
  2343. if (obj === 0)
  2344. return 1 / obj === Infinity ? '0' : '-0';
  2345. if (obj !== obj)
  2346. return 'NaN'; // eslint-disable-line no-self-compare
  2347. }
  2348. if (typeof obj === 'symbol') {
  2349. const key = Symbol.keyFor(obj);
  2350. // eslint-disable-next-line no-undefined
  2351. if (key !== undefined)
  2352. return `Symbol.for(${stringify$8(key)})`;
  2353. }
  2354. if (typeof obj === 'bigint')
  2355. return `${obj}n`;
  2356. return stringify$8(obj);
  2357. }
  2358. const dataToEsm = function dataToEsm(data, options = {}) {
  2359. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  2360. const _ = options.compact ? '' : ' ';
  2361. const n = options.compact ? '' : '\n';
  2362. const declarationType = options.preferConst ? 'const' : 'var';
  2363. if (options.namedExports === false ||
  2364. typeof data !== 'object' ||
  2365. Array.isArray(data) ||
  2366. data instanceof Date ||
  2367. data instanceof RegExp ||
  2368. data === null) {
  2369. const code = serialize(data, options.compact ? null : t, '');
  2370. const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
  2371. return `export default${magic}${code};`;
  2372. }
  2373. let namedExportCode = '';
  2374. const defaultExportRows = [];
  2375. for (const [key, value] of Object.entries(data)) {
  2376. if (key === makeLegalIdentifier(key)) {
  2377. if (options.objectShorthand)
  2378. defaultExportRows.push(key);
  2379. else
  2380. defaultExportRows.push(`${key}:${_}${key}`);
  2381. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  2382. }
  2383. else {
  2384. defaultExportRows.push(`${stringify$8(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
  2385. }
  2386. }
  2387. return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  2388. };
  2389. var path$l = require$$0$4;
  2390. var commondir = function (basedir, relfiles) {
  2391. if (relfiles) {
  2392. var files = relfiles.map(function (r) {
  2393. return path$l.resolve(basedir, r);
  2394. });
  2395. }
  2396. else {
  2397. var files = basedir;
  2398. }
  2399. var res = files.slice(1).reduce(function (ps, file) {
  2400. if (!file.match(/^([A-Za-z]:)?\/|\\/)) {
  2401. throw new Error('relative path without a basedir');
  2402. }
  2403. var xs = file.split(/\/+|\\+/);
  2404. for (
  2405. var i = 0;
  2406. ps[i] === xs[i] && i < Math.min(ps.length, xs.length);
  2407. i++
  2408. );
  2409. return ps.slice(0, i);
  2410. }, files[0].split(/\/+|\\+/));
  2411. // Windows correctly handles paths with forward-slashes
  2412. return res.length > 1 ? res.join('/') : '/'
  2413. };
  2414. var getCommonDir = /*@__PURE__*/getDefaultExportFromCjs(commondir);
  2415. var old$1 = {};
  2416. // Copyright Joyent, Inc. and other Node contributors.
  2417. //
  2418. // Permission is hereby granted, free of charge, to any person obtaining a
  2419. // copy of this software and associated documentation files (the
  2420. // "Software"), to deal in the Software without restriction, including
  2421. // without limitation the rights to use, copy, modify, merge, publish,
  2422. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2423. // persons to whom the Software is furnished to do so, subject to the
  2424. // following conditions:
  2425. //
  2426. // The above copyright notice and this permission notice shall be included
  2427. // in all copies or substantial portions of the Software.
  2428. //
  2429. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2430. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2431. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2432. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2433. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2434. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2435. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2436. var pathModule = require$$0$4;
  2437. var isWindows$6 = process.platform === 'win32';
  2438. var fs$k = require$$0__default;
  2439. // JavaScript implementation of realpath, ported from node pre-v6
  2440. var DEBUG$1 = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  2441. function rethrow() {
  2442. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  2443. // is fairly slow to generate.
  2444. var callback;
  2445. if (DEBUG$1) {
  2446. var backtrace = new Error;
  2447. callback = debugCallback;
  2448. } else
  2449. callback = missingCallback;
  2450. return callback;
  2451. function debugCallback(err) {
  2452. if (err) {
  2453. backtrace.message = err.message;
  2454. err = backtrace;
  2455. missingCallback(err);
  2456. }
  2457. }
  2458. function missingCallback(err) {
  2459. if (err) {
  2460. if (process.throwDeprecation)
  2461. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  2462. else if (!process.noDeprecation) {
  2463. var msg = 'fs: missing callback ' + (err.stack || err.message);
  2464. if (process.traceDeprecation)
  2465. console.trace(msg);
  2466. else
  2467. console.error(msg);
  2468. }
  2469. }
  2470. }
  2471. }
  2472. function maybeCallback(cb) {
  2473. return typeof cb === 'function' ? cb : rethrow();
  2474. }
  2475. // Regexp that finds the next partion of a (partial) path
  2476. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  2477. if (isWindows$6) {
  2478. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  2479. } else {
  2480. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  2481. }
  2482. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  2483. if (isWindows$6) {
  2484. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  2485. } else {
  2486. var splitRootRe = /^[\/]*/;
  2487. }
  2488. old$1.realpathSync = function realpathSync(p, cache) {
  2489. // make p is absolute
  2490. p = pathModule.resolve(p);
  2491. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  2492. return cache[p];
  2493. }
  2494. var original = p,
  2495. seenLinks = {},
  2496. knownHard = {};
  2497. // current character position in p
  2498. var pos;
  2499. // the partial path so far, including a trailing slash if any
  2500. var current;
  2501. // the partial path without a trailing slash (except when pointing at a root)
  2502. var base;
  2503. // the partial path scanned in the previous round, with slash
  2504. var previous;
  2505. start();
  2506. function start() {
  2507. // Skip over roots
  2508. var m = splitRootRe.exec(p);
  2509. pos = m[0].length;
  2510. current = m[0];
  2511. base = m[0];
  2512. previous = '';
  2513. // On windows, check that the root exists. On unix there is no need.
  2514. if (isWindows$6 && !knownHard[base]) {
  2515. fs$k.lstatSync(base);
  2516. knownHard[base] = true;
  2517. }
  2518. }
  2519. // walk down the path, swapping out linked pathparts for their real
  2520. // values
  2521. // NB: p.length changes.
  2522. while (pos < p.length) {
  2523. // find the next part
  2524. nextPartRe.lastIndex = pos;
  2525. var result = nextPartRe.exec(p);
  2526. previous = current;
  2527. current += result[0];
  2528. base = previous + result[1];
  2529. pos = nextPartRe.lastIndex;
  2530. // continue if not a symlink
  2531. if (knownHard[base] || (cache && cache[base] === base)) {
  2532. continue;
  2533. }
  2534. var resolvedLink;
  2535. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  2536. // some known symbolic link. no need to stat again.
  2537. resolvedLink = cache[base];
  2538. } else {
  2539. var stat = fs$k.lstatSync(base);
  2540. if (!stat.isSymbolicLink()) {
  2541. knownHard[base] = true;
  2542. if (cache) cache[base] = base;
  2543. continue;
  2544. }
  2545. // read the link if it wasn't read before
  2546. // dev/ino always return 0 on windows, so skip the check.
  2547. var linkTarget = null;
  2548. if (!isWindows$6) {
  2549. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  2550. if (seenLinks.hasOwnProperty(id)) {
  2551. linkTarget = seenLinks[id];
  2552. }
  2553. }
  2554. if (linkTarget === null) {
  2555. fs$k.statSync(base);
  2556. linkTarget = fs$k.readlinkSync(base);
  2557. }
  2558. resolvedLink = pathModule.resolve(previous, linkTarget);
  2559. // track this, if given a cache.
  2560. if (cache) cache[base] = resolvedLink;
  2561. if (!isWindows$6) seenLinks[id] = linkTarget;
  2562. }
  2563. // resolve the link, then start over
  2564. p = pathModule.resolve(resolvedLink, p.slice(pos));
  2565. start();
  2566. }
  2567. if (cache) cache[original] = p;
  2568. return p;
  2569. };
  2570. old$1.realpath = function realpath(p, cache, cb) {
  2571. if (typeof cb !== 'function') {
  2572. cb = maybeCallback(cache);
  2573. cache = null;
  2574. }
  2575. // make p is absolute
  2576. p = pathModule.resolve(p);
  2577. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  2578. return process.nextTick(cb.bind(null, null, cache[p]));
  2579. }
  2580. var original = p,
  2581. seenLinks = {},
  2582. knownHard = {};
  2583. // current character position in p
  2584. var pos;
  2585. // the partial path so far, including a trailing slash if any
  2586. var current;
  2587. // the partial path without a trailing slash (except when pointing at a root)
  2588. var base;
  2589. // the partial path scanned in the previous round, with slash
  2590. var previous;
  2591. start();
  2592. function start() {
  2593. // Skip over roots
  2594. var m = splitRootRe.exec(p);
  2595. pos = m[0].length;
  2596. current = m[0];
  2597. base = m[0];
  2598. previous = '';
  2599. // On windows, check that the root exists. On unix there is no need.
  2600. if (isWindows$6 && !knownHard[base]) {
  2601. fs$k.lstat(base, function(err) {
  2602. if (err) return cb(err);
  2603. knownHard[base] = true;
  2604. LOOP();
  2605. });
  2606. } else {
  2607. process.nextTick(LOOP);
  2608. }
  2609. }
  2610. // walk down the path, swapping out linked pathparts for their real
  2611. // values
  2612. function LOOP() {
  2613. // stop if scanned past end of path
  2614. if (pos >= p.length) {
  2615. if (cache) cache[original] = p;
  2616. return cb(null, p);
  2617. }
  2618. // find the next part
  2619. nextPartRe.lastIndex = pos;
  2620. var result = nextPartRe.exec(p);
  2621. previous = current;
  2622. current += result[0];
  2623. base = previous + result[1];
  2624. pos = nextPartRe.lastIndex;
  2625. // continue if not a symlink
  2626. if (knownHard[base] || (cache && cache[base] === base)) {
  2627. return process.nextTick(LOOP);
  2628. }
  2629. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  2630. // known symbolic link. no need to stat again.
  2631. return gotResolvedLink(cache[base]);
  2632. }
  2633. return fs$k.lstat(base, gotStat);
  2634. }
  2635. function gotStat(err, stat) {
  2636. if (err) return cb(err);
  2637. // if not a symlink, skip to the next path part
  2638. if (!stat.isSymbolicLink()) {
  2639. knownHard[base] = true;
  2640. if (cache) cache[base] = base;
  2641. return process.nextTick(LOOP);
  2642. }
  2643. // stat & read the link if not read before
  2644. // call gotTarget as soon as the link target is known
  2645. // dev/ino always return 0 on windows, so skip the check.
  2646. if (!isWindows$6) {
  2647. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  2648. if (seenLinks.hasOwnProperty(id)) {
  2649. return gotTarget(null, seenLinks[id], base);
  2650. }
  2651. }
  2652. fs$k.stat(base, function(err) {
  2653. if (err) return cb(err);
  2654. fs$k.readlink(base, function(err, target) {
  2655. if (!isWindows$6) seenLinks[id] = target;
  2656. gotTarget(err, target);
  2657. });
  2658. });
  2659. }
  2660. function gotTarget(err, target, base) {
  2661. if (err) return cb(err);
  2662. var resolvedLink = pathModule.resolve(previous, target);
  2663. if (cache) cache[base] = resolvedLink;
  2664. gotResolvedLink(resolvedLink);
  2665. }
  2666. function gotResolvedLink(resolvedLink) {
  2667. // resolve the link, then start over
  2668. p = pathModule.resolve(resolvedLink, p.slice(pos));
  2669. start();
  2670. }
  2671. };
  2672. var fs_realpath = realpath$2;
  2673. realpath$2.realpath = realpath$2;
  2674. realpath$2.sync = realpathSync;
  2675. realpath$2.realpathSync = realpathSync;
  2676. realpath$2.monkeypatch = monkeypatch;
  2677. realpath$2.unmonkeypatch = unmonkeypatch;
  2678. var fs$j = require$$0__default;
  2679. var origRealpath = fs$j.realpath;
  2680. var origRealpathSync = fs$j.realpathSync;
  2681. var version$4 = process.version;
  2682. var ok = /^v[0-5]\./.test(version$4);
  2683. var old = old$1;
  2684. function newError (er) {
  2685. return er && er.syscall === 'realpath' && (
  2686. er.code === 'ELOOP' ||
  2687. er.code === 'ENOMEM' ||
  2688. er.code === 'ENAMETOOLONG'
  2689. )
  2690. }
  2691. function realpath$2 (p, cache, cb) {
  2692. if (ok) {
  2693. return origRealpath(p, cache, cb)
  2694. }
  2695. if (typeof cache === 'function') {
  2696. cb = cache;
  2697. cache = null;
  2698. }
  2699. origRealpath(p, cache, function (er, result) {
  2700. if (newError(er)) {
  2701. old.realpath(p, cache, cb);
  2702. } else {
  2703. cb(er, result);
  2704. }
  2705. });
  2706. }
  2707. function realpathSync (p, cache) {
  2708. if (ok) {
  2709. return origRealpathSync(p, cache)
  2710. }
  2711. try {
  2712. return origRealpathSync(p, cache)
  2713. } catch (er) {
  2714. if (newError(er)) {
  2715. return old.realpathSync(p, cache)
  2716. } else {
  2717. throw er
  2718. }
  2719. }
  2720. }
  2721. function monkeypatch () {
  2722. fs$j.realpath = realpath$2;
  2723. fs$j.realpathSync = realpathSync;
  2724. }
  2725. function unmonkeypatch () {
  2726. fs$j.realpath = origRealpath;
  2727. fs$j.realpathSync = origRealpathSync;
  2728. }
  2729. const isWindows$5 = typeof process === 'object' &&
  2730. process &&
  2731. process.platform === 'win32';
  2732. var path$k = isWindows$5 ? { sep: '\\' } : { sep: '/' };
  2733. var balancedMatch = balanced$1;
  2734. function balanced$1(a, b, str) {
  2735. if (a instanceof RegExp) a = maybeMatch(a, str);
  2736. if (b instanceof RegExp) b = maybeMatch(b, str);
  2737. var r = range$1(a, b, str);
  2738. return r && {
  2739. start: r[0],
  2740. end: r[1],
  2741. pre: str.slice(0, r[0]),
  2742. body: str.slice(r[0] + a.length, r[1]),
  2743. post: str.slice(r[1] + b.length)
  2744. };
  2745. }
  2746. function maybeMatch(reg, str) {
  2747. var m = str.match(reg);
  2748. return m ? m[0] : null;
  2749. }
  2750. balanced$1.range = range$1;
  2751. function range$1(a, b, str) {
  2752. var begs, beg, left, right, result;
  2753. var ai = str.indexOf(a);
  2754. var bi = str.indexOf(b, ai + 1);
  2755. var i = ai;
  2756. if (ai >= 0 && bi > 0) {
  2757. if(a===b) {
  2758. return [ai, bi];
  2759. }
  2760. begs = [];
  2761. left = str.length;
  2762. while (i >= 0 && !result) {
  2763. if (i == ai) {
  2764. begs.push(i);
  2765. ai = str.indexOf(a, i + 1);
  2766. } else if (begs.length == 1) {
  2767. result = [ begs.pop(), bi ];
  2768. } else {
  2769. beg = begs.pop();
  2770. if (beg < left) {
  2771. left = beg;
  2772. right = bi;
  2773. }
  2774. bi = str.indexOf(b, i + 1);
  2775. }
  2776. i = ai < bi && ai >= 0 ? ai : bi;
  2777. }
  2778. if (begs.length) {
  2779. result = [ left, right ];
  2780. }
  2781. }
  2782. return result;
  2783. }
  2784. var balanced = balancedMatch;
  2785. var braceExpansion = expandTop;
  2786. var escSlash = '\0SLASH'+Math.random()+'\0';
  2787. var escOpen = '\0OPEN'+Math.random()+'\0';
  2788. var escClose = '\0CLOSE'+Math.random()+'\0';
  2789. var escComma = '\0COMMA'+Math.random()+'\0';
  2790. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  2791. function numeric(str) {
  2792. return parseInt(str, 10) == str
  2793. ? parseInt(str, 10)
  2794. : str.charCodeAt(0);
  2795. }
  2796. function escapeBraces(str) {
  2797. return str.split('\\\\').join(escSlash)
  2798. .split('\\{').join(escOpen)
  2799. .split('\\}').join(escClose)
  2800. .split('\\,').join(escComma)
  2801. .split('\\.').join(escPeriod);
  2802. }
  2803. function unescapeBraces(str) {
  2804. return str.split(escSlash).join('\\')
  2805. .split(escOpen).join('{')
  2806. .split(escClose).join('}')
  2807. .split(escComma).join(',')
  2808. .split(escPeriod).join('.');
  2809. }
  2810. // Basically just str.split(","), but handling cases
  2811. // where we have nested braced sections, which should be
  2812. // treated as individual members, like {a,{b,c},d}
  2813. function parseCommaParts(str) {
  2814. if (!str)
  2815. return [''];
  2816. var parts = [];
  2817. var m = balanced('{', '}', str);
  2818. if (!m)
  2819. return str.split(',');
  2820. var pre = m.pre;
  2821. var body = m.body;
  2822. var post = m.post;
  2823. var p = pre.split(',');
  2824. p[p.length-1] += '{' + body + '}';
  2825. var postParts = parseCommaParts(post);
  2826. if (post.length) {
  2827. p[p.length-1] += postParts.shift();
  2828. p.push.apply(p, postParts);
  2829. }
  2830. parts.push.apply(parts, p);
  2831. return parts;
  2832. }
  2833. function expandTop(str) {
  2834. if (!str)
  2835. return [];
  2836. // I don't know why Bash 4.3 does this, but it does.
  2837. // Anything starting with {} will have the first two bytes preserved
  2838. // but *only* at the top level, so {},a}b will not expand to anything,
  2839. // but a{},b}c will be expanded to [a}c,abc].
  2840. // One could argue that this is a bug in Bash, but since the goal of
  2841. // this module is to match Bash's rules, we escape a leading {}
  2842. if (str.substr(0, 2) === '{}') {
  2843. str = '\\{\\}' + str.substr(2);
  2844. }
  2845. return expand$4(escapeBraces(str), true).map(unescapeBraces);
  2846. }
  2847. function embrace(str) {
  2848. return '{' + str + '}';
  2849. }
  2850. function isPadded(el) {
  2851. return /^-?0\d/.test(el);
  2852. }
  2853. function lte(i, y) {
  2854. return i <= y;
  2855. }
  2856. function gte(i, y) {
  2857. return i >= y;
  2858. }
  2859. function expand$4(str, isTop) {
  2860. var expansions = [];
  2861. var m = balanced('{', '}', str);
  2862. if (!m) return [str];
  2863. // no need to expand pre, since it is guaranteed to be free of brace-sets
  2864. var pre = m.pre;
  2865. var post = m.post.length
  2866. ? expand$4(m.post, false)
  2867. : [''];
  2868. if (/\$$/.test(m.pre)) {
  2869. for (var k = 0; k < post.length; k++) {
  2870. var expansion = pre+ '{' + m.body + '}' + post[k];
  2871. expansions.push(expansion);
  2872. }
  2873. } else {
  2874. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  2875. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  2876. var isSequence = isNumericSequence || isAlphaSequence;
  2877. var isOptions = m.body.indexOf(',') >= 0;
  2878. if (!isSequence && !isOptions) {
  2879. // {a},b}
  2880. if (m.post.match(/,.*\}/)) {
  2881. str = m.pre + '{' + m.body + escClose + m.post;
  2882. return expand$4(str);
  2883. }
  2884. return [str];
  2885. }
  2886. var n;
  2887. if (isSequence) {
  2888. n = m.body.split(/\.\./);
  2889. } else {
  2890. n = parseCommaParts(m.body);
  2891. if (n.length === 1) {
  2892. // x{{a,b}}y ==> x{a}y x{b}y
  2893. n = expand$4(n[0], false).map(embrace);
  2894. if (n.length === 1) {
  2895. return post.map(function(p) {
  2896. return m.pre + n[0] + p;
  2897. });
  2898. }
  2899. }
  2900. }
  2901. // at this point, n is the parts, and we know it's not a comma set
  2902. // with a single entry.
  2903. var N;
  2904. if (isSequence) {
  2905. var x = numeric(n[0]);
  2906. var y = numeric(n[1]);
  2907. var width = Math.max(n[0].length, n[1].length);
  2908. var incr = n.length == 3
  2909. ? Math.abs(numeric(n[2]))
  2910. : 1;
  2911. var test = lte;
  2912. var reverse = y < x;
  2913. if (reverse) {
  2914. incr *= -1;
  2915. test = gte;
  2916. }
  2917. var pad = n.some(isPadded);
  2918. N = [];
  2919. for (var i = x; test(i, y); i += incr) {
  2920. var c;
  2921. if (isAlphaSequence) {
  2922. c = String.fromCharCode(i);
  2923. if (c === '\\')
  2924. c = '';
  2925. } else {
  2926. c = String(i);
  2927. if (pad) {
  2928. var need = width - c.length;
  2929. if (need > 0) {
  2930. var z = new Array(need + 1).join('0');
  2931. if (i < 0)
  2932. c = '-' + z + c.slice(1);
  2933. else
  2934. c = z + c;
  2935. }
  2936. }
  2937. }
  2938. N.push(c);
  2939. }
  2940. } else {
  2941. N = [];
  2942. for (var j = 0; j < n.length; j++) {
  2943. N.push.apply(N, expand$4(n[j], false));
  2944. }
  2945. }
  2946. for (var j = 0; j < N.length; j++) {
  2947. for (var k = 0; k < post.length; k++) {
  2948. var expansion = pre + N[j] + post[k];
  2949. if (!isTop || isSequence || expansion)
  2950. expansions.push(expansion);
  2951. }
  2952. }
  2953. }
  2954. return expansions;
  2955. }
  2956. const minimatch$1 = minimatch_1 = (p, pattern, options = {}) => {
  2957. assertValidPattern(pattern);
  2958. // shortcut: comments match nothing.
  2959. if (!options.nocomment && pattern.charAt(0) === '#') {
  2960. return false
  2961. }
  2962. return new Minimatch$1(pattern, options).match(p)
  2963. };
  2964. var minimatch_1 = minimatch$1;
  2965. const path$j = path$k;
  2966. minimatch$1.sep = path$j.sep;
  2967. const GLOBSTAR$2 = Symbol('globstar **');
  2968. minimatch$1.GLOBSTAR = GLOBSTAR$2;
  2969. const expand$3 = braceExpansion;
  2970. const plTypes = {
  2971. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  2972. '?': { open: '(?:', close: ')?' },
  2973. '+': { open: '(?:', close: ')+' },
  2974. '*': { open: '(?:', close: ')*' },
  2975. '@': { open: '(?:', close: ')' }
  2976. };
  2977. // any single thing other than /
  2978. // don't need to escape / when using new RegExp()
  2979. const qmark = '[^/]';
  2980. // * => any number of characters
  2981. const star = qmark + '*?';
  2982. // ** when dots are allowed. Anything goes, except .. and .
  2983. // not (^ or / followed by one or two dots followed by $ or /),
  2984. // followed by anything, any number of times.
  2985. const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  2986. // not a ^ or / followed by a dot,
  2987. // followed by anything, any number of times.
  2988. const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  2989. // "abc" -> { a:true, b:true, c:true }
  2990. const charSet = s => s.split('').reduce((set, c) => {
  2991. set[c] = true;
  2992. return set
  2993. }, {});
  2994. // characters that need to be escaped in RegExp.
  2995. const reSpecials = charSet('().*{}+?[]^$\\!');
  2996. // characters that indicate we have to add the pattern start
  2997. const addPatternStartSet = charSet('[.(');
  2998. // normalizes slashes.
  2999. const slashSplit = /\/+/;
  3000. minimatch$1.filter = (pattern, options = {}) =>
  3001. (p, i, list) => minimatch$1(p, pattern, options);
  3002. const ext = (a, b = {}) => {
  3003. const t = {};
  3004. Object.keys(a).forEach(k => t[k] = a[k]);
  3005. Object.keys(b).forEach(k => t[k] = b[k]);
  3006. return t
  3007. };
  3008. minimatch$1.defaults = def => {
  3009. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  3010. return minimatch$1
  3011. }
  3012. const orig = minimatch$1;
  3013. const m = (p, pattern, options) => orig(p, pattern, ext(def, options));
  3014. m.Minimatch = class Minimatch extends orig.Minimatch {
  3015. constructor (pattern, options) {
  3016. super(pattern, ext(def, options));
  3017. }
  3018. };
  3019. m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch;
  3020. m.filter = (pattern, options) => orig.filter(pattern, ext(def, options));
  3021. m.defaults = options => orig.defaults(ext(def, options));
  3022. m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options));
  3023. m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options));
  3024. m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options));
  3025. return m
  3026. };
  3027. // Brace expansion:
  3028. // a{b,c}d -> abd acd
  3029. // a{b,}c -> abc ac
  3030. // a{0..3}d -> a0d a1d a2d a3d
  3031. // a{b,c{d,e}f}g -> abg acdfg acefg
  3032. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  3033. //
  3034. // Invalid sets are not expanded.
  3035. // a{2..}b -> a{2..}b
  3036. // a{b}c -> a{b}c
  3037. minimatch$1.braceExpand = (pattern, options) => braceExpand(pattern, options);
  3038. const braceExpand = (pattern, options = {}) => {
  3039. assertValidPattern(pattern);
  3040. // Thanks to Yeting Li <https://github.com/yetingli> for
  3041. // improving this regexp to avoid a ReDOS vulnerability.
  3042. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  3043. // shortcut. no need to expand.
  3044. return [pattern]
  3045. }
  3046. return expand$3(pattern)
  3047. };
  3048. const MAX_PATTERN_LENGTH = 1024 * 64;
  3049. const assertValidPattern = pattern => {
  3050. if (typeof pattern !== 'string') {
  3051. throw new TypeError('invalid pattern')
  3052. }
  3053. if (pattern.length > MAX_PATTERN_LENGTH) {
  3054. throw new TypeError('pattern is too long')
  3055. }
  3056. };
  3057. // parse a component of the expanded set.
  3058. // At this point, no pattern may contain "/" in it
  3059. // so we're going to return a 2d array, where each entry is the full
  3060. // pattern, split on '/', and then turned into a regular expression.
  3061. // A regexp is made at the end which joins each array with an
  3062. // escaped /, and another full one which joins each regexp with |.
  3063. //
  3064. // Following the lead of Bash 4.1, note that "**" only has special meaning
  3065. // when it is the *only* thing in a path portion. Otherwise, any series
  3066. // of * is equivalent to a single *. Globstar behavior is enabled by
  3067. // default, and can be disabled by setting options.noglobstar.
  3068. const SUBPARSE = Symbol('subparse');
  3069. minimatch$1.makeRe = (pattern, options) =>
  3070. new Minimatch$1(pattern, options || {}).makeRe();
  3071. minimatch$1.match = (list, pattern, options = {}) => {
  3072. const mm = new Minimatch$1(pattern, options);
  3073. list = list.filter(f => mm.match(f));
  3074. if (mm.options.nonull && !list.length) {
  3075. list.push(pattern);
  3076. }
  3077. return list
  3078. };
  3079. // replace stuff like \* with *
  3080. const globUnescape = s => s.replace(/\\(.)/g, '$1');
  3081. const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  3082. let Minimatch$1 = class Minimatch {
  3083. constructor (pattern, options) {
  3084. assertValidPattern(pattern);
  3085. if (!options) options = {};
  3086. this.options = options;
  3087. this.set = [];
  3088. this.pattern = pattern;
  3089. this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
  3090. options.allowWindowsEscape === false;
  3091. if (this.windowsPathsNoEscape) {
  3092. this.pattern = this.pattern.replace(/\\/g, '/');
  3093. }
  3094. this.regexp = null;
  3095. this.negate = false;
  3096. this.comment = false;
  3097. this.empty = false;
  3098. this.partial = !!options.partial;
  3099. // make the set of regexps etc.
  3100. this.make();
  3101. }
  3102. debug () {}
  3103. make () {
  3104. const pattern = this.pattern;
  3105. const options = this.options;
  3106. // empty patterns and comments match nothing.
  3107. if (!options.nocomment && pattern.charAt(0) === '#') {
  3108. this.comment = true;
  3109. return
  3110. }
  3111. if (!pattern) {
  3112. this.empty = true;
  3113. return
  3114. }
  3115. // step 1: figure out negation, etc.
  3116. this.parseNegate();
  3117. // step 2: expand braces
  3118. let set = this.globSet = this.braceExpand();
  3119. if (options.debug) this.debug = (...args) => console.error(...args);
  3120. this.debug(this.pattern, set);
  3121. // step 3: now we have a set, so turn each one into a series of path-portion
  3122. // matching patterns.
  3123. // These will be regexps, except in the case of "**", which is
  3124. // set to the GLOBSTAR object for globstar behavior,
  3125. // and will not contain any / characters
  3126. set = this.globParts = set.map(s => s.split(slashSplit));
  3127. this.debug(this.pattern, set);
  3128. // glob --> regexps
  3129. set = set.map((s, si, set) => s.map(this.parse, this));
  3130. this.debug(this.pattern, set);
  3131. // filter out everything that didn't compile properly.
  3132. set = set.filter(s => s.indexOf(false) === -1);
  3133. this.debug(this.pattern, set);
  3134. this.set = set;
  3135. }
  3136. parseNegate () {
  3137. if (this.options.nonegate) return
  3138. const pattern = this.pattern;
  3139. let negate = false;
  3140. let negateOffset = 0;
  3141. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  3142. negate = !negate;
  3143. negateOffset++;
  3144. }
  3145. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  3146. this.negate = negate;
  3147. }
  3148. // set partial to true to test if, for example,
  3149. // "/a/b" matches the start of "/*/b/*/d"
  3150. // Partial means, if you run out of file before you run
  3151. // out of pattern, then that's fine, as long as all
  3152. // the parts match.
  3153. matchOne (file, pattern, partial) {
  3154. var options = this.options;
  3155. this.debug('matchOne',
  3156. { 'this': this, file: file, pattern: pattern });
  3157. this.debug('matchOne', file.length, pattern.length);
  3158. for (var fi = 0,
  3159. pi = 0,
  3160. fl = file.length,
  3161. pl = pattern.length
  3162. ; (fi < fl) && (pi < pl)
  3163. ; fi++, pi++) {
  3164. this.debug('matchOne loop');
  3165. var p = pattern[pi];
  3166. var f = file[fi];
  3167. this.debug(pattern, p, f);
  3168. // should be impossible.
  3169. // some invalid regexp stuff in the set.
  3170. /* istanbul ignore if */
  3171. if (p === false) return false
  3172. if (p === GLOBSTAR$2) {
  3173. this.debug('GLOBSTAR', [pattern, p, f]);
  3174. // "**"
  3175. // a/**/b/**/c would match the following:
  3176. // a/b/x/y/z/c
  3177. // a/x/y/z/b/c
  3178. // a/b/x/b/x/c
  3179. // a/b/c
  3180. // To do this, take the rest of the pattern after
  3181. // the **, and see if it would match the file remainder.
  3182. // If so, return success.
  3183. // If not, the ** "swallows" a segment, and try again.
  3184. // This is recursively awful.
  3185. //
  3186. // a/**/b/**/c matching a/b/x/y/z/c
  3187. // - a matches a
  3188. // - doublestar
  3189. // - matchOne(b/x/y/z/c, b/**/c)
  3190. // - b matches b
  3191. // - doublestar
  3192. // - matchOne(x/y/z/c, c) -> no
  3193. // - matchOne(y/z/c, c) -> no
  3194. // - matchOne(z/c, c) -> no
  3195. // - matchOne(c, c) yes, hit
  3196. var fr = fi;
  3197. var pr = pi + 1;
  3198. if (pr === pl) {
  3199. this.debug('** at the end');
  3200. // a ** at the end will just swallow the rest.
  3201. // We have found a match.
  3202. // however, it will not swallow /.x, unless
  3203. // options.dot is set.
  3204. // . and .. are *never* matched by **, for explosively
  3205. // exponential reasons.
  3206. for (; fi < fl; fi++) {
  3207. if (file[fi] === '.' || file[fi] === '..' ||
  3208. (!options.dot && file[fi].charAt(0) === '.')) return false
  3209. }
  3210. return true
  3211. }
  3212. // ok, let's see if we can swallow whatever we can.
  3213. while (fr < fl) {
  3214. var swallowee = file[fr];
  3215. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  3216. // XXX remove this slice. Just pass the start index.
  3217. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  3218. this.debug('globstar found match!', fr, fl, swallowee);
  3219. // found a match.
  3220. return true
  3221. } else {
  3222. // can't swallow "." or ".." ever.
  3223. // can only swallow ".foo" when explicitly asked.
  3224. if (swallowee === '.' || swallowee === '..' ||
  3225. (!options.dot && swallowee.charAt(0) === '.')) {
  3226. this.debug('dot detected!', file, fr, pattern, pr);
  3227. break
  3228. }
  3229. // ** swallows a segment, and continue.
  3230. this.debug('globstar swallow a segment, and continue');
  3231. fr++;
  3232. }
  3233. }
  3234. // no match was found.
  3235. // However, in partial mode, we can't say this is necessarily over.
  3236. // If there's more *pattern* left, then
  3237. /* istanbul ignore if */
  3238. if (partial) {
  3239. // ran out of file
  3240. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  3241. if (fr === fl) return true
  3242. }
  3243. return false
  3244. }
  3245. // something other than **
  3246. // non-magic patterns just have to match exactly
  3247. // patterns with magic have been turned into regexps.
  3248. var hit;
  3249. if (typeof p === 'string') {
  3250. hit = f === p;
  3251. this.debug('string match', p, f, hit);
  3252. } else {
  3253. hit = f.match(p);
  3254. this.debug('pattern match', p, f, hit);
  3255. }
  3256. if (!hit) return false
  3257. }
  3258. // Note: ending in / means that we'll get a final ""
  3259. // at the end of the pattern. This can only match a
  3260. // corresponding "" at the end of the file.
  3261. // If the file ends in /, then it can only match a
  3262. // a pattern that ends in /, unless the pattern just
  3263. // doesn't have any more for it. But, a/b/ should *not*
  3264. // match "a/b/*", even though "" matches against the
  3265. // [^/]*? pattern, except in partial mode, where it might
  3266. // simply not be reached yet.
  3267. // However, a/b/ should still satisfy a/*
  3268. // now either we fell off the end of the pattern, or we're done.
  3269. if (fi === fl && pi === pl) {
  3270. // ran out of pattern and filename at the same time.
  3271. // an exact hit!
  3272. return true
  3273. } else if (fi === fl) {
  3274. // ran out of file, but still had pattern left.
  3275. // this is ok if we're doing the match as part of
  3276. // a glob fs traversal.
  3277. return partial
  3278. } else /* istanbul ignore else */ if (pi === pl) {
  3279. // ran out of pattern, still have file left.
  3280. // this is only acceptable if we're on the very last
  3281. // empty segment of a file with a trailing slash.
  3282. // a/* should match a/b/
  3283. return (fi === fl - 1) && (file[fi] === '')
  3284. }
  3285. // should be unreachable.
  3286. /* istanbul ignore next */
  3287. throw new Error('wtf?')
  3288. }
  3289. braceExpand () {
  3290. return braceExpand(this.pattern, this.options)
  3291. }
  3292. parse (pattern, isSub) {
  3293. assertValidPattern(pattern);
  3294. const options = this.options;
  3295. // shortcuts
  3296. if (pattern === '**') {
  3297. if (!options.noglobstar)
  3298. return GLOBSTAR$2
  3299. else
  3300. pattern = '*';
  3301. }
  3302. if (pattern === '') return ''
  3303. let re = '';
  3304. let hasMagic = !!options.nocase;
  3305. let escaping = false;
  3306. // ? => one single character
  3307. const patternListStack = [];
  3308. const negativeLists = [];
  3309. let stateChar;
  3310. let inClass = false;
  3311. let reClassStart = -1;
  3312. let classStart = -1;
  3313. let cs;
  3314. let pl;
  3315. let sp;
  3316. // . and .. never match anything that doesn't start with .,
  3317. // even when options.dot is set.
  3318. const patternStart = pattern.charAt(0) === '.' ? '' // anything
  3319. // not (start or / followed by . or .. followed by / or end)
  3320. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  3321. : '(?!\\.)';
  3322. const clearStateChar = () => {
  3323. if (stateChar) {
  3324. // we had some state-tracking character
  3325. // that wasn't consumed by this pass.
  3326. switch (stateChar) {
  3327. case '*':
  3328. re += star;
  3329. hasMagic = true;
  3330. break
  3331. case '?':
  3332. re += qmark;
  3333. hasMagic = true;
  3334. break
  3335. default:
  3336. re += '\\' + stateChar;
  3337. break
  3338. }
  3339. this.debug('clearStateChar %j %j', stateChar, re);
  3340. stateChar = false;
  3341. }
  3342. };
  3343. for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {
  3344. this.debug('%s\t%s %s %j', pattern, i, re, c);
  3345. // skip over any that are escaped.
  3346. if (escaping) {
  3347. /* istanbul ignore next - completely not allowed, even escaped. */
  3348. if (c === '/') {
  3349. return false
  3350. }
  3351. if (reSpecials[c]) {
  3352. re += '\\';
  3353. }
  3354. re += c;
  3355. escaping = false;
  3356. continue
  3357. }
  3358. switch (c) {
  3359. /* istanbul ignore next */
  3360. case '/': {
  3361. // Should already be path-split by now.
  3362. return false
  3363. }
  3364. case '\\':
  3365. clearStateChar();
  3366. escaping = true;
  3367. continue
  3368. // the various stateChar values
  3369. // for the "extglob" stuff.
  3370. case '?':
  3371. case '*':
  3372. case '+':
  3373. case '@':
  3374. case '!':
  3375. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  3376. // all of those are literals inside a class, except that
  3377. // the glob [!a] means [^a] in regexp
  3378. if (inClass) {
  3379. this.debug(' in class');
  3380. if (c === '!' && i === classStart + 1) c = '^';
  3381. re += c;
  3382. continue
  3383. }
  3384. // if we already have a stateChar, then it means
  3385. // that there was something like ** or +? in there.
  3386. // Handle the stateChar, then proceed with this one.
  3387. this.debug('call clearStateChar %j', stateChar);
  3388. clearStateChar();
  3389. stateChar = c;
  3390. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  3391. // just clear the statechar *now*, rather than even diving into
  3392. // the patternList stuff.
  3393. if (options.noext) clearStateChar();
  3394. continue
  3395. case '(':
  3396. if (inClass) {
  3397. re += '(';
  3398. continue
  3399. }
  3400. if (!stateChar) {
  3401. re += '\\(';
  3402. continue
  3403. }
  3404. patternListStack.push({
  3405. type: stateChar,
  3406. start: i - 1,
  3407. reStart: re.length,
  3408. open: plTypes[stateChar].open,
  3409. close: plTypes[stateChar].close
  3410. });
  3411. // negation is (?:(?!js)[^/]*)
  3412. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  3413. this.debug('plType %j %j', stateChar, re);
  3414. stateChar = false;
  3415. continue
  3416. case ')':
  3417. if (inClass || !patternListStack.length) {
  3418. re += '\\)';
  3419. continue
  3420. }
  3421. clearStateChar();
  3422. hasMagic = true;
  3423. pl = patternListStack.pop();
  3424. // negation is (?:(?!js)[^/]*)
  3425. // The others are (?:<pattern>)<type>
  3426. re += pl.close;
  3427. if (pl.type === '!') {
  3428. negativeLists.push(pl);
  3429. }
  3430. pl.reEnd = re.length;
  3431. continue
  3432. case '|':
  3433. if (inClass || !patternListStack.length) {
  3434. re += '\\|';
  3435. continue
  3436. }
  3437. clearStateChar();
  3438. re += '|';
  3439. continue
  3440. // these are mostly the same in regexp and glob
  3441. case '[':
  3442. // swallow any state-tracking char before the [
  3443. clearStateChar();
  3444. if (inClass) {
  3445. re += '\\' + c;
  3446. continue
  3447. }
  3448. inClass = true;
  3449. classStart = i;
  3450. reClassStart = re.length;
  3451. re += c;
  3452. continue
  3453. case ']':
  3454. // a right bracket shall lose its special
  3455. // meaning and represent itself in
  3456. // a bracket expression if it occurs
  3457. // first in the list. -- POSIX.2 2.8.3.2
  3458. if (i === classStart + 1 || !inClass) {
  3459. re += '\\' + c;
  3460. continue
  3461. }
  3462. // handle the case where we left a class open.
  3463. // "[z-a]" is valid, equivalent to "\[z-a\]"
  3464. // split where the last [ was, make sure we don't have
  3465. // an invalid re. if so, re-walk the contents of the
  3466. // would-be class to re-translate any characters that
  3467. // were passed through as-is
  3468. // TODO: It would probably be faster to determine this
  3469. // without a try/catch and a new RegExp, but it's tricky
  3470. // to do safely. For now, this is safe and works.
  3471. cs = pattern.substring(classStart + 1, i);
  3472. // finish up the class.
  3473. hasMagic = true;
  3474. inClass = false;
  3475. re += c;
  3476. continue
  3477. default:
  3478. // swallow any state char that wasn't consumed
  3479. clearStateChar();
  3480. if (reSpecials[c] && !(c === '^' && inClass)) {
  3481. re += '\\';
  3482. }
  3483. re += c;
  3484. break
  3485. } // switch
  3486. } // for
  3487. // handle the case where we left a class open.
  3488. // "[abc" is valid, equivalent to "\[abc"
  3489. if (inClass) {
  3490. // split where the last [ was, and escape it
  3491. // this is a huge pita. We now have to re-walk
  3492. // the contents of the would-be class to re-translate
  3493. // any characters that were passed through as-is
  3494. cs = pattern.substr(classStart + 1);
  3495. sp = this.parse(cs, SUBPARSE);
  3496. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  3497. hasMagic = hasMagic || sp[1];
  3498. }
  3499. // handle the case where we had a +( thing at the *end*
  3500. // of the pattern.
  3501. // each pattern list stack adds 3 chars, and we need to go through
  3502. // and escape any | chars that were passed through as-is for the regexp.
  3503. // Go through and escape them, taking care not to double-escape any
  3504. // | chars that were already escaped.
  3505. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  3506. let tail;
  3507. tail = re.slice(pl.reStart + pl.open.length);
  3508. this.debug('setting tail', re, pl);
  3509. // maybe some even number of \, then maybe 1 \, followed by a |
  3510. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
  3511. /* istanbul ignore else - should already be done */
  3512. if (!$2) {
  3513. // the | isn't already escaped, so escape it.
  3514. $2 = '\\';
  3515. }
  3516. // need to escape all those slashes *again*, without escaping the
  3517. // one that we need for escaping the | character. As it works out,
  3518. // escaping an even number of slashes can be done by simply repeating
  3519. // it exactly after itself. That's why this trick works.
  3520. //
  3521. // I am sorry that you have to see this.
  3522. return $1 + $1 + $2 + '|'
  3523. });
  3524. this.debug('tail=%j\n %s', tail, tail, pl, re);
  3525. const t = pl.type === '*' ? star
  3526. : pl.type === '?' ? qmark
  3527. : '\\' + pl.type;
  3528. hasMagic = true;
  3529. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  3530. }
  3531. // handle trailing things that only matter at the very end.
  3532. clearStateChar();
  3533. if (escaping) {
  3534. // trailing \\
  3535. re += '\\\\';
  3536. }
  3537. // only need to apply the nodot start if the re starts with
  3538. // something that could conceivably capture a dot
  3539. const addPatternStart = addPatternStartSet[re.charAt(0)];
  3540. // Hack to work around lack of negative lookbehind in JS
  3541. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  3542. // like 'a.xyz.yz' doesn't match. So, the first negative
  3543. // lookahead, has to look ALL the way ahead, to the end of
  3544. // the pattern.
  3545. for (let n = negativeLists.length - 1; n > -1; n--) {
  3546. const nl = negativeLists[n];
  3547. const nlBefore = re.slice(0, nl.reStart);
  3548. const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  3549. let nlAfter = re.slice(nl.reEnd);
  3550. const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
  3551. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  3552. // mean that we should *not* include the ) in the bit that is considered
  3553. // "after" the negated section.
  3554. const openParensBefore = nlBefore.split('(').length - 1;
  3555. let cleanAfter = nlAfter;
  3556. for (let i = 0; i < openParensBefore; i++) {
  3557. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  3558. }
  3559. nlAfter = cleanAfter;
  3560. const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : '';
  3561. re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  3562. }
  3563. // if the re is not "" at this point, then we need to make sure
  3564. // it doesn't match against an empty path part.
  3565. // Otherwise a/* will match a/, which it should not.
  3566. if (re !== '' && hasMagic) {
  3567. re = '(?=.)' + re;
  3568. }
  3569. if (addPatternStart) {
  3570. re = patternStart + re;
  3571. }
  3572. // parsing just a piece of a larger pattern.
  3573. if (isSub === SUBPARSE) {
  3574. return [re, hasMagic]
  3575. }
  3576. // skip the regexp for non-magical patterns
  3577. // unescape anything in it, though, so that it'll be
  3578. // an exact match against a file etc.
  3579. if (!hasMagic) {
  3580. return globUnescape(pattern)
  3581. }
  3582. const flags = options.nocase ? 'i' : '';
  3583. try {
  3584. return Object.assign(new RegExp('^' + re + '$', flags), {
  3585. _glob: pattern,
  3586. _src: re,
  3587. })
  3588. } catch (er) /* istanbul ignore next - should be impossible */ {
  3589. // If it was an invalid regular expression, then it can't match
  3590. // anything. This trick looks for a character after the end of
  3591. // the string, which is of course impossible, except in multi-line
  3592. // mode, but it's not a /m regex.
  3593. return new RegExp('$.')
  3594. }
  3595. }
  3596. makeRe () {
  3597. if (this.regexp || this.regexp === false) return this.regexp
  3598. // at this point, this.set is a 2d array of partial
  3599. // pattern strings, or "**".
  3600. //
  3601. // It's better to use .match(). This function shouldn't
  3602. // be used, really, but it's pretty convenient sometimes,
  3603. // when you just want to work with a regex.
  3604. const set = this.set;
  3605. if (!set.length) {
  3606. this.regexp = false;
  3607. return this.regexp
  3608. }
  3609. const options = this.options;
  3610. const twoStar = options.noglobstar ? star
  3611. : options.dot ? twoStarDot
  3612. : twoStarNoDot;
  3613. const flags = options.nocase ? 'i' : '';
  3614. // coalesce globstars and regexpify non-globstar patterns
  3615. // if it's the only item, then we just do one twoStar
  3616. // if it's the first, and there are more, prepend (\/|twoStar\/)? to next
  3617. // if it's the last, append (\/twoStar|) to previous
  3618. // if it's in the middle, append (\/|\/twoStar\/) to previous
  3619. // then filter out GLOBSTAR symbols
  3620. let re = set.map(pattern => {
  3621. pattern = pattern.map(p =>
  3622. typeof p === 'string' ? regExpEscape(p)
  3623. : p === GLOBSTAR$2 ? GLOBSTAR$2
  3624. : p._src
  3625. ).reduce((set, p) => {
  3626. if (!(set[set.length - 1] === GLOBSTAR$2 && p === GLOBSTAR$2)) {
  3627. set.push(p);
  3628. }
  3629. return set
  3630. }, []);
  3631. pattern.forEach((p, i) => {
  3632. if (p !== GLOBSTAR$2 || pattern[i-1] === GLOBSTAR$2) {
  3633. return
  3634. }
  3635. if (i === 0) {
  3636. if (pattern.length > 1) {
  3637. pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1];
  3638. } else {
  3639. pattern[i] = twoStar;
  3640. }
  3641. } else if (i === pattern.length - 1) {
  3642. pattern[i-1] += '(?:\\\/|' + twoStar + ')?';
  3643. } else {
  3644. pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1];
  3645. pattern[i+1] = GLOBSTAR$2;
  3646. }
  3647. });
  3648. return pattern.filter(p => p !== GLOBSTAR$2).join('/')
  3649. }).join('|');
  3650. // must match entire pattern
  3651. // ending in a * or ** will make it less strict.
  3652. re = '^(?:' + re + ')$';
  3653. // can match anything, as long as it's not this.
  3654. if (this.negate) re = '^(?!' + re + ').*$';
  3655. try {
  3656. this.regexp = new RegExp(re, flags);
  3657. } catch (ex) /* istanbul ignore next - should be impossible */ {
  3658. this.regexp = false;
  3659. }
  3660. return this.regexp
  3661. }
  3662. match (f, partial = this.partial) {
  3663. this.debug('match', f, this.pattern);
  3664. // short-circuit in the case of busted things.
  3665. // comments, etc.
  3666. if (this.comment) return false
  3667. if (this.empty) return f === ''
  3668. if (f === '/' && partial) return true
  3669. const options = this.options;
  3670. // windows: need to use /, not \
  3671. if (path$j.sep !== '/') {
  3672. f = f.split(path$j.sep).join('/');
  3673. }
  3674. // treat the test path as a set of pathparts.
  3675. f = f.split(slashSplit);
  3676. this.debug(this.pattern, 'split', f);
  3677. // just ONE of the pattern sets in this.set needs to match
  3678. // in order for it to be valid. If negating, then just one
  3679. // match means that we have failed.
  3680. // Either way, return on the first hit.
  3681. const set = this.set;
  3682. this.debug(this.pattern, 'set', set);
  3683. // Find the basename of the path by looking for the last non-empty segment
  3684. let filename;
  3685. for (let i = f.length - 1; i >= 0; i--) {
  3686. filename = f[i];
  3687. if (filename) break
  3688. }
  3689. for (let i = 0; i < set.length; i++) {
  3690. const pattern = set[i];
  3691. let file = f;
  3692. if (options.matchBase && pattern.length === 1) {
  3693. file = [filename];
  3694. }
  3695. const hit = this.matchOne(file, pattern, partial);
  3696. if (hit) {
  3697. if (options.flipNegate) return true
  3698. return !this.negate
  3699. }
  3700. }
  3701. // didn't get any hits. this is success if it's a negative
  3702. // pattern, failure otherwise.
  3703. if (options.flipNegate) return false
  3704. return this.negate
  3705. }
  3706. static defaults (def) {
  3707. return minimatch$1.defaults(def).Minimatch
  3708. }
  3709. };
  3710. minimatch$1.Minimatch = Minimatch$1;
  3711. var inherits = {exports: {}};
  3712. var inherits_browser = {exports: {}};
  3713. var hasRequiredInherits_browser;
  3714. function requireInherits_browser () {
  3715. if (hasRequiredInherits_browser) return inherits_browser.exports;
  3716. hasRequiredInherits_browser = 1;
  3717. if (typeof Object.create === 'function') {
  3718. // implementation from standard node.js 'util' module
  3719. inherits_browser.exports = function inherits(ctor, superCtor) {
  3720. if (superCtor) {
  3721. ctor.super_ = superCtor;
  3722. ctor.prototype = Object.create(superCtor.prototype, {
  3723. constructor: {
  3724. value: ctor,
  3725. enumerable: false,
  3726. writable: true,
  3727. configurable: true
  3728. }
  3729. });
  3730. }
  3731. };
  3732. } else {
  3733. // old school shim for old browsers
  3734. inherits_browser.exports = function inherits(ctor, superCtor) {
  3735. if (superCtor) {
  3736. ctor.super_ = superCtor;
  3737. var TempCtor = function () {};
  3738. TempCtor.prototype = superCtor.prototype;
  3739. ctor.prototype = new TempCtor();
  3740. ctor.prototype.constructor = ctor;
  3741. }
  3742. };
  3743. }
  3744. return inherits_browser.exports;
  3745. }
  3746. try {
  3747. var util$2 = require('util');
  3748. /* istanbul ignore next */
  3749. if (typeof util$2.inherits !== 'function') throw '';
  3750. inherits.exports = util$2.inherits;
  3751. } catch (e) {
  3752. /* istanbul ignore next */
  3753. inherits.exports = requireInherits_browser();
  3754. }
  3755. var inheritsExports = inherits.exports;
  3756. var common$c = {};
  3757. common$c.setopts = setopts;
  3758. common$c.ownProp = ownProp;
  3759. common$c.makeAbs = makeAbs;
  3760. common$c.finish = finish;
  3761. common$c.mark = mark;
  3762. common$c.isIgnored = isIgnored;
  3763. common$c.childrenIgnored = childrenIgnored;
  3764. function ownProp (obj, field) {
  3765. return Object.prototype.hasOwnProperty.call(obj, field)
  3766. }
  3767. var fs$i = require$$0__default;
  3768. var path$i = require$$0$4;
  3769. var minimatch = minimatch_1;
  3770. var isAbsolute = require$$0$4.isAbsolute;
  3771. var Minimatch = minimatch.Minimatch;
  3772. function alphasort (a, b) {
  3773. return a.localeCompare(b, 'en')
  3774. }
  3775. function setupIgnores (self, options) {
  3776. self.ignore = options.ignore || [];
  3777. if (!Array.isArray(self.ignore))
  3778. self.ignore = [self.ignore];
  3779. if (self.ignore.length) {
  3780. self.ignore = self.ignore.map(ignoreMap);
  3781. }
  3782. }
  3783. // ignore patterns are always in dot:true mode.
  3784. function ignoreMap (pattern) {
  3785. var gmatcher = null;
  3786. if (pattern.slice(-3) === '/**') {
  3787. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  3788. gmatcher = new Minimatch(gpattern, { dot: true });
  3789. }
  3790. return {
  3791. matcher: new Minimatch(pattern, { dot: true }),
  3792. gmatcher: gmatcher
  3793. }
  3794. }
  3795. function setopts (self, pattern, options) {
  3796. if (!options)
  3797. options = {};
  3798. // base-matching: just use globstar for that.
  3799. if (options.matchBase && -1 === pattern.indexOf("/")) {
  3800. if (options.noglobstar) {
  3801. throw new Error("base matching requires globstar")
  3802. }
  3803. pattern = "**/" + pattern;
  3804. }
  3805. self.silent = !!options.silent;
  3806. self.pattern = pattern;
  3807. self.strict = options.strict !== false;
  3808. self.realpath = !!options.realpath;
  3809. self.realpathCache = options.realpathCache || Object.create(null);
  3810. self.follow = !!options.follow;
  3811. self.dot = !!options.dot;
  3812. self.mark = !!options.mark;
  3813. self.nodir = !!options.nodir;
  3814. if (self.nodir)
  3815. self.mark = true;
  3816. self.sync = !!options.sync;
  3817. self.nounique = !!options.nounique;
  3818. self.nonull = !!options.nonull;
  3819. self.nosort = !!options.nosort;
  3820. self.nocase = !!options.nocase;
  3821. self.stat = !!options.stat;
  3822. self.noprocess = !!options.noprocess;
  3823. self.absolute = !!options.absolute;
  3824. self.fs = options.fs || fs$i;
  3825. self.maxLength = options.maxLength || Infinity;
  3826. self.cache = options.cache || Object.create(null);
  3827. self.statCache = options.statCache || Object.create(null);
  3828. self.symlinks = options.symlinks || Object.create(null);
  3829. setupIgnores(self, options);
  3830. self.changedCwd = false;
  3831. var cwd = process.cwd();
  3832. if (!ownProp(options, "cwd"))
  3833. self.cwd = path$i.resolve(cwd);
  3834. else {
  3835. self.cwd = path$i.resolve(options.cwd);
  3836. self.changedCwd = self.cwd !== cwd;
  3837. }
  3838. self.root = options.root || path$i.resolve(self.cwd, "/");
  3839. self.root = path$i.resolve(self.root);
  3840. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  3841. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  3842. self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  3843. self.nomount = !!options.nomount;
  3844. if (process.platform === "win32") {
  3845. self.root = self.root.replace(/\\/g, "/");
  3846. self.cwd = self.cwd.replace(/\\/g, "/");
  3847. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  3848. }
  3849. // disable comments and negation in Minimatch.
  3850. // Note that they are not supported in Glob itself anyway.
  3851. options.nonegate = true;
  3852. options.nocomment = true;
  3853. // always treat \ in patterns as escapes, not path separators
  3854. options.allowWindowsEscape = true;
  3855. self.minimatch = new Minimatch(pattern, options);
  3856. self.options = self.minimatch.options;
  3857. }
  3858. function finish (self) {
  3859. var nou = self.nounique;
  3860. var all = nou ? [] : Object.create(null);
  3861. for (var i = 0, l = self.matches.length; i < l; i ++) {
  3862. var matches = self.matches[i];
  3863. if (!matches || Object.keys(matches).length === 0) {
  3864. if (self.nonull) {
  3865. // do like the shell, and spit out the literal glob
  3866. var literal = self.minimatch.globSet[i];
  3867. if (nou)
  3868. all.push(literal);
  3869. else
  3870. all[literal] = true;
  3871. }
  3872. } else {
  3873. // had matches
  3874. var m = Object.keys(matches);
  3875. if (nou)
  3876. all.push.apply(all, m);
  3877. else
  3878. m.forEach(function (m) {
  3879. all[m] = true;
  3880. });
  3881. }
  3882. }
  3883. if (!nou)
  3884. all = Object.keys(all);
  3885. if (!self.nosort)
  3886. all = all.sort(alphasort);
  3887. // at *some* point we statted all of these
  3888. if (self.mark) {
  3889. for (var i = 0; i < all.length; i++) {
  3890. all[i] = self._mark(all[i]);
  3891. }
  3892. if (self.nodir) {
  3893. all = all.filter(function (e) {
  3894. var notDir = !(/\/$/.test(e));
  3895. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  3896. if (notDir && c)
  3897. notDir = c !== 'DIR' && !Array.isArray(c);
  3898. return notDir
  3899. });
  3900. }
  3901. }
  3902. if (self.ignore.length)
  3903. all = all.filter(function(m) {
  3904. return !isIgnored(self, m)
  3905. });
  3906. self.found = all;
  3907. }
  3908. function mark (self, p) {
  3909. var abs = makeAbs(self, p);
  3910. var c = self.cache[abs];
  3911. var m = p;
  3912. if (c) {
  3913. var isDir = c === 'DIR' || Array.isArray(c);
  3914. var slash = p.slice(-1) === '/';
  3915. if (isDir && !slash)
  3916. m += '/';
  3917. else if (!isDir && slash)
  3918. m = m.slice(0, -1);
  3919. if (m !== p) {
  3920. var mabs = makeAbs(self, m);
  3921. self.statCache[mabs] = self.statCache[abs];
  3922. self.cache[mabs] = self.cache[abs];
  3923. }
  3924. }
  3925. return m
  3926. }
  3927. // lotta situps...
  3928. function makeAbs (self, f) {
  3929. var abs = f;
  3930. if (f.charAt(0) === '/') {
  3931. abs = path$i.join(self.root, f);
  3932. } else if (isAbsolute(f) || f === '') {
  3933. abs = f;
  3934. } else if (self.changedCwd) {
  3935. abs = path$i.resolve(self.cwd, f);
  3936. } else {
  3937. abs = path$i.resolve(f);
  3938. }
  3939. if (process.platform === 'win32')
  3940. abs = abs.replace(/\\/g, '/');
  3941. return abs
  3942. }
  3943. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  3944. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  3945. function isIgnored (self, path) {
  3946. if (!self.ignore.length)
  3947. return false
  3948. return self.ignore.some(function(item) {
  3949. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  3950. })
  3951. }
  3952. function childrenIgnored (self, path) {
  3953. if (!self.ignore.length)
  3954. return false
  3955. return self.ignore.some(function(item) {
  3956. return !!(item.gmatcher && item.gmatcher.match(path))
  3957. })
  3958. }
  3959. var sync$9;
  3960. var hasRequiredSync;
  3961. function requireSync () {
  3962. if (hasRequiredSync) return sync$9;
  3963. hasRequiredSync = 1;
  3964. sync$9 = globSync;
  3965. globSync.GlobSync = GlobSync;
  3966. var rp = fs_realpath;
  3967. var minimatch = minimatch_1;
  3968. requireGlob().Glob;
  3969. var path = require$$0$4;
  3970. var assert = require$$5;
  3971. var isAbsolute = require$$0$4.isAbsolute;
  3972. var common = common$c;
  3973. var setopts = common.setopts;
  3974. var ownProp = common.ownProp;
  3975. var childrenIgnored = common.childrenIgnored;
  3976. var isIgnored = common.isIgnored;
  3977. function globSync (pattern, options) {
  3978. if (typeof options === 'function' || arguments.length === 3)
  3979. throw new TypeError('callback provided to sync glob\n'+
  3980. 'See: https://github.com/isaacs/node-glob/issues/167')
  3981. return new GlobSync(pattern, options).found
  3982. }
  3983. function GlobSync (pattern, options) {
  3984. if (!pattern)
  3985. throw new Error('must provide pattern')
  3986. if (typeof options === 'function' || arguments.length === 3)
  3987. throw new TypeError('callback provided to sync glob\n'+
  3988. 'See: https://github.com/isaacs/node-glob/issues/167')
  3989. if (!(this instanceof GlobSync))
  3990. return new GlobSync(pattern, options)
  3991. setopts(this, pattern, options);
  3992. if (this.noprocess)
  3993. return this
  3994. var n = this.minimatch.set.length;
  3995. this.matches = new Array(n);
  3996. for (var i = 0; i < n; i ++) {
  3997. this._process(this.minimatch.set[i], i, false);
  3998. }
  3999. this._finish();
  4000. }
  4001. GlobSync.prototype._finish = function () {
  4002. assert.ok(this instanceof GlobSync);
  4003. if (this.realpath) {
  4004. var self = this;
  4005. this.matches.forEach(function (matchset, index) {
  4006. var set = self.matches[index] = Object.create(null);
  4007. for (var p in matchset) {
  4008. try {
  4009. p = self._makeAbs(p);
  4010. var real = rp.realpathSync(p, self.realpathCache);
  4011. set[real] = true;
  4012. } catch (er) {
  4013. if (er.syscall === 'stat')
  4014. set[self._makeAbs(p)] = true;
  4015. else
  4016. throw er
  4017. }
  4018. }
  4019. });
  4020. }
  4021. common.finish(this);
  4022. };
  4023. GlobSync.prototype._process = function (pattern, index, inGlobStar) {
  4024. assert.ok(this instanceof GlobSync);
  4025. // Get the first [n] parts of pattern that are all strings.
  4026. var n = 0;
  4027. while (typeof pattern[n] === 'string') {
  4028. n ++;
  4029. }
  4030. // now n is the index of the first one that is *not* a string.
  4031. // See if there's anything else
  4032. var prefix;
  4033. switch (n) {
  4034. // if not, then this is rather simple
  4035. case pattern.length:
  4036. this._processSimple(pattern.join('/'), index);
  4037. return
  4038. case 0:
  4039. // pattern *starts* with some non-trivial item.
  4040. // going to readdir(cwd), but not include the prefix in matches.
  4041. prefix = null;
  4042. break
  4043. default:
  4044. // pattern has some string bits in the front.
  4045. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  4046. // or 'relative' like '../baz'
  4047. prefix = pattern.slice(0, n).join('/');
  4048. break
  4049. }
  4050. var remain = pattern.slice(n);
  4051. // get the list of entries.
  4052. var read;
  4053. if (prefix === null)
  4054. read = '.';
  4055. else if (isAbsolute(prefix) ||
  4056. isAbsolute(pattern.map(function (p) {
  4057. return typeof p === 'string' ? p : '[*]'
  4058. }).join('/'))) {
  4059. if (!prefix || !isAbsolute(prefix))
  4060. prefix = '/' + prefix;
  4061. read = prefix;
  4062. } else
  4063. read = prefix;
  4064. var abs = this._makeAbs(read);
  4065. //if ignored, skip processing
  4066. if (childrenIgnored(this, read))
  4067. return
  4068. var isGlobStar = remain[0] === minimatch.GLOBSTAR;
  4069. if (isGlobStar)
  4070. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  4071. else
  4072. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  4073. };
  4074. GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  4075. var entries = this._readdir(abs, inGlobStar);
  4076. // if the abs isn't a dir, then nothing can match!
  4077. if (!entries)
  4078. return
  4079. // It will only match dot entries if it starts with a dot, or if
  4080. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  4081. var pn = remain[0];
  4082. var negate = !!this.minimatch.negate;
  4083. var rawGlob = pn._glob;
  4084. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  4085. var matchedEntries = [];
  4086. for (var i = 0; i < entries.length; i++) {
  4087. var e = entries[i];
  4088. if (e.charAt(0) !== '.' || dotOk) {
  4089. var m;
  4090. if (negate && !prefix) {
  4091. m = !e.match(pn);
  4092. } else {
  4093. m = e.match(pn);
  4094. }
  4095. if (m)
  4096. matchedEntries.push(e);
  4097. }
  4098. }
  4099. var len = matchedEntries.length;
  4100. // If there are no matched entries, then nothing matches.
  4101. if (len === 0)
  4102. return
  4103. // if this is the last remaining pattern bit, then no need for
  4104. // an additional stat *unless* the user has specified mark or
  4105. // stat explicitly. We know they exist, since readdir returned
  4106. // them.
  4107. if (remain.length === 1 && !this.mark && !this.stat) {
  4108. if (!this.matches[index])
  4109. this.matches[index] = Object.create(null);
  4110. for (var i = 0; i < len; i ++) {
  4111. var e = matchedEntries[i];
  4112. if (prefix) {
  4113. if (prefix.slice(-1) !== '/')
  4114. e = prefix + '/' + e;
  4115. else
  4116. e = prefix + e;
  4117. }
  4118. if (e.charAt(0) === '/' && !this.nomount) {
  4119. e = path.join(this.root, e);
  4120. }
  4121. this._emitMatch(index, e);
  4122. }
  4123. // This was the last one, and no stats were needed
  4124. return
  4125. }
  4126. // now test all matched entries as stand-ins for that part
  4127. // of the pattern.
  4128. remain.shift();
  4129. for (var i = 0; i < len; i ++) {
  4130. var e = matchedEntries[i];
  4131. var newPattern;
  4132. if (prefix)
  4133. newPattern = [prefix, e];
  4134. else
  4135. newPattern = [e];
  4136. this._process(newPattern.concat(remain), index, inGlobStar);
  4137. }
  4138. };
  4139. GlobSync.prototype._emitMatch = function (index, e) {
  4140. if (isIgnored(this, e))
  4141. return
  4142. var abs = this._makeAbs(e);
  4143. if (this.mark)
  4144. e = this._mark(e);
  4145. if (this.absolute) {
  4146. e = abs;
  4147. }
  4148. if (this.matches[index][e])
  4149. return
  4150. if (this.nodir) {
  4151. var c = this.cache[abs];
  4152. if (c === 'DIR' || Array.isArray(c))
  4153. return
  4154. }
  4155. this.matches[index][e] = true;
  4156. if (this.stat)
  4157. this._stat(e);
  4158. };
  4159. GlobSync.prototype._readdirInGlobStar = function (abs) {
  4160. // follow all symlinked directories forever
  4161. // just proceed as if this is a non-globstar situation
  4162. if (this.follow)
  4163. return this._readdir(abs, false)
  4164. var entries;
  4165. var lstat;
  4166. try {
  4167. lstat = this.fs.lstatSync(abs);
  4168. } catch (er) {
  4169. if (er.code === 'ENOENT') {
  4170. // lstat failed, doesn't exist
  4171. return null
  4172. }
  4173. }
  4174. var isSym = lstat && lstat.isSymbolicLink();
  4175. this.symlinks[abs] = isSym;
  4176. // If it's not a symlink or a dir, then it's definitely a regular file.
  4177. // don't bother doing a readdir in that case.
  4178. if (!isSym && lstat && !lstat.isDirectory())
  4179. this.cache[abs] = 'FILE';
  4180. else
  4181. entries = this._readdir(abs, false);
  4182. return entries
  4183. };
  4184. GlobSync.prototype._readdir = function (abs, inGlobStar) {
  4185. if (inGlobStar && !ownProp(this.symlinks, abs))
  4186. return this._readdirInGlobStar(abs)
  4187. if (ownProp(this.cache, abs)) {
  4188. var c = this.cache[abs];
  4189. if (!c || c === 'FILE')
  4190. return null
  4191. if (Array.isArray(c))
  4192. return c
  4193. }
  4194. try {
  4195. return this._readdirEntries(abs, this.fs.readdirSync(abs))
  4196. } catch (er) {
  4197. this._readdirError(abs, er);
  4198. return null
  4199. }
  4200. };
  4201. GlobSync.prototype._readdirEntries = function (abs, entries) {
  4202. // if we haven't asked to stat everything, then just
  4203. // assume that everything in there exists, so we can avoid
  4204. // having to stat it a second time.
  4205. if (!this.mark && !this.stat) {
  4206. for (var i = 0; i < entries.length; i ++) {
  4207. var e = entries[i];
  4208. if (abs === '/')
  4209. e = abs + e;
  4210. else
  4211. e = abs + '/' + e;
  4212. this.cache[e] = true;
  4213. }
  4214. }
  4215. this.cache[abs] = entries;
  4216. // mark and cache dir-ness
  4217. return entries
  4218. };
  4219. GlobSync.prototype._readdirError = function (f, er) {
  4220. // handle errors, and cache the information
  4221. switch (er.code) {
  4222. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  4223. case 'ENOTDIR': // totally normal. means it *does* exist.
  4224. var abs = this._makeAbs(f);
  4225. this.cache[abs] = 'FILE';
  4226. if (abs === this.cwdAbs) {
  4227. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  4228. error.path = this.cwd;
  4229. error.code = er.code;
  4230. throw error
  4231. }
  4232. break
  4233. case 'ENOENT': // not terribly unusual
  4234. case 'ELOOP':
  4235. case 'ENAMETOOLONG':
  4236. case 'UNKNOWN':
  4237. this.cache[this._makeAbs(f)] = false;
  4238. break
  4239. default: // some unusual error. Treat as failure.
  4240. this.cache[this._makeAbs(f)] = false;
  4241. if (this.strict)
  4242. throw er
  4243. if (!this.silent)
  4244. console.error('glob error', er);
  4245. break
  4246. }
  4247. };
  4248. GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  4249. var entries = this._readdir(abs, inGlobStar);
  4250. // no entries means not a dir, so it can never have matches
  4251. // foo.txt/** doesn't match foo.txt
  4252. if (!entries)
  4253. return
  4254. // test without the globstar, and with every child both below
  4255. // and replacing the globstar.
  4256. var remainWithoutGlobStar = remain.slice(1);
  4257. var gspref = prefix ? [ prefix ] : [];
  4258. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  4259. // the noGlobStar pattern exits the inGlobStar state
  4260. this._process(noGlobStar, index, false);
  4261. var len = entries.length;
  4262. var isSym = this.symlinks[abs];
  4263. // If it's a symlink, and we're in a globstar, then stop
  4264. if (isSym && inGlobStar)
  4265. return
  4266. for (var i = 0; i < len; i++) {
  4267. var e = entries[i];
  4268. if (e.charAt(0) === '.' && !this.dot)
  4269. continue
  4270. // these two cases enter the inGlobStar state
  4271. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  4272. this._process(instead, index, true);
  4273. var below = gspref.concat(entries[i], remain);
  4274. this._process(below, index, true);
  4275. }
  4276. };
  4277. GlobSync.prototype._processSimple = function (prefix, index) {
  4278. // XXX review this. Shouldn't it be doing the mounting etc
  4279. // before doing stat? kinda weird?
  4280. var exists = this._stat(prefix);
  4281. if (!this.matches[index])
  4282. this.matches[index] = Object.create(null);
  4283. // If it doesn't exist, then just mark the lack of results
  4284. if (!exists)
  4285. return
  4286. if (prefix && isAbsolute(prefix) && !this.nomount) {
  4287. var trail = /[\/\\]$/.test(prefix);
  4288. if (prefix.charAt(0) === '/') {
  4289. prefix = path.join(this.root, prefix);
  4290. } else {
  4291. prefix = path.resolve(this.root, prefix);
  4292. if (trail)
  4293. prefix += '/';
  4294. }
  4295. }
  4296. if (process.platform === 'win32')
  4297. prefix = prefix.replace(/\\/g, '/');
  4298. // Mark this as a match
  4299. this._emitMatch(index, prefix);
  4300. };
  4301. // Returns either 'DIR', 'FILE', or false
  4302. GlobSync.prototype._stat = function (f) {
  4303. var abs = this._makeAbs(f);
  4304. var needDir = f.slice(-1) === '/';
  4305. if (f.length > this.maxLength)
  4306. return false
  4307. if (!this.stat && ownProp(this.cache, abs)) {
  4308. var c = this.cache[abs];
  4309. if (Array.isArray(c))
  4310. c = 'DIR';
  4311. // It exists, but maybe not how we need it
  4312. if (!needDir || c === 'DIR')
  4313. return c
  4314. if (needDir && c === 'FILE')
  4315. return false
  4316. // otherwise we have to stat, because maybe c=true
  4317. // if we know it exists, but not what it is.
  4318. }
  4319. var stat = this.statCache[abs];
  4320. if (!stat) {
  4321. var lstat;
  4322. try {
  4323. lstat = this.fs.lstatSync(abs);
  4324. } catch (er) {
  4325. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  4326. this.statCache[abs] = false;
  4327. return false
  4328. }
  4329. }
  4330. if (lstat && lstat.isSymbolicLink()) {
  4331. try {
  4332. stat = this.fs.statSync(abs);
  4333. } catch (er) {
  4334. stat = lstat;
  4335. }
  4336. } else {
  4337. stat = lstat;
  4338. }
  4339. }
  4340. this.statCache[abs] = stat;
  4341. var c = true;
  4342. if (stat)
  4343. c = stat.isDirectory() ? 'DIR' : 'FILE';
  4344. this.cache[abs] = this.cache[abs] || c;
  4345. if (needDir && c === 'FILE')
  4346. return false
  4347. return c
  4348. };
  4349. GlobSync.prototype._mark = function (p) {
  4350. return common.mark(this, p)
  4351. };
  4352. GlobSync.prototype._makeAbs = function (f) {
  4353. return common.makeAbs(this, f)
  4354. };
  4355. return sync$9;
  4356. }
  4357. // Returns a wrapper function that returns a wrapped callback
  4358. // The wrapper function should do some stuff, and return a
  4359. // presumably different callback function.
  4360. // This makes sure that own properties are retained, so that
  4361. // decorations and such are not lost along the way.
  4362. var wrappy_1 = wrappy$2;
  4363. function wrappy$2 (fn, cb) {
  4364. if (fn && cb) return wrappy$2(fn)(cb)
  4365. if (typeof fn !== 'function')
  4366. throw new TypeError('need wrapper function')
  4367. Object.keys(fn).forEach(function (k) {
  4368. wrapper[k] = fn[k];
  4369. });
  4370. return wrapper
  4371. function wrapper() {
  4372. var args = new Array(arguments.length);
  4373. for (var i = 0; i < args.length; i++) {
  4374. args[i] = arguments[i];
  4375. }
  4376. var ret = fn.apply(this, args);
  4377. var cb = args[args.length-1];
  4378. if (typeof ret === 'function' && ret !== cb) {
  4379. Object.keys(cb).forEach(function (k) {
  4380. ret[k] = cb[k];
  4381. });
  4382. }
  4383. return ret
  4384. }
  4385. }
  4386. var once$2 = {exports: {}};
  4387. var wrappy$1 = wrappy_1;
  4388. once$2.exports = wrappy$1(once$1);
  4389. once$2.exports.strict = wrappy$1(onceStrict);
  4390. once$1.proto = once$1(function () {
  4391. Object.defineProperty(Function.prototype, 'once', {
  4392. value: function () {
  4393. return once$1(this)
  4394. },
  4395. configurable: true
  4396. });
  4397. Object.defineProperty(Function.prototype, 'onceStrict', {
  4398. value: function () {
  4399. return onceStrict(this)
  4400. },
  4401. configurable: true
  4402. });
  4403. });
  4404. function once$1 (fn) {
  4405. var f = function () {
  4406. if (f.called) return f.value
  4407. f.called = true;
  4408. return f.value = fn.apply(this, arguments)
  4409. };
  4410. f.called = false;
  4411. return f
  4412. }
  4413. function onceStrict (fn) {
  4414. var f = function () {
  4415. if (f.called)
  4416. throw new Error(f.onceError)
  4417. f.called = true;
  4418. return f.value = fn.apply(this, arguments)
  4419. };
  4420. var name = fn.name || 'Function wrapped with `once`';
  4421. f.onceError = name + " shouldn't be called more than once";
  4422. f.called = false;
  4423. return f
  4424. }
  4425. var onceExports = once$2.exports;
  4426. var wrappy = wrappy_1;
  4427. var reqs = Object.create(null);
  4428. var once = onceExports;
  4429. var inflight_1 = wrappy(inflight);
  4430. function inflight (key, cb) {
  4431. if (reqs[key]) {
  4432. reqs[key].push(cb);
  4433. return null
  4434. } else {
  4435. reqs[key] = [cb];
  4436. return makeres(key)
  4437. }
  4438. }
  4439. function makeres (key) {
  4440. return once(function RES () {
  4441. var cbs = reqs[key];
  4442. var len = cbs.length;
  4443. var args = slice$1(arguments);
  4444. // XXX It's somewhat ambiguous whether a new callback added in this
  4445. // pass should be queued for later execution if something in the
  4446. // list of callbacks throws, or if it should just be discarded.
  4447. // However, it's such an edge case that it hardly matters, and either
  4448. // choice is likely as surprising as the other.
  4449. // As it happens, we do go ahead and schedule it for later execution.
  4450. try {
  4451. for (var i = 0; i < len; i++) {
  4452. cbs[i].apply(null, args);
  4453. }
  4454. } finally {
  4455. if (cbs.length > len) {
  4456. // added more in the interim.
  4457. // de-zalgo, just in case, but don't call again.
  4458. cbs.splice(0, len);
  4459. process.nextTick(function () {
  4460. RES.apply(null, args);
  4461. });
  4462. } else {
  4463. delete reqs[key];
  4464. }
  4465. }
  4466. })
  4467. }
  4468. function slice$1 (args) {
  4469. var length = args.length;
  4470. var array = [];
  4471. for (var i = 0; i < length; i++) array[i] = args[i];
  4472. return array
  4473. }
  4474. var glob_1;
  4475. var hasRequiredGlob;
  4476. function requireGlob () {
  4477. if (hasRequiredGlob) return glob_1;
  4478. hasRequiredGlob = 1;
  4479. // Approach:
  4480. //
  4481. // 1. Get the minimatch set
  4482. // 2. For each pattern in the set, PROCESS(pattern, false)
  4483. // 3. Store matches per-set, then uniq them
  4484. //
  4485. // PROCESS(pattern, inGlobStar)
  4486. // Get the first [n] items from pattern that are all strings
  4487. // Join these together. This is PREFIX.
  4488. // If there is no more remaining, then stat(PREFIX) and
  4489. // add to matches if it succeeds. END.
  4490. //
  4491. // If inGlobStar and PREFIX is symlink and points to dir
  4492. // set ENTRIES = []
  4493. // else readdir(PREFIX) as ENTRIES
  4494. // If fail, END
  4495. //
  4496. // with ENTRIES
  4497. // If pattern[n] is GLOBSTAR
  4498. // // handle the case where the globstar match is empty
  4499. // // by pruning it out, and testing the resulting pattern
  4500. // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
  4501. // // handle other cases.
  4502. // for ENTRY in ENTRIES (not dotfiles)
  4503. // // attach globstar + tail onto the entry
  4504. // // Mark that this entry is a globstar match
  4505. // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
  4506. //
  4507. // else // not globstar
  4508. // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
  4509. // Test ENTRY against pattern[n]
  4510. // If fails, continue
  4511. // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
  4512. //
  4513. // Caveat:
  4514. // Cache all stats and readdirs results to minimize syscall. Since all
  4515. // we ever care about is existence and directory-ness, we can just keep
  4516. // `true` for files, and [children,...] for directories, or `false` for
  4517. // things that don't exist.
  4518. glob_1 = glob;
  4519. var rp = fs_realpath;
  4520. var minimatch = minimatch_1;
  4521. var inherits = inheritsExports;
  4522. var EE = require$$0$5.EventEmitter;
  4523. var path = require$$0$4;
  4524. var assert = require$$5;
  4525. var isAbsolute = require$$0$4.isAbsolute;
  4526. var globSync = requireSync();
  4527. var common = common$c;
  4528. var setopts = common.setopts;
  4529. var ownProp = common.ownProp;
  4530. var inflight = inflight_1;
  4531. var childrenIgnored = common.childrenIgnored;
  4532. var isIgnored = common.isIgnored;
  4533. var once = onceExports;
  4534. function glob (pattern, options, cb) {
  4535. if (typeof options === 'function') cb = options, options = {};
  4536. if (!options) options = {};
  4537. if (options.sync) {
  4538. if (cb)
  4539. throw new TypeError('callback provided to sync glob')
  4540. return globSync(pattern, options)
  4541. }
  4542. return new Glob(pattern, options, cb)
  4543. }
  4544. glob.sync = globSync;
  4545. var GlobSync = glob.GlobSync = globSync.GlobSync;
  4546. // old api surface
  4547. glob.glob = glob;
  4548. function extend (origin, add) {
  4549. if (add === null || typeof add !== 'object') {
  4550. return origin
  4551. }
  4552. var keys = Object.keys(add);
  4553. var i = keys.length;
  4554. while (i--) {
  4555. origin[keys[i]] = add[keys[i]];
  4556. }
  4557. return origin
  4558. }
  4559. glob.hasMagic = function (pattern, options_) {
  4560. var options = extend({}, options_);
  4561. options.noprocess = true;
  4562. var g = new Glob(pattern, options);
  4563. var set = g.minimatch.set;
  4564. if (!pattern)
  4565. return false
  4566. if (set.length > 1)
  4567. return true
  4568. for (var j = 0; j < set[0].length; j++) {
  4569. if (typeof set[0][j] !== 'string')
  4570. return true
  4571. }
  4572. return false
  4573. };
  4574. glob.Glob = Glob;
  4575. inherits(Glob, EE);
  4576. function Glob (pattern, options, cb) {
  4577. if (typeof options === 'function') {
  4578. cb = options;
  4579. options = null;
  4580. }
  4581. if (options && options.sync) {
  4582. if (cb)
  4583. throw new TypeError('callback provided to sync glob')
  4584. return new GlobSync(pattern, options)
  4585. }
  4586. if (!(this instanceof Glob))
  4587. return new Glob(pattern, options, cb)
  4588. setopts(this, pattern, options);
  4589. this._didRealPath = false;
  4590. // process each pattern in the minimatch set
  4591. var n = this.minimatch.set.length;
  4592. // The matches are stored as {<filename>: true,...} so that
  4593. // duplicates are automagically pruned.
  4594. // Later, we do an Object.keys() on these.
  4595. // Keep them as a list so we can fill in when nonull is set.
  4596. this.matches = new Array(n);
  4597. if (typeof cb === 'function') {
  4598. cb = once(cb);
  4599. this.on('error', cb);
  4600. this.on('end', function (matches) {
  4601. cb(null, matches);
  4602. });
  4603. }
  4604. var self = this;
  4605. this._processing = 0;
  4606. this._emitQueue = [];
  4607. this._processQueue = [];
  4608. this.paused = false;
  4609. if (this.noprocess)
  4610. return this
  4611. if (n === 0)
  4612. return done()
  4613. var sync = true;
  4614. for (var i = 0; i < n; i ++) {
  4615. this._process(this.minimatch.set[i], i, false, done);
  4616. }
  4617. sync = false;
  4618. function done () {
  4619. --self._processing;
  4620. if (self._processing <= 0) {
  4621. if (sync) {
  4622. process.nextTick(function () {
  4623. self._finish();
  4624. });
  4625. } else {
  4626. self._finish();
  4627. }
  4628. }
  4629. }
  4630. }
  4631. Glob.prototype._finish = function () {
  4632. assert(this instanceof Glob);
  4633. if (this.aborted)
  4634. return
  4635. if (this.realpath && !this._didRealpath)
  4636. return this._realpath()
  4637. common.finish(this);
  4638. this.emit('end', this.found);
  4639. };
  4640. Glob.prototype._realpath = function () {
  4641. if (this._didRealpath)
  4642. return
  4643. this._didRealpath = true;
  4644. var n = this.matches.length;
  4645. if (n === 0)
  4646. return this._finish()
  4647. var self = this;
  4648. for (var i = 0; i < this.matches.length; i++)
  4649. this._realpathSet(i, next);
  4650. function next () {
  4651. if (--n === 0)
  4652. self._finish();
  4653. }
  4654. };
  4655. Glob.prototype._realpathSet = function (index, cb) {
  4656. var matchset = this.matches[index];
  4657. if (!matchset)
  4658. return cb()
  4659. var found = Object.keys(matchset);
  4660. var self = this;
  4661. var n = found.length;
  4662. if (n === 0)
  4663. return cb()
  4664. var set = this.matches[index] = Object.create(null);
  4665. found.forEach(function (p, i) {
  4666. // If there's a problem with the stat, then it means that
  4667. // one or more of the links in the realpath couldn't be
  4668. // resolved. just return the abs value in that case.
  4669. p = self._makeAbs(p);
  4670. rp.realpath(p, self.realpathCache, function (er, real) {
  4671. if (!er)
  4672. set[real] = true;
  4673. else if (er.syscall === 'stat')
  4674. set[p] = true;
  4675. else
  4676. self.emit('error', er); // srsly wtf right here
  4677. if (--n === 0) {
  4678. self.matches[index] = set;
  4679. cb();
  4680. }
  4681. });
  4682. });
  4683. };
  4684. Glob.prototype._mark = function (p) {
  4685. return common.mark(this, p)
  4686. };
  4687. Glob.prototype._makeAbs = function (f) {
  4688. return common.makeAbs(this, f)
  4689. };
  4690. Glob.prototype.abort = function () {
  4691. this.aborted = true;
  4692. this.emit('abort');
  4693. };
  4694. Glob.prototype.pause = function () {
  4695. if (!this.paused) {
  4696. this.paused = true;
  4697. this.emit('pause');
  4698. }
  4699. };
  4700. Glob.prototype.resume = function () {
  4701. if (this.paused) {
  4702. this.emit('resume');
  4703. this.paused = false;
  4704. if (this._emitQueue.length) {
  4705. var eq = this._emitQueue.slice(0);
  4706. this._emitQueue.length = 0;
  4707. for (var i = 0; i < eq.length; i ++) {
  4708. var e = eq[i];
  4709. this._emitMatch(e[0], e[1]);
  4710. }
  4711. }
  4712. if (this._processQueue.length) {
  4713. var pq = this._processQueue.slice(0);
  4714. this._processQueue.length = 0;
  4715. for (var i = 0; i < pq.length; i ++) {
  4716. var p = pq[i];
  4717. this._processing--;
  4718. this._process(p[0], p[1], p[2], p[3]);
  4719. }
  4720. }
  4721. }
  4722. };
  4723. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  4724. assert(this instanceof Glob);
  4725. assert(typeof cb === 'function');
  4726. if (this.aborted)
  4727. return
  4728. this._processing++;
  4729. if (this.paused) {
  4730. this._processQueue.push([pattern, index, inGlobStar, cb]);
  4731. return
  4732. }
  4733. //console.error('PROCESS %d', this._processing, pattern)
  4734. // Get the first [n] parts of pattern that are all strings.
  4735. var n = 0;
  4736. while (typeof pattern[n] === 'string') {
  4737. n ++;
  4738. }
  4739. // now n is the index of the first one that is *not* a string.
  4740. // see if there's anything else
  4741. var prefix;
  4742. switch (n) {
  4743. // if not, then this is rather simple
  4744. case pattern.length:
  4745. this._processSimple(pattern.join('/'), index, cb);
  4746. return
  4747. case 0:
  4748. // pattern *starts* with some non-trivial item.
  4749. // going to readdir(cwd), but not include the prefix in matches.
  4750. prefix = null;
  4751. break
  4752. default:
  4753. // pattern has some string bits in the front.
  4754. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  4755. // or 'relative' like '../baz'
  4756. prefix = pattern.slice(0, n).join('/');
  4757. break
  4758. }
  4759. var remain = pattern.slice(n);
  4760. // get the list of entries.
  4761. var read;
  4762. if (prefix === null)
  4763. read = '.';
  4764. else if (isAbsolute(prefix) ||
  4765. isAbsolute(pattern.map(function (p) {
  4766. return typeof p === 'string' ? p : '[*]'
  4767. }).join('/'))) {
  4768. if (!prefix || !isAbsolute(prefix))
  4769. prefix = '/' + prefix;
  4770. read = prefix;
  4771. } else
  4772. read = prefix;
  4773. var abs = this._makeAbs(read);
  4774. //if ignored, skip _processing
  4775. if (childrenIgnored(this, read))
  4776. return cb()
  4777. var isGlobStar = remain[0] === minimatch.GLOBSTAR;
  4778. if (isGlobStar)
  4779. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  4780. else
  4781. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  4782. };
  4783. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  4784. var self = this;
  4785. this._readdir(abs, inGlobStar, function (er, entries) {
  4786. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  4787. });
  4788. };
  4789. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  4790. // if the abs isn't a dir, then nothing can match!
  4791. if (!entries)
  4792. return cb()
  4793. // It will only match dot entries if it starts with a dot, or if
  4794. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  4795. var pn = remain[0];
  4796. var negate = !!this.minimatch.negate;
  4797. var rawGlob = pn._glob;
  4798. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  4799. var matchedEntries = [];
  4800. for (var i = 0; i < entries.length; i++) {
  4801. var e = entries[i];
  4802. if (e.charAt(0) !== '.' || dotOk) {
  4803. var m;
  4804. if (negate && !prefix) {
  4805. m = !e.match(pn);
  4806. } else {
  4807. m = e.match(pn);
  4808. }
  4809. if (m)
  4810. matchedEntries.push(e);
  4811. }
  4812. }
  4813. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  4814. var len = matchedEntries.length;
  4815. // If there are no matched entries, then nothing matches.
  4816. if (len === 0)
  4817. return cb()
  4818. // if this is the last remaining pattern bit, then no need for
  4819. // an additional stat *unless* the user has specified mark or
  4820. // stat explicitly. We know they exist, since readdir returned
  4821. // them.
  4822. if (remain.length === 1 && !this.mark && !this.stat) {
  4823. if (!this.matches[index])
  4824. this.matches[index] = Object.create(null);
  4825. for (var i = 0; i < len; i ++) {
  4826. var e = matchedEntries[i];
  4827. if (prefix) {
  4828. if (prefix !== '/')
  4829. e = prefix + '/' + e;
  4830. else
  4831. e = prefix + e;
  4832. }
  4833. if (e.charAt(0) === '/' && !this.nomount) {
  4834. e = path.join(this.root, e);
  4835. }
  4836. this._emitMatch(index, e);
  4837. }
  4838. // This was the last one, and no stats were needed
  4839. return cb()
  4840. }
  4841. // now test all matched entries as stand-ins for that part
  4842. // of the pattern.
  4843. remain.shift();
  4844. for (var i = 0; i < len; i ++) {
  4845. var e = matchedEntries[i];
  4846. if (prefix) {
  4847. if (prefix !== '/')
  4848. e = prefix + '/' + e;
  4849. else
  4850. e = prefix + e;
  4851. }
  4852. this._process([e].concat(remain), index, inGlobStar, cb);
  4853. }
  4854. cb();
  4855. };
  4856. Glob.prototype._emitMatch = function (index, e) {
  4857. if (this.aborted)
  4858. return
  4859. if (isIgnored(this, e))
  4860. return
  4861. if (this.paused) {
  4862. this._emitQueue.push([index, e]);
  4863. return
  4864. }
  4865. var abs = isAbsolute(e) ? e : this._makeAbs(e);
  4866. if (this.mark)
  4867. e = this._mark(e);
  4868. if (this.absolute)
  4869. e = abs;
  4870. if (this.matches[index][e])
  4871. return
  4872. if (this.nodir) {
  4873. var c = this.cache[abs];
  4874. if (c === 'DIR' || Array.isArray(c))
  4875. return
  4876. }
  4877. this.matches[index][e] = true;
  4878. var st = this.statCache[abs];
  4879. if (st)
  4880. this.emit('stat', e, st);
  4881. this.emit('match', e);
  4882. };
  4883. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  4884. if (this.aborted)
  4885. return
  4886. // follow all symlinked directories forever
  4887. // just proceed as if this is a non-globstar situation
  4888. if (this.follow)
  4889. return this._readdir(abs, false, cb)
  4890. var lstatkey = 'lstat\0' + abs;
  4891. var self = this;
  4892. var lstatcb = inflight(lstatkey, lstatcb_);
  4893. if (lstatcb)
  4894. self.fs.lstat(abs, lstatcb);
  4895. function lstatcb_ (er, lstat) {
  4896. if (er && er.code === 'ENOENT')
  4897. return cb()
  4898. var isSym = lstat && lstat.isSymbolicLink();
  4899. self.symlinks[abs] = isSym;
  4900. // If it's not a symlink or a dir, then it's definitely a regular file.
  4901. // don't bother doing a readdir in that case.
  4902. if (!isSym && lstat && !lstat.isDirectory()) {
  4903. self.cache[abs] = 'FILE';
  4904. cb();
  4905. } else
  4906. self._readdir(abs, false, cb);
  4907. }
  4908. };
  4909. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  4910. if (this.aborted)
  4911. return
  4912. cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb);
  4913. if (!cb)
  4914. return
  4915. //console.error('RD %j %j', +inGlobStar, abs)
  4916. if (inGlobStar && !ownProp(this.symlinks, abs))
  4917. return this._readdirInGlobStar(abs, cb)
  4918. if (ownProp(this.cache, abs)) {
  4919. var c = this.cache[abs];
  4920. if (!c || c === 'FILE')
  4921. return cb()
  4922. if (Array.isArray(c))
  4923. return cb(null, c)
  4924. }
  4925. var self = this;
  4926. self.fs.readdir(abs, readdirCb(this, abs, cb));
  4927. };
  4928. function readdirCb (self, abs, cb) {
  4929. return function (er, entries) {
  4930. if (er)
  4931. self._readdirError(abs, er, cb);
  4932. else
  4933. self._readdirEntries(abs, entries, cb);
  4934. }
  4935. }
  4936. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  4937. if (this.aborted)
  4938. return
  4939. // if we haven't asked to stat everything, then just
  4940. // assume that everything in there exists, so we can avoid
  4941. // having to stat it a second time.
  4942. if (!this.mark && !this.stat) {
  4943. for (var i = 0; i < entries.length; i ++) {
  4944. var e = entries[i];
  4945. if (abs === '/')
  4946. e = abs + e;
  4947. else
  4948. e = abs + '/' + e;
  4949. this.cache[e] = true;
  4950. }
  4951. }
  4952. this.cache[abs] = entries;
  4953. return cb(null, entries)
  4954. };
  4955. Glob.prototype._readdirError = function (f, er, cb) {
  4956. if (this.aborted)
  4957. return
  4958. // handle errors, and cache the information
  4959. switch (er.code) {
  4960. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  4961. case 'ENOTDIR': // totally normal. means it *does* exist.
  4962. var abs = this._makeAbs(f);
  4963. this.cache[abs] = 'FILE';
  4964. if (abs === this.cwdAbs) {
  4965. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  4966. error.path = this.cwd;
  4967. error.code = er.code;
  4968. this.emit('error', error);
  4969. this.abort();
  4970. }
  4971. break
  4972. case 'ENOENT': // not terribly unusual
  4973. case 'ELOOP':
  4974. case 'ENAMETOOLONG':
  4975. case 'UNKNOWN':
  4976. this.cache[this._makeAbs(f)] = false;
  4977. break
  4978. default: // some unusual error. Treat as failure.
  4979. this.cache[this._makeAbs(f)] = false;
  4980. if (this.strict) {
  4981. this.emit('error', er);
  4982. // If the error is handled, then we abort
  4983. // if not, we threw out of here
  4984. this.abort();
  4985. }
  4986. if (!this.silent)
  4987. console.error('glob error', er);
  4988. break
  4989. }
  4990. return cb()
  4991. };
  4992. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  4993. var self = this;
  4994. this._readdir(abs, inGlobStar, function (er, entries) {
  4995. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  4996. });
  4997. };
  4998. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  4999. //console.error('pgs2', prefix, remain[0], entries)
  5000. // no entries means not a dir, so it can never have matches
  5001. // foo.txt/** doesn't match foo.txt
  5002. if (!entries)
  5003. return cb()
  5004. // test without the globstar, and with every child both below
  5005. // and replacing the globstar.
  5006. var remainWithoutGlobStar = remain.slice(1);
  5007. var gspref = prefix ? [ prefix ] : [];
  5008. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  5009. // the noGlobStar pattern exits the inGlobStar state
  5010. this._process(noGlobStar, index, false, cb);
  5011. var isSym = this.symlinks[abs];
  5012. var len = entries.length;
  5013. // If it's a symlink, and we're in a globstar, then stop
  5014. if (isSym && inGlobStar)
  5015. return cb()
  5016. for (var i = 0; i < len; i++) {
  5017. var e = entries[i];
  5018. if (e.charAt(0) === '.' && !this.dot)
  5019. continue
  5020. // these two cases enter the inGlobStar state
  5021. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  5022. this._process(instead, index, true, cb);
  5023. var below = gspref.concat(entries[i], remain);
  5024. this._process(below, index, true, cb);
  5025. }
  5026. cb();
  5027. };
  5028. Glob.prototype._processSimple = function (prefix, index, cb) {
  5029. // XXX review this. Shouldn't it be doing the mounting etc
  5030. // before doing stat? kinda weird?
  5031. var self = this;
  5032. this._stat(prefix, function (er, exists) {
  5033. self._processSimple2(prefix, index, er, exists, cb);
  5034. });
  5035. };
  5036. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  5037. //console.error('ps2', prefix, exists)
  5038. if (!this.matches[index])
  5039. this.matches[index] = Object.create(null);
  5040. // If it doesn't exist, then just mark the lack of results
  5041. if (!exists)
  5042. return cb()
  5043. if (prefix && isAbsolute(prefix) && !this.nomount) {
  5044. var trail = /[\/\\]$/.test(prefix);
  5045. if (prefix.charAt(0) === '/') {
  5046. prefix = path.join(this.root, prefix);
  5047. } else {
  5048. prefix = path.resolve(this.root, prefix);
  5049. if (trail)
  5050. prefix += '/';
  5051. }
  5052. }
  5053. if (process.platform === 'win32')
  5054. prefix = prefix.replace(/\\/g, '/');
  5055. // Mark this as a match
  5056. this._emitMatch(index, prefix);
  5057. cb();
  5058. };
  5059. // Returns either 'DIR', 'FILE', or false
  5060. Glob.prototype._stat = function (f, cb) {
  5061. var abs = this._makeAbs(f);
  5062. var needDir = f.slice(-1) === '/';
  5063. if (f.length > this.maxLength)
  5064. return cb()
  5065. if (!this.stat && ownProp(this.cache, abs)) {
  5066. var c = this.cache[abs];
  5067. if (Array.isArray(c))
  5068. c = 'DIR';
  5069. // It exists, but maybe not how we need it
  5070. if (!needDir || c === 'DIR')
  5071. return cb(null, c)
  5072. if (needDir && c === 'FILE')
  5073. return cb()
  5074. // otherwise we have to stat, because maybe c=true
  5075. // if we know it exists, but not what it is.
  5076. }
  5077. var stat = this.statCache[abs];
  5078. if (stat !== undefined) {
  5079. if (stat === false)
  5080. return cb(null, stat)
  5081. else {
  5082. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  5083. if (needDir && type === 'FILE')
  5084. return cb()
  5085. else
  5086. return cb(null, type, stat)
  5087. }
  5088. }
  5089. var self = this;
  5090. var statcb = inflight('stat\0' + abs, lstatcb_);
  5091. if (statcb)
  5092. self.fs.lstat(abs, statcb);
  5093. function lstatcb_ (er, lstat) {
  5094. if (lstat && lstat.isSymbolicLink()) {
  5095. // If it's a symlink, then treat it as the target, unless
  5096. // the target does not exist, then treat it as a file.
  5097. return self.fs.stat(abs, function (er, stat) {
  5098. if (er)
  5099. self._stat2(f, abs, null, lstat, cb);
  5100. else
  5101. self._stat2(f, abs, er, stat, cb);
  5102. })
  5103. } else {
  5104. self._stat2(f, abs, er, lstat, cb);
  5105. }
  5106. }
  5107. };
  5108. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  5109. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  5110. this.statCache[abs] = false;
  5111. return cb()
  5112. }
  5113. var needDir = f.slice(-1) === '/';
  5114. this.statCache[abs] = stat;
  5115. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  5116. return cb(null, false, stat)
  5117. var c = true;
  5118. if (stat)
  5119. c = stat.isDirectory() ? 'DIR' : 'FILE';
  5120. this.cache[abs] = this.cache[abs] || c;
  5121. if (needDir && c === 'FILE')
  5122. return cb()
  5123. return cb(null, c, stat)
  5124. };
  5125. return glob_1;
  5126. }
  5127. var globExports = requireGlob();
  5128. var glob$1 = /*@__PURE__*/getDefaultExportFromCjs(globExports);
  5129. const comma = ','.charCodeAt(0);
  5130. const semicolon = ';'.charCodeAt(0);
  5131. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  5132. const intToChar = new Uint8Array(64); // 64 possible chars.
  5133. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  5134. for (let i = 0; i < chars$1.length; i++) {
  5135. const c = chars$1.charCodeAt(i);
  5136. intToChar[i] = c;
  5137. charToInt[c] = i;
  5138. }
  5139. // Provide a fallback for older environments.
  5140. const td = typeof TextDecoder !== 'undefined'
  5141. ? /* #__PURE__ */ new TextDecoder()
  5142. : typeof Buffer !== 'undefined'
  5143. ? {
  5144. decode(buf) {
  5145. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  5146. return out.toString();
  5147. },
  5148. }
  5149. : {
  5150. decode(buf) {
  5151. let out = '';
  5152. for (let i = 0; i < buf.length; i++) {
  5153. out += String.fromCharCode(buf[i]);
  5154. }
  5155. return out;
  5156. },
  5157. };
  5158. function decode(mappings) {
  5159. const state = new Int32Array(5);
  5160. const decoded = [];
  5161. let index = 0;
  5162. do {
  5163. const semi = indexOf(mappings, index);
  5164. const line = [];
  5165. let sorted = true;
  5166. let lastCol = 0;
  5167. state[0] = 0;
  5168. for (let i = index; i < semi; i++) {
  5169. let seg;
  5170. i = decodeInteger(mappings, i, state, 0); // genColumn
  5171. const col = state[0];
  5172. if (col < lastCol)
  5173. sorted = false;
  5174. lastCol = col;
  5175. if (hasMoreVlq(mappings, i, semi)) {
  5176. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  5177. i = decodeInteger(mappings, i, state, 2); // sourceLine
  5178. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  5179. if (hasMoreVlq(mappings, i, semi)) {
  5180. i = decodeInteger(mappings, i, state, 4); // namesIndex
  5181. seg = [col, state[1], state[2], state[3], state[4]];
  5182. }
  5183. else {
  5184. seg = [col, state[1], state[2], state[3]];
  5185. }
  5186. }
  5187. else {
  5188. seg = [col];
  5189. }
  5190. line.push(seg);
  5191. }
  5192. if (!sorted)
  5193. sort(line);
  5194. decoded.push(line);
  5195. index = semi + 1;
  5196. } while (index <= mappings.length);
  5197. return decoded;
  5198. }
  5199. function indexOf(mappings, index) {
  5200. const idx = mappings.indexOf(';', index);
  5201. return idx === -1 ? mappings.length : idx;
  5202. }
  5203. function decodeInteger(mappings, pos, state, j) {
  5204. let value = 0;
  5205. let shift = 0;
  5206. let integer = 0;
  5207. do {
  5208. const c = mappings.charCodeAt(pos++);
  5209. integer = charToInt[c];
  5210. value |= (integer & 31) << shift;
  5211. shift += 5;
  5212. } while (integer & 32);
  5213. const shouldNegate = value & 1;
  5214. value >>>= 1;
  5215. if (shouldNegate) {
  5216. value = -0x80000000 | -value;
  5217. }
  5218. state[j] += value;
  5219. return pos;
  5220. }
  5221. function hasMoreVlq(mappings, i, length) {
  5222. if (i >= length)
  5223. return false;
  5224. return mappings.charCodeAt(i) !== comma;
  5225. }
  5226. function sort(line) {
  5227. line.sort(sortComparator$1);
  5228. }
  5229. function sortComparator$1(a, b) {
  5230. return a[0] - b[0];
  5231. }
  5232. function encode$1(decoded) {
  5233. const state = new Int32Array(5);
  5234. const bufLength = 1024 * 16;
  5235. const subLength = bufLength - 36;
  5236. const buf = new Uint8Array(bufLength);
  5237. const sub = buf.subarray(0, subLength);
  5238. let pos = 0;
  5239. let out = '';
  5240. for (let i = 0; i < decoded.length; i++) {
  5241. const line = decoded[i];
  5242. if (i > 0) {
  5243. if (pos === bufLength) {
  5244. out += td.decode(buf);
  5245. pos = 0;
  5246. }
  5247. buf[pos++] = semicolon;
  5248. }
  5249. if (line.length === 0)
  5250. continue;
  5251. state[0] = 0;
  5252. for (let j = 0; j < line.length; j++) {
  5253. const segment = line[j];
  5254. // We can push up to 5 ints, each int can take at most 7 chars, and we
  5255. // may push a comma.
  5256. if (pos > subLength) {
  5257. out += td.decode(sub);
  5258. buf.copyWithin(0, subLength, pos);
  5259. pos -= subLength;
  5260. }
  5261. if (j > 0)
  5262. buf[pos++] = comma;
  5263. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  5264. if (segment.length === 1)
  5265. continue;
  5266. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  5267. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  5268. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  5269. if (segment.length === 4)
  5270. continue;
  5271. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  5272. }
  5273. }
  5274. return out + td.decode(buf.subarray(0, pos));
  5275. }
  5276. function encodeInteger(buf, pos, state, segment, j) {
  5277. const next = segment[j];
  5278. let num = next - state[j];
  5279. state[j] = next;
  5280. num = num < 0 ? (-num << 1) | 1 : num << 1;
  5281. do {
  5282. let clamped = num & 0b011111;
  5283. num >>>= 5;
  5284. if (num > 0)
  5285. clamped |= 0b100000;
  5286. buf[pos++] = intToChar[clamped];
  5287. } while (num > 0);
  5288. return pos;
  5289. }
  5290. let BitSet$1 = class BitSet {
  5291. constructor(arg) {
  5292. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  5293. }
  5294. add(n) {
  5295. this.bits[n >> 5] |= 1 << (n & 31);
  5296. }
  5297. has(n) {
  5298. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  5299. }
  5300. };
  5301. let Chunk$1 = class Chunk {
  5302. constructor(start, end, content) {
  5303. this.start = start;
  5304. this.end = end;
  5305. this.original = content;
  5306. this.intro = '';
  5307. this.outro = '';
  5308. this.content = content;
  5309. this.storeName = false;
  5310. this.edited = false;
  5311. {
  5312. this.previous = null;
  5313. this.next = null;
  5314. }
  5315. }
  5316. appendLeft(content) {
  5317. this.outro += content;
  5318. }
  5319. appendRight(content) {
  5320. this.intro = this.intro + content;
  5321. }
  5322. clone() {
  5323. const chunk = new Chunk(this.start, this.end, this.original);
  5324. chunk.intro = this.intro;
  5325. chunk.outro = this.outro;
  5326. chunk.content = this.content;
  5327. chunk.storeName = this.storeName;
  5328. chunk.edited = this.edited;
  5329. return chunk;
  5330. }
  5331. contains(index) {
  5332. return this.start < index && index < this.end;
  5333. }
  5334. eachNext(fn) {
  5335. let chunk = this;
  5336. while (chunk) {
  5337. fn(chunk);
  5338. chunk = chunk.next;
  5339. }
  5340. }
  5341. eachPrevious(fn) {
  5342. let chunk = this;
  5343. while (chunk) {
  5344. fn(chunk);
  5345. chunk = chunk.previous;
  5346. }
  5347. }
  5348. edit(content, storeName, contentOnly) {
  5349. this.content = content;
  5350. if (!contentOnly) {
  5351. this.intro = '';
  5352. this.outro = '';
  5353. }
  5354. this.storeName = storeName;
  5355. this.edited = true;
  5356. return this;
  5357. }
  5358. prependLeft(content) {
  5359. this.outro = content + this.outro;
  5360. }
  5361. prependRight(content) {
  5362. this.intro = content + this.intro;
  5363. }
  5364. split(index) {
  5365. const sliceIndex = index - this.start;
  5366. const originalBefore = this.original.slice(0, sliceIndex);
  5367. const originalAfter = this.original.slice(sliceIndex);
  5368. this.original = originalBefore;
  5369. const newChunk = new Chunk(index, this.end, originalAfter);
  5370. newChunk.outro = this.outro;
  5371. this.outro = '';
  5372. this.end = index;
  5373. if (this.edited) {
  5374. // TODO is this block necessary?...
  5375. newChunk.edit('', false);
  5376. this.content = '';
  5377. } else {
  5378. this.content = originalBefore;
  5379. }
  5380. newChunk.next = this.next;
  5381. if (newChunk.next) newChunk.next.previous = newChunk;
  5382. newChunk.previous = this;
  5383. this.next = newChunk;
  5384. return newChunk;
  5385. }
  5386. toString() {
  5387. return this.intro + this.content + this.outro;
  5388. }
  5389. trimEnd(rx) {
  5390. this.outro = this.outro.replace(rx, '');
  5391. if (this.outro.length) return true;
  5392. const trimmed = this.content.replace(rx, '');
  5393. if (trimmed.length) {
  5394. if (trimmed !== this.content) {
  5395. this.split(this.start + trimmed.length).edit('', undefined, true);
  5396. }
  5397. return true;
  5398. } else {
  5399. this.edit('', undefined, true);
  5400. this.intro = this.intro.replace(rx, '');
  5401. if (this.intro.length) return true;
  5402. }
  5403. }
  5404. trimStart(rx) {
  5405. this.intro = this.intro.replace(rx, '');
  5406. if (this.intro.length) return true;
  5407. const trimmed = this.content.replace(rx, '');
  5408. if (trimmed.length) {
  5409. if (trimmed !== this.content) {
  5410. this.split(this.end - trimmed.length);
  5411. this.edit('', undefined, true);
  5412. }
  5413. return true;
  5414. } else {
  5415. this.edit('', undefined, true);
  5416. this.outro = this.outro.replace(rx, '');
  5417. if (this.outro.length) return true;
  5418. }
  5419. }
  5420. };
  5421. function getBtoa$1 () {
  5422. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  5423. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  5424. } else if (typeof Buffer === 'function') {
  5425. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  5426. } else {
  5427. return () => {
  5428. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  5429. };
  5430. }
  5431. }
  5432. const btoa$2 = /*#__PURE__*/ getBtoa$1();
  5433. let SourceMap$2 = class SourceMap {
  5434. constructor(properties) {
  5435. this.version = 3;
  5436. this.file = properties.file;
  5437. this.sources = properties.sources;
  5438. this.sourcesContent = properties.sourcesContent;
  5439. this.names = properties.names;
  5440. this.mappings = encode$1(properties.mappings);
  5441. }
  5442. toString() {
  5443. return JSON.stringify(this);
  5444. }
  5445. toUrl() {
  5446. return 'data:application/json;charset=utf-8;base64,' + btoa$2(this.toString());
  5447. }
  5448. };
  5449. function guessIndent$1(code) {
  5450. const lines = code.split('\n');
  5451. const tabbed = lines.filter((line) => /^\t+/.test(line));
  5452. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  5453. if (tabbed.length === 0 && spaced.length === 0) {
  5454. return null;
  5455. }
  5456. // More lines tabbed than spaced? Assume tabs, and
  5457. // default to tabs in the case of a tie (or nothing
  5458. // to go on)
  5459. if (tabbed.length >= spaced.length) {
  5460. return '\t';
  5461. }
  5462. // Otherwise, we need to guess the multiple
  5463. const min = spaced.reduce((previous, current) => {
  5464. const numSpaces = /^ +/.exec(current)[0].length;
  5465. return Math.min(numSpaces, previous);
  5466. }, Infinity);
  5467. return new Array(min + 1).join(' ');
  5468. }
  5469. function getRelativePath$1(from, to) {
  5470. const fromParts = from.split(/[/\\]/);
  5471. const toParts = to.split(/[/\\]/);
  5472. fromParts.pop(); // get dirname
  5473. while (fromParts[0] === toParts[0]) {
  5474. fromParts.shift();
  5475. toParts.shift();
  5476. }
  5477. if (fromParts.length) {
  5478. let i = fromParts.length;
  5479. while (i--) fromParts[i] = '..';
  5480. }
  5481. return fromParts.concat(toParts).join('/');
  5482. }
  5483. const toString$3 = Object.prototype.toString;
  5484. function isObject$3(thing) {
  5485. return toString$3.call(thing) === '[object Object]';
  5486. }
  5487. function getLocator$1(source) {
  5488. const originalLines = source.split('\n');
  5489. const lineOffsets = [];
  5490. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  5491. lineOffsets.push(pos);
  5492. pos += originalLines[i].length + 1;
  5493. }
  5494. return function locate(index) {
  5495. let i = 0;
  5496. let j = lineOffsets.length;
  5497. while (i < j) {
  5498. const m = (i + j) >> 1;
  5499. if (index < lineOffsets[m]) {
  5500. j = m;
  5501. } else {
  5502. i = m + 1;
  5503. }
  5504. }
  5505. const line = i - 1;
  5506. const column = index - lineOffsets[line];
  5507. return { line, column };
  5508. };
  5509. }
  5510. let Mappings$1 = class Mappings {
  5511. constructor(hires) {
  5512. this.hires = hires;
  5513. this.generatedCodeLine = 0;
  5514. this.generatedCodeColumn = 0;
  5515. this.raw = [];
  5516. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  5517. this.pending = null;
  5518. }
  5519. addEdit(sourceIndex, content, loc, nameIndex) {
  5520. if (content.length) {
  5521. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  5522. if (nameIndex >= 0) {
  5523. segment.push(nameIndex);
  5524. }
  5525. this.rawSegments.push(segment);
  5526. } else if (this.pending) {
  5527. this.rawSegments.push(this.pending);
  5528. }
  5529. this.advance(content);
  5530. this.pending = null;
  5531. }
  5532. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  5533. let originalCharIndex = chunk.start;
  5534. let first = true;
  5535. while (originalCharIndex < chunk.end) {
  5536. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  5537. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  5538. }
  5539. if (original[originalCharIndex] === '\n') {
  5540. loc.line += 1;
  5541. loc.column = 0;
  5542. this.generatedCodeLine += 1;
  5543. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  5544. this.generatedCodeColumn = 0;
  5545. first = true;
  5546. } else {
  5547. loc.column += 1;
  5548. this.generatedCodeColumn += 1;
  5549. first = false;
  5550. }
  5551. originalCharIndex += 1;
  5552. }
  5553. this.pending = null;
  5554. }
  5555. advance(str) {
  5556. if (!str) return;
  5557. const lines = str.split('\n');
  5558. if (lines.length > 1) {
  5559. for (let i = 0; i < lines.length - 1; i++) {
  5560. this.generatedCodeLine++;
  5561. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  5562. }
  5563. this.generatedCodeColumn = 0;
  5564. }
  5565. this.generatedCodeColumn += lines[lines.length - 1].length;
  5566. }
  5567. };
  5568. const n$2 = '\n';
  5569. const warned$1 = {
  5570. insertLeft: false,
  5571. insertRight: false,
  5572. storeName: false,
  5573. };
  5574. let MagicString$1 = class MagicString {
  5575. constructor(string, options = {}) {
  5576. const chunk = new Chunk$1(0, string.length, string);
  5577. Object.defineProperties(this, {
  5578. original: { writable: true, value: string },
  5579. outro: { writable: true, value: '' },
  5580. intro: { writable: true, value: '' },
  5581. firstChunk: { writable: true, value: chunk },
  5582. lastChunk: { writable: true, value: chunk },
  5583. lastSearchedChunk: { writable: true, value: chunk },
  5584. byStart: { writable: true, value: {} },
  5585. byEnd: { writable: true, value: {} },
  5586. filename: { writable: true, value: options.filename },
  5587. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  5588. sourcemapLocations: { writable: true, value: new BitSet$1() },
  5589. storedNames: { writable: true, value: {} },
  5590. indentStr: { writable: true, value: undefined },
  5591. });
  5592. this.byStart[0] = chunk;
  5593. this.byEnd[string.length] = chunk;
  5594. }
  5595. addSourcemapLocation(char) {
  5596. this.sourcemapLocations.add(char);
  5597. }
  5598. append(content) {
  5599. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  5600. this.outro += content;
  5601. return this;
  5602. }
  5603. appendLeft(index, content) {
  5604. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  5605. this._split(index);
  5606. const chunk = this.byEnd[index];
  5607. if (chunk) {
  5608. chunk.appendLeft(content);
  5609. } else {
  5610. this.intro += content;
  5611. }
  5612. return this;
  5613. }
  5614. appendRight(index, content) {
  5615. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  5616. this._split(index);
  5617. const chunk = this.byStart[index];
  5618. if (chunk) {
  5619. chunk.appendRight(content);
  5620. } else {
  5621. this.outro += content;
  5622. }
  5623. return this;
  5624. }
  5625. clone() {
  5626. const cloned = new MagicString(this.original, { filename: this.filename });
  5627. let originalChunk = this.firstChunk;
  5628. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  5629. while (originalChunk) {
  5630. cloned.byStart[clonedChunk.start] = clonedChunk;
  5631. cloned.byEnd[clonedChunk.end] = clonedChunk;
  5632. const nextOriginalChunk = originalChunk.next;
  5633. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  5634. if (nextClonedChunk) {
  5635. clonedChunk.next = nextClonedChunk;
  5636. nextClonedChunk.previous = clonedChunk;
  5637. clonedChunk = nextClonedChunk;
  5638. }
  5639. originalChunk = nextOriginalChunk;
  5640. }
  5641. cloned.lastChunk = clonedChunk;
  5642. if (this.indentExclusionRanges) {
  5643. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  5644. }
  5645. cloned.sourcemapLocations = new BitSet$1(this.sourcemapLocations);
  5646. cloned.intro = this.intro;
  5647. cloned.outro = this.outro;
  5648. return cloned;
  5649. }
  5650. generateDecodedMap(options) {
  5651. options = options || {};
  5652. const sourceIndex = 0;
  5653. const names = Object.keys(this.storedNames);
  5654. const mappings = new Mappings$1(options.hires);
  5655. const locate = getLocator$1(this.original);
  5656. if (this.intro) {
  5657. mappings.advance(this.intro);
  5658. }
  5659. this.firstChunk.eachNext((chunk) => {
  5660. const loc = locate(chunk.start);
  5661. if (chunk.intro.length) mappings.advance(chunk.intro);
  5662. if (chunk.edited) {
  5663. mappings.addEdit(
  5664. sourceIndex,
  5665. chunk.content,
  5666. loc,
  5667. chunk.storeName ? names.indexOf(chunk.original) : -1
  5668. );
  5669. } else {
  5670. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  5671. }
  5672. if (chunk.outro.length) mappings.advance(chunk.outro);
  5673. });
  5674. return {
  5675. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  5676. sources: [options.source ? getRelativePath$1(options.file || '', options.source) : null],
  5677. sourcesContent: options.includeContent ? [this.original] : [null],
  5678. names,
  5679. mappings: mappings.raw,
  5680. };
  5681. }
  5682. generateMap(options) {
  5683. return new SourceMap$2(this.generateDecodedMap(options));
  5684. }
  5685. _ensureindentStr() {
  5686. if (this.indentStr === undefined) {
  5687. this.indentStr = guessIndent$1(this.original);
  5688. }
  5689. }
  5690. _getRawIndentString() {
  5691. this._ensureindentStr();
  5692. return this.indentStr;
  5693. }
  5694. getIndentString() {
  5695. this._ensureindentStr();
  5696. return this.indentStr === null ? '\t' : this.indentStr;
  5697. }
  5698. indent(indentStr, options) {
  5699. const pattern = /^[^\r\n]/gm;
  5700. if (isObject$3(indentStr)) {
  5701. options = indentStr;
  5702. indentStr = undefined;
  5703. }
  5704. if (indentStr === undefined) {
  5705. this._ensureindentStr();
  5706. indentStr = this.indentStr || '\t';
  5707. }
  5708. if (indentStr === '') return this; // noop
  5709. options = options || {};
  5710. // Process exclusion ranges
  5711. const isExcluded = {};
  5712. if (options.exclude) {
  5713. const exclusions =
  5714. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  5715. exclusions.forEach((exclusion) => {
  5716. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  5717. isExcluded[i] = true;
  5718. }
  5719. });
  5720. }
  5721. let shouldIndentNextCharacter = options.indentStart !== false;
  5722. const replacer = (match) => {
  5723. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  5724. shouldIndentNextCharacter = true;
  5725. return match;
  5726. };
  5727. this.intro = this.intro.replace(pattern, replacer);
  5728. let charIndex = 0;
  5729. let chunk = this.firstChunk;
  5730. while (chunk) {
  5731. const end = chunk.end;
  5732. if (chunk.edited) {
  5733. if (!isExcluded[charIndex]) {
  5734. chunk.content = chunk.content.replace(pattern, replacer);
  5735. if (chunk.content.length) {
  5736. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  5737. }
  5738. }
  5739. } else {
  5740. charIndex = chunk.start;
  5741. while (charIndex < end) {
  5742. if (!isExcluded[charIndex]) {
  5743. const char = this.original[charIndex];
  5744. if (char === '\n') {
  5745. shouldIndentNextCharacter = true;
  5746. } else if (char !== '\r' && shouldIndentNextCharacter) {
  5747. shouldIndentNextCharacter = false;
  5748. if (charIndex === chunk.start) {
  5749. chunk.prependRight(indentStr);
  5750. } else {
  5751. this._splitChunk(chunk, charIndex);
  5752. chunk = chunk.next;
  5753. chunk.prependRight(indentStr);
  5754. }
  5755. }
  5756. }
  5757. charIndex += 1;
  5758. }
  5759. }
  5760. charIndex = chunk.end;
  5761. chunk = chunk.next;
  5762. }
  5763. this.outro = this.outro.replace(pattern, replacer);
  5764. return this;
  5765. }
  5766. insert() {
  5767. throw new Error(
  5768. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  5769. );
  5770. }
  5771. insertLeft(index, content) {
  5772. if (!warned$1.insertLeft) {
  5773. console.warn(
  5774. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  5775. ); // eslint-disable-line no-console
  5776. warned$1.insertLeft = true;
  5777. }
  5778. return this.appendLeft(index, content);
  5779. }
  5780. insertRight(index, content) {
  5781. if (!warned$1.insertRight) {
  5782. console.warn(
  5783. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  5784. ); // eslint-disable-line no-console
  5785. warned$1.insertRight = true;
  5786. }
  5787. return this.prependRight(index, content);
  5788. }
  5789. move(start, end, index) {
  5790. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  5791. this._split(start);
  5792. this._split(end);
  5793. this._split(index);
  5794. const first = this.byStart[start];
  5795. const last = this.byEnd[end];
  5796. const oldLeft = first.previous;
  5797. const oldRight = last.next;
  5798. const newRight = this.byStart[index];
  5799. if (!newRight && last === this.lastChunk) return this;
  5800. const newLeft = newRight ? newRight.previous : this.lastChunk;
  5801. if (oldLeft) oldLeft.next = oldRight;
  5802. if (oldRight) oldRight.previous = oldLeft;
  5803. if (newLeft) newLeft.next = first;
  5804. if (newRight) newRight.previous = last;
  5805. if (!first.previous) this.firstChunk = last.next;
  5806. if (!last.next) {
  5807. this.lastChunk = first.previous;
  5808. this.lastChunk.next = null;
  5809. }
  5810. first.previous = newLeft;
  5811. last.next = newRight || null;
  5812. if (!newLeft) this.firstChunk = first;
  5813. if (!newRight) this.lastChunk = last;
  5814. return this;
  5815. }
  5816. overwrite(start, end, content, options) {
  5817. options = options || {};
  5818. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  5819. }
  5820. update(start, end, content, options) {
  5821. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  5822. while (start < 0) start += this.original.length;
  5823. while (end < 0) end += this.original.length;
  5824. if (end > this.original.length) throw new Error('end is out of bounds');
  5825. if (start === end)
  5826. throw new Error(
  5827. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  5828. );
  5829. this._split(start);
  5830. this._split(end);
  5831. if (options === true) {
  5832. if (!warned$1.storeName) {
  5833. console.warn(
  5834. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  5835. ); // eslint-disable-line no-console
  5836. warned$1.storeName = true;
  5837. }
  5838. options = { storeName: true };
  5839. }
  5840. const storeName = options !== undefined ? options.storeName : false;
  5841. const overwrite = options !== undefined ? options.overwrite : false;
  5842. if (storeName) {
  5843. const original = this.original.slice(start, end);
  5844. Object.defineProperty(this.storedNames, original, {
  5845. writable: true,
  5846. value: true,
  5847. enumerable: true,
  5848. });
  5849. }
  5850. const first = this.byStart[start];
  5851. const last = this.byEnd[end];
  5852. if (first) {
  5853. let chunk = first;
  5854. while (chunk !== last) {
  5855. if (chunk.next !== this.byStart[chunk.end]) {
  5856. throw new Error('Cannot overwrite across a split point');
  5857. }
  5858. chunk = chunk.next;
  5859. chunk.edit('', false);
  5860. }
  5861. first.edit(content, storeName, !overwrite);
  5862. } else {
  5863. // must be inserting at the end
  5864. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  5865. // TODO last chunk in the array may not be the last chunk, if it's moved...
  5866. last.next = newChunk;
  5867. newChunk.previous = last;
  5868. }
  5869. return this;
  5870. }
  5871. prepend(content) {
  5872. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  5873. this.intro = content + this.intro;
  5874. return this;
  5875. }
  5876. prependLeft(index, content) {
  5877. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  5878. this._split(index);
  5879. const chunk = this.byEnd[index];
  5880. if (chunk) {
  5881. chunk.prependLeft(content);
  5882. } else {
  5883. this.intro = content + this.intro;
  5884. }
  5885. return this;
  5886. }
  5887. prependRight(index, content) {
  5888. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  5889. this._split(index);
  5890. const chunk = this.byStart[index];
  5891. if (chunk) {
  5892. chunk.prependRight(content);
  5893. } else {
  5894. this.outro = content + this.outro;
  5895. }
  5896. return this;
  5897. }
  5898. remove(start, end) {
  5899. while (start < 0) start += this.original.length;
  5900. while (end < 0) end += this.original.length;
  5901. if (start === end) return this;
  5902. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  5903. if (start > end) throw new Error('end must be greater than start');
  5904. this._split(start);
  5905. this._split(end);
  5906. let chunk = this.byStart[start];
  5907. while (chunk) {
  5908. chunk.intro = '';
  5909. chunk.outro = '';
  5910. chunk.edit('');
  5911. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  5912. }
  5913. return this;
  5914. }
  5915. lastChar() {
  5916. if (this.outro.length) return this.outro[this.outro.length - 1];
  5917. let chunk = this.lastChunk;
  5918. do {
  5919. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  5920. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  5921. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  5922. } while ((chunk = chunk.previous));
  5923. if (this.intro.length) return this.intro[this.intro.length - 1];
  5924. return '';
  5925. }
  5926. lastLine() {
  5927. let lineIndex = this.outro.lastIndexOf(n$2);
  5928. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  5929. let lineStr = this.outro;
  5930. let chunk = this.lastChunk;
  5931. do {
  5932. if (chunk.outro.length > 0) {
  5933. lineIndex = chunk.outro.lastIndexOf(n$2);
  5934. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  5935. lineStr = chunk.outro + lineStr;
  5936. }
  5937. if (chunk.content.length > 0) {
  5938. lineIndex = chunk.content.lastIndexOf(n$2);
  5939. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  5940. lineStr = chunk.content + lineStr;
  5941. }
  5942. if (chunk.intro.length > 0) {
  5943. lineIndex = chunk.intro.lastIndexOf(n$2);
  5944. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  5945. lineStr = chunk.intro + lineStr;
  5946. }
  5947. } while ((chunk = chunk.previous));
  5948. lineIndex = this.intro.lastIndexOf(n$2);
  5949. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  5950. return this.intro + lineStr;
  5951. }
  5952. slice(start = 0, end = this.original.length) {
  5953. while (start < 0) start += this.original.length;
  5954. while (end < 0) end += this.original.length;
  5955. let result = '';
  5956. // find start chunk
  5957. let chunk = this.firstChunk;
  5958. while (chunk && (chunk.start > start || chunk.end <= start)) {
  5959. // found end chunk before start
  5960. if (chunk.start < end && chunk.end >= end) {
  5961. return result;
  5962. }
  5963. chunk = chunk.next;
  5964. }
  5965. if (chunk && chunk.edited && chunk.start !== start)
  5966. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  5967. const startChunk = chunk;
  5968. while (chunk) {
  5969. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  5970. result += chunk.intro;
  5971. }
  5972. const containsEnd = chunk.start < end && chunk.end >= end;
  5973. if (containsEnd && chunk.edited && chunk.end !== end)
  5974. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  5975. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  5976. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  5977. result += chunk.content.slice(sliceStart, sliceEnd);
  5978. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  5979. result += chunk.outro;
  5980. }
  5981. if (containsEnd) {
  5982. break;
  5983. }
  5984. chunk = chunk.next;
  5985. }
  5986. return result;
  5987. }
  5988. // TODO deprecate this? not really very useful
  5989. snip(start, end) {
  5990. const clone = this.clone();
  5991. clone.remove(0, start);
  5992. clone.remove(end, clone.original.length);
  5993. return clone;
  5994. }
  5995. _split(index) {
  5996. if (this.byStart[index] || this.byEnd[index]) return;
  5997. let chunk = this.lastSearchedChunk;
  5998. const searchForward = index > chunk.end;
  5999. while (chunk) {
  6000. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  6001. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  6002. }
  6003. }
  6004. _splitChunk(chunk, index) {
  6005. if (chunk.edited && chunk.content.length) {
  6006. // zero-length edited chunks are a special case (overlapping replacements)
  6007. const loc = getLocator$1(this.original)(index);
  6008. throw new Error(
  6009. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  6010. );
  6011. }
  6012. const newChunk = chunk.split(index);
  6013. this.byEnd[index] = chunk;
  6014. this.byStart[index] = newChunk;
  6015. this.byEnd[newChunk.end] = newChunk;
  6016. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  6017. this.lastSearchedChunk = chunk;
  6018. return true;
  6019. }
  6020. toString() {
  6021. let str = this.intro;
  6022. let chunk = this.firstChunk;
  6023. while (chunk) {
  6024. str += chunk.toString();
  6025. chunk = chunk.next;
  6026. }
  6027. return str + this.outro;
  6028. }
  6029. isEmpty() {
  6030. let chunk = this.firstChunk;
  6031. do {
  6032. if (
  6033. (chunk.intro.length && chunk.intro.trim()) ||
  6034. (chunk.content.length && chunk.content.trim()) ||
  6035. (chunk.outro.length && chunk.outro.trim())
  6036. )
  6037. return false;
  6038. } while ((chunk = chunk.next));
  6039. return true;
  6040. }
  6041. length() {
  6042. let chunk = this.firstChunk;
  6043. let length = 0;
  6044. do {
  6045. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  6046. } while ((chunk = chunk.next));
  6047. return length;
  6048. }
  6049. trimLines() {
  6050. return this.trim('[\\r\\n]');
  6051. }
  6052. trim(charType) {
  6053. return this.trimStart(charType).trimEnd(charType);
  6054. }
  6055. trimEndAborted(charType) {
  6056. const rx = new RegExp((charType || '\\s') + '+$');
  6057. this.outro = this.outro.replace(rx, '');
  6058. if (this.outro.length) return true;
  6059. let chunk = this.lastChunk;
  6060. do {
  6061. const end = chunk.end;
  6062. const aborted = chunk.trimEnd(rx);
  6063. // if chunk was trimmed, we have a new lastChunk
  6064. if (chunk.end !== end) {
  6065. if (this.lastChunk === chunk) {
  6066. this.lastChunk = chunk.next;
  6067. }
  6068. this.byEnd[chunk.end] = chunk;
  6069. this.byStart[chunk.next.start] = chunk.next;
  6070. this.byEnd[chunk.next.end] = chunk.next;
  6071. }
  6072. if (aborted) return true;
  6073. chunk = chunk.previous;
  6074. } while (chunk);
  6075. return false;
  6076. }
  6077. trimEnd(charType) {
  6078. this.trimEndAborted(charType);
  6079. return this;
  6080. }
  6081. trimStartAborted(charType) {
  6082. const rx = new RegExp('^' + (charType || '\\s') + '+');
  6083. this.intro = this.intro.replace(rx, '');
  6084. if (this.intro.length) return true;
  6085. let chunk = this.firstChunk;
  6086. do {
  6087. const end = chunk.end;
  6088. const aborted = chunk.trimStart(rx);
  6089. if (chunk.end !== end) {
  6090. // special case...
  6091. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  6092. this.byEnd[chunk.end] = chunk;
  6093. this.byStart[chunk.next.start] = chunk.next;
  6094. this.byEnd[chunk.next.end] = chunk.next;
  6095. }
  6096. if (aborted) return true;
  6097. chunk = chunk.next;
  6098. } while (chunk);
  6099. return false;
  6100. }
  6101. trimStart(charType) {
  6102. this.trimStartAborted(charType);
  6103. return this;
  6104. }
  6105. hasChanged() {
  6106. return this.original !== this.toString();
  6107. }
  6108. _replaceRegexp(searchValue, replacement) {
  6109. function getReplacement(match, str) {
  6110. if (typeof replacement === 'string') {
  6111. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  6112. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  6113. if (i === '$') return '$';
  6114. if (i === '&') return match[0];
  6115. const num = +i;
  6116. if (num < match.length) return match[+i];
  6117. return `$${i}`;
  6118. });
  6119. } else {
  6120. return replacement(...match, match.index, str, match.groups);
  6121. }
  6122. }
  6123. function matchAll(re, str) {
  6124. let match;
  6125. const matches = [];
  6126. while ((match = re.exec(str))) {
  6127. matches.push(match);
  6128. }
  6129. return matches;
  6130. }
  6131. if (searchValue.global) {
  6132. const matches = matchAll(searchValue, this.original);
  6133. matches.forEach((match) => {
  6134. if (match.index != null)
  6135. this.overwrite(
  6136. match.index,
  6137. match.index + match[0].length,
  6138. getReplacement(match, this.original)
  6139. );
  6140. });
  6141. } else {
  6142. const match = this.original.match(searchValue);
  6143. if (match && match.index != null)
  6144. this.overwrite(
  6145. match.index,
  6146. match.index + match[0].length,
  6147. getReplacement(match, this.original)
  6148. );
  6149. }
  6150. return this;
  6151. }
  6152. _replaceString(string, replacement) {
  6153. const { original } = this;
  6154. const index = original.indexOf(string);
  6155. if (index !== -1) {
  6156. this.overwrite(index, index + string.length, replacement);
  6157. }
  6158. return this;
  6159. }
  6160. replace(searchValue, replacement) {
  6161. if (typeof searchValue === 'string') {
  6162. return this._replaceString(searchValue, replacement);
  6163. }
  6164. return this._replaceRegexp(searchValue, replacement);
  6165. }
  6166. _replaceAllString(string, replacement) {
  6167. const { original } = this;
  6168. const stringLength = string.length;
  6169. for (
  6170. let index = original.indexOf(string);
  6171. index !== -1;
  6172. index = original.indexOf(string, index + stringLength)
  6173. ) {
  6174. this.overwrite(index, index + stringLength, replacement);
  6175. }
  6176. return this;
  6177. }
  6178. replaceAll(searchValue, replacement) {
  6179. if (typeof searchValue === 'string') {
  6180. return this._replaceAllString(searchValue, replacement);
  6181. }
  6182. if (!searchValue.global) {
  6183. throw new TypeError(
  6184. 'MagicString.prototype.replaceAll called with a non-global RegExp argument'
  6185. );
  6186. }
  6187. return this._replaceRegexp(searchValue, replacement);
  6188. }
  6189. };
  6190. function isReference(node, parent) {
  6191. if (node.type === 'MemberExpression') {
  6192. return !node.computed && isReference(node.object, node);
  6193. }
  6194. if (node.type === 'Identifier') {
  6195. if (!parent)
  6196. return true;
  6197. switch (parent.type) {
  6198. // disregard `bar` in `foo.bar`
  6199. case 'MemberExpression': return parent.computed || node === parent.object;
  6200. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  6201. case 'MethodDefinition': return parent.computed;
  6202. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  6203. case 'FieldDefinition': return parent.computed || node === parent.value;
  6204. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  6205. case 'Property': return parent.computed || node === parent.value;
  6206. // disregard the `bar` in `export { foo as bar }` or
  6207. // the foo in `import { foo as bar }`
  6208. case 'ExportSpecifier':
  6209. case 'ImportSpecifier': return node === parent.local;
  6210. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  6211. case 'LabeledStatement':
  6212. case 'BreakStatement':
  6213. case 'ContinueStatement': return false;
  6214. default: return true;
  6215. }
  6216. }
  6217. return false;
  6218. }
  6219. var version$3 = "24.1.0";
  6220. var peerDependencies = {
  6221. rollup: "^2.68.0||^3.0.0"
  6222. };
  6223. function tryParse(parse, code, id) {
  6224. try {
  6225. return parse(code, { allowReturnOutsideFunction: true });
  6226. } catch (err) {
  6227. err.message += ` in ${id}`;
  6228. throw err;
  6229. }
  6230. }
  6231. const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
  6232. const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
  6233. function hasCjsKeywords(code, ignoreGlobal) {
  6234. const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
  6235. return firstpass.test(code);
  6236. }
  6237. /* eslint-disable no-underscore-dangle */
  6238. function analyzeTopLevelStatements(parse, code, id) {
  6239. const ast = tryParse(parse, code, id);
  6240. let isEsModule = false;
  6241. let hasDefaultExport = false;
  6242. let hasNamedExports = false;
  6243. for (const node of ast.body) {
  6244. switch (node.type) {
  6245. case 'ExportDefaultDeclaration':
  6246. isEsModule = true;
  6247. hasDefaultExport = true;
  6248. break;
  6249. case 'ExportNamedDeclaration':
  6250. isEsModule = true;
  6251. if (node.declaration) {
  6252. hasNamedExports = true;
  6253. } else {
  6254. for (const specifier of node.specifiers) {
  6255. if (specifier.exported.name === 'default') {
  6256. hasDefaultExport = true;
  6257. } else {
  6258. hasNamedExports = true;
  6259. }
  6260. }
  6261. }
  6262. break;
  6263. case 'ExportAllDeclaration':
  6264. isEsModule = true;
  6265. if (node.exported && node.exported.name === 'default') {
  6266. hasDefaultExport = true;
  6267. } else {
  6268. hasNamedExports = true;
  6269. }
  6270. break;
  6271. case 'ImportDeclaration':
  6272. isEsModule = true;
  6273. break;
  6274. }
  6275. }
  6276. return { isEsModule, hasDefaultExport, hasNamedExports, ast };
  6277. }
  6278. /* eslint-disable import/prefer-default-export */
  6279. function deconflict(scopes, globals, identifier) {
  6280. let i = 1;
  6281. let deconflicted = makeLegalIdentifier(identifier);
  6282. const hasConflicts = () =>
  6283. scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
  6284. while (hasConflicts()) {
  6285. deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
  6286. i += 1;
  6287. }
  6288. for (const scope of scopes) {
  6289. scope.declarations[deconflicted] = true;
  6290. }
  6291. return deconflicted;
  6292. }
  6293. function getName(id) {
  6294. const name = makeLegalIdentifier(basename$1(id, extname(id)));
  6295. if (name !== 'index') {
  6296. return name;
  6297. }
  6298. return makeLegalIdentifier(basename$1(dirname$1(id)));
  6299. }
  6300. function normalizePathSlashes(path) {
  6301. return path.replace(/\\/g, '/');
  6302. }
  6303. const getVirtualPathForDynamicRequirePath = (path, commonDir) =>
  6304. `/${normalizePathSlashes(relative$1(commonDir, path))}`;
  6305. function capitalize(name) {
  6306. return name[0].toUpperCase() + name.slice(1);
  6307. }
  6308. function getStrictRequiresFilter({ strictRequires }) {
  6309. switch (strictRequires) {
  6310. case true:
  6311. return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
  6312. // eslint-disable-next-line no-undefined
  6313. case undefined:
  6314. case 'auto':
  6315. case 'debug':
  6316. case null:
  6317. return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
  6318. case false:
  6319. return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
  6320. default:
  6321. if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) {
  6322. return {
  6323. strictRequiresFilter: createFilter$1(strictRequires),
  6324. detectCyclesAndConditional: false
  6325. };
  6326. }
  6327. throw new Error('Unexpected value for "strictRequires" option.');
  6328. }
  6329. }
  6330. function getPackageEntryPoint(dirPath) {
  6331. let entryPoint = 'index.js';
  6332. try {
  6333. if (existsSync(join$1(dirPath, 'package.json'))) {
  6334. entryPoint =
  6335. JSON.parse(readFileSync(join$1(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
  6336. entryPoint;
  6337. }
  6338. } catch (ignored) {
  6339. // ignored
  6340. }
  6341. return entryPoint;
  6342. }
  6343. function isDirectory(path) {
  6344. try {
  6345. if (statSync$1(path).isDirectory()) return true;
  6346. } catch (ignored) {
  6347. // Nothing to do here
  6348. }
  6349. return false;
  6350. }
  6351. function getDynamicRequireModules(patterns, dynamicRequireRoot) {
  6352. const dynamicRequireModules = new Map();
  6353. const dirNames = new Set();
  6354. for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
  6355. const isNegated = pattern.startsWith('!');
  6356. const modifyMap = (targetPath, resolvedPath) =>
  6357. isNegated
  6358. ? dynamicRequireModules.delete(targetPath)
  6359. : dynamicRequireModules.set(targetPath, resolvedPath);
  6360. for (const path of glob$1.sync(isNegated ? pattern.substr(1) : pattern)) {
  6361. const resolvedPath = resolve$3(path);
  6362. const requirePath = normalizePathSlashes(resolvedPath);
  6363. if (isDirectory(resolvedPath)) {
  6364. dirNames.add(resolvedPath);
  6365. const modulePath = resolve$3(join$1(resolvedPath, getPackageEntryPoint(path)));
  6366. modifyMap(requirePath, modulePath);
  6367. modifyMap(normalizePathSlashes(modulePath), modulePath);
  6368. } else {
  6369. dirNames.add(dirname$1(resolvedPath));
  6370. modifyMap(requirePath, resolvedPath);
  6371. }
  6372. }
  6373. }
  6374. return {
  6375. commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null,
  6376. dynamicRequireModules
  6377. };
  6378. }
  6379. const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
  6380. const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
  6381. const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
  6382. function getDynamicModuleRegistry(
  6383. isDynamicRequireModulesEnabled,
  6384. dynamicRequireModules,
  6385. commonDir,
  6386. ignoreDynamicRequires
  6387. ) {
  6388. if (!isDynamicRequireModulesEnabled) {
  6389. return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
  6390. ${FAILED_REQUIRE_ERROR}
  6391. }`;
  6392. }
  6393. const dynamicModuleImports = [...dynamicRequireModules.values()]
  6394. .map(
  6395. (id, index) =>
  6396. `import ${
  6397. id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }`
  6398. } from ${JSON.stringify(id)};`
  6399. )
  6400. .join('\n');
  6401. const dynamicModuleProps = [...dynamicRequireModules.keys()]
  6402. .map(
  6403. (id, index) =>
  6404. `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${
  6405. id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}`
  6406. }`
  6407. )
  6408. .join(',\n');
  6409. return `${dynamicModuleImports}
  6410. var dynamicModules;
  6411. function getDynamicModules() {
  6412. return dynamicModules || (dynamicModules = {
  6413. ${dynamicModuleProps}
  6414. });
  6415. }
  6416. export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
  6417. function handleRequire(path) {
  6418. var resolvedPath = commonjsResolve(path, originalModuleDir);
  6419. if (resolvedPath !== null) {
  6420. return getDynamicModules()[resolvedPath]();
  6421. }
  6422. ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
  6423. }
  6424. handleRequire.resolve = function (path) {
  6425. var resolvedPath = commonjsResolve(path, originalModuleDir);
  6426. if (resolvedPath !== null) {
  6427. return resolvedPath;
  6428. }
  6429. return require.resolve(path);
  6430. }
  6431. return handleRequire;
  6432. }
  6433. function commonjsResolve (path, originalModuleDir) {
  6434. var shouldTryNodeModules = isPossibleNodeModulesPath(path);
  6435. path = normalize(path);
  6436. var relPath;
  6437. if (path[0] === '/') {
  6438. originalModuleDir = '';
  6439. }
  6440. var modules = getDynamicModules();
  6441. var checkedExtensions = ['', '.js', '.json'];
  6442. while (true) {
  6443. if (!shouldTryNodeModules) {
  6444. relPath = normalize(originalModuleDir + '/' + path);
  6445. } else {
  6446. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  6447. }
  6448. if (relPath.endsWith('/..')) {
  6449. break; // Travelled too far up, avoid infinite loop
  6450. }
  6451. for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
  6452. var resolvedPath = relPath + checkedExtensions[extensionIndex];
  6453. if (modules[resolvedPath]) {
  6454. return resolvedPath;
  6455. }
  6456. }
  6457. if (!shouldTryNodeModules) break;
  6458. var nextDir = normalize(originalModuleDir + '/..');
  6459. if (nextDir === originalModuleDir) break;
  6460. originalModuleDir = nextDir;
  6461. }
  6462. return null;
  6463. }
  6464. function isPossibleNodeModulesPath (modulePath) {
  6465. var c0 = modulePath[0];
  6466. if (c0 === '/' || c0 === '\\\\') return false;
  6467. var c1 = modulePath[1], c2 = modulePath[2];
  6468. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
  6469. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
  6470. if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
  6471. return true;
  6472. }
  6473. function normalize (path) {
  6474. path = path.replace(/\\\\/g, '/');
  6475. var parts = path.split('/');
  6476. var slashed = parts[0] === '';
  6477. for (var i = 1; i < parts.length; i++) {
  6478. if (parts[i] === '.' || parts[i] === '') {
  6479. parts.splice(i--, 1);
  6480. }
  6481. }
  6482. for (var i = 1; i < parts.length; i++) {
  6483. if (parts[i] !== '..') continue;
  6484. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  6485. parts.splice(--i, 2);
  6486. i--;
  6487. }
  6488. }
  6489. path = parts.join('/');
  6490. if (slashed && path[0] !== '/') path = '/' + path;
  6491. else if (path.length === 0) path = '.';
  6492. return path;
  6493. }`;
  6494. }
  6495. const isWrappedId = (id, suffix) => id.endsWith(suffix);
  6496. const wrapId$1 = (id, suffix) => `\0${id}${suffix}`;
  6497. const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
  6498. const PROXY_SUFFIX = '?commonjs-proxy';
  6499. const WRAPPED_SUFFIX = '?commonjs-wrapped';
  6500. const EXTERNAL_SUFFIX = '?commonjs-external';
  6501. const EXPORTS_SUFFIX = '?commonjs-exports';
  6502. const MODULE_SUFFIX = '?commonjs-module';
  6503. const ENTRY_SUFFIX = '?commonjs-entry';
  6504. const ES_IMPORT_SUFFIX = '?commonjs-es-import';
  6505. const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
  6506. const HELPERS_ID = '\0commonjsHelpers.js';
  6507. const IS_WRAPPED_COMMONJS = 'withRequireFunction';
  6508. // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
  6509. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
  6510. // This could be improved by inspecting Rollup's "generatedCode" option
  6511. const HELPERS = `
  6512. export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  6513. export function getDefaultExportFromCjs (x) {
  6514. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  6515. }
  6516. export function getDefaultExportFromNamespaceIfPresent (n) {
  6517. return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  6518. }
  6519. export function getDefaultExportFromNamespaceIfNotNamed (n) {
  6520. return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  6521. }
  6522. export function getAugmentedNamespace(n) {
  6523. if (n.__esModule) return n;
  6524. var f = n.default;
  6525. if (typeof f == "function") {
  6526. var a = function a () {
  6527. if (this instanceof a) {
  6528. var args = [null];
  6529. args.push.apply(args, arguments);
  6530. var Ctor = Function.bind.apply(f, args);
  6531. return new Ctor();
  6532. }
  6533. return f.apply(this, arguments);
  6534. };
  6535. a.prototype = f.prototype;
  6536. } else a = {};
  6537. Object.defineProperty(a, '__esModule', {value: true});
  6538. Object.keys(n).forEach(function (k) {
  6539. var d = Object.getOwnPropertyDescriptor(n, k);
  6540. Object.defineProperty(a, k, d.get ? d : {
  6541. enumerable: true,
  6542. get: function () {
  6543. return n[k];
  6544. }
  6545. });
  6546. });
  6547. return a;
  6548. }
  6549. `;
  6550. function getHelpersModule() {
  6551. return HELPERS;
  6552. }
  6553. function getUnknownRequireProxy(id, requireReturnsDefault) {
  6554. if (requireReturnsDefault === true || id.endsWith('.json')) {
  6555. return `export { default } from ${JSON.stringify(id)};`;
  6556. }
  6557. const name = getName(id);
  6558. const exported =
  6559. requireReturnsDefault === 'auto'
  6560. ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
  6561. : requireReturnsDefault === 'preferred'
  6562. ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
  6563. : !requireReturnsDefault
  6564. ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
  6565. : `export default ${name};`;
  6566. return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
  6567. }
  6568. async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
  6569. const name = getName(id);
  6570. const {
  6571. meta: { commonjs: commonjsMeta }
  6572. } = await loadModule({ id });
  6573. if (!commonjsMeta) {
  6574. return getUnknownRequireProxy(id, requireReturnsDefault);
  6575. }
  6576. if (commonjsMeta.isCommonJS) {
  6577. return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
  6578. }
  6579. if (!requireReturnsDefault) {
  6580. return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
  6581. id
  6582. )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
  6583. }
  6584. if (
  6585. requireReturnsDefault !== true &&
  6586. (requireReturnsDefault === 'namespace' ||
  6587. !commonjsMeta.hasDefaultExport ||
  6588. (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
  6589. ) {
  6590. return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
  6591. }
  6592. return `export { default } from ${JSON.stringify(id)};`;
  6593. }
  6594. function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
  6595. const {
  6596. meta: { commonjs: commonjsMeta },
  6597. hasDefaultExport
  6598. } = getModuleInfo(id);
  6599. if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
  6600. const stringifiedId = JSON.stringify(id);
  6601. let code = `export * from ${stringifiedId};`;
  6602. if (hasDefaultExport) {
  6603. code += `export { default } from ${stringifiedId};`;
  6604. }
  6605. return code;
  6606. }
  6607. return getEsImportProxy(id, defaultIsModuleExports);
  6608. }
  6609. function getEsImportProxy(id, defaultIsModuleExports) {
  6610. const name = getName(id);
  6611. const exportsName = `${name}Exports`;
  6612. const requireModule = `require${capitalize(name)}`;
  6613. let code =
  6614. `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` +
  6615. `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` +
  6616. `var ${exportsName} = ${requireModule}();\n` +
  6617. `export { ${exportsName} as __moduleExports };`;
  6618. if (defaultIsModuleExports === true) {
  6619. code += `\nexport { ${exportsName} as default };`;
  6620. } else {
  6621. code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
  6622. }
  6623. return {
  6624. code,
  6625. syntheticNamedExports: '__moduleExports'
  6626. };
  6627. }
  6628. /* eslint-disable no-param-reassign, no-undefined */
  6629. function getCandidatesForExtension(resolved, extension) {
  6630. return [resolved + extension, `${resolved}${sep$1}index${extension}`];
  6631. }
  6632. function getCandidates(resolved, extensions) {
  6633. return extensions.reduce(
  6634. (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
  6635. [resolved]
  6636. );
  6637. }
  6638. function resolveExtensions(importee, importer, extensions) {
  6639. // not our problem
  6640. if (importee[0] !== '.' || !importer) return undefined;
  6641. const resolved = resolve$3(dirname$1(importer), importee);
  6642. const candidates = getCandidates(resolved, extensions);
  6643. for (let i = 0; i < candidates.length; i += 1) {
  6644. try {
  6645. const stats = statSync$1(candidates[i]);
  6646. if (stats.isFile()) return { id: candidates[i] };
  6647. } catch (err) {
  6648. /* noop */
  6649. }
  6650. }
  6651. return undefined;
  6652. }
  6653. function getResolveId(extensions, isPossibleCjsId) {
  6654. const currentlyResolving = new Map();
  6655. return {
  6656. /**
  6657. * This is a Maps of importers to Sets of require sources being resolved at
  6658. * the moment by resolveRequireSourcesAndUpdateMeta
  6659. */
  6660. currentlyResolving,
  6661. async resolveId(importee, importer, resolveOptions) {
  6662. const customOptions = resolveOptions.custom;
  6663. // All logic below is specific to ES imports.
  6664. // Also, if we do not skip this logic for requires that are resolved while
  6665. // transforming a commonjs file, it can easily lead to deadlocks.
  6666. if (
  6667. customOptions &&
  6668. customOptions['node-resolve'] &&
  6669. customOptions['node-resolve'].isRequire
  6670. ) {
  6671. return null;
  6672. }
  6673. const currentlyResolvingForParent = currentlyResolving.get(importer);
  6674. if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
  6675. this.warn({
  6676. code: 'THIS_RESOLVE_WITHOUT_OPTIONS',
  6677. message:
  6678. 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
  6679. url: 'https://rollupjs.org/guide/en/#resolveid'
  6680. });
  6681. return null;
  6682. }
  6683. if (isWrappedId(importee, WRAPPED_SUFFIX)) {
  6684. return unwrapId$1(importee, WRAPPED_SUFFIX);
  6685. }
  6686. if (
  6687. importee.endsWith(ENTRY_SUFFIX) ||
  6688. isWrappedId(importee, MODULE_SUFFIX) ||
  6689. isWrappedId(importee, EXPORTS_SUFFIX) ||
  6690. isWrappedId(importee, PROXY_SUFFIX) ||
  6691. isWrappedId(importee, ES_IMPORT_SUFFIX) ||
  6692. isWrappedId(importee, EXTERNAL_SUFFIX) ||
  6693. importee.startsWith(HELPERS_ID) ||
  6694. importee === DYNAMIC_MODULES_ID
  6695. ) {
  6696. return importee;
  6697. }
  6698. if (importer) {
  6699. if (
  6700. importer === DYNAMIC_MODULES_ID ||
  6701. // Proxies are only importing resolved ids, no need to resolve again
  6702. isWrappedId(importer, PROXY_SUFFIX) ||
  6703. isWrappedId(importer, ES_IMPORT_SUFFIX) ||
  6704. importer.endsWith(ENTRY_SUFFIX)
  6705. ) {
  6706. return importee;
  6707. }
  6708. if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
  6709. // We need to return null for unresolved imports so that the proper warning is shown
  6710. if (
  6711. !(await this.resolve(
  6712. importee,
  6713. importer,
  6714. Object.assign({ skipSelf: true }, resolveOptions)
  6715. ))
  6716. ) {
  6717. return null;
  6718. }
  6719. // For other external imports, we need to make sure they are handled as external
  6720. return { id: importee, external: true };
  6721. }
  6722. }
  6723. if (importee.startsWith('\0')) {
  6724. return null;
  6725. }
  6726. // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
  6727. // if that is the case, we need to add a proxy.
  6728. const resolved =
  6729. (await this.resolve(
  6730. importee,
  6731. importer,
  6732. Object.assign({ skipSelf: true }, resolveOptions)
  6733. )) || resolveExtensions(importee, importer, extensions);
  6734. // Make sure that even if other plugins resolve again, we ignore our own proxies
  6735. if (
  6736. !resolved ||
  6737. resolved.external ||
  6738. resolved.id.endsWith(ENTRY_SUFFIX) ||
  6739. isWrappedId(resolved.id, ES_IMPORT_SUFFIX) ||
  6740. !isPossibleCjsId(resolved.id)
  6741. ) {
  6742. return resolved;
  6743. }
  6744. const moduleInfo = await this.load(resolved);
  6745. const {
  6746. meta: { commonjs: commonjsMeta }
  6747. } = moduleInfo;
  6748. if (commonjsMeta) {
  6749. const { isCommonJS } = commonjsMeta;
  6750. if (isCommonJS) {
  6751. if (resolveOptions.isEntry) {
  6752. moduleInfo.moduleSideEffects = true;
  6753. // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
  6754. return resolved.id + ENTRY_SUFFIX;
  6755. }
  6756. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  6757. return { id: wrapId$1(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
  6758. }
  6759. }
  6760. }
  6761. return resolved;
  6762. }
  6763. };
  6764. }
  6765. function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) {
  6766. const knownCjsModuleTypes = Object.create(null);
  6767. const requiredIds = Object.create(null);
  6768. const unconditionallyRequiredIds = Object.create(null);
  6769. const dependencies = Object.create(null);
  6770. const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
  6771. const isCyclic = (id) => {
  6772. const dependenciesToCheck = new Set(getDependencies(id));
  6773. for (const dependency of dependenciesToCheck) {
  6774. if (dependency === id) {
  6775. return true;
  6776. }
  6777. for (const childDependency of getDependencies(dependency)) {
  6778. dependenciesToCheck.add(childDependency);
  6779. }
  6780. }
  6781. return false;
  6782. };
  6783. // Once a module is listed here, its type (wrapped or not) is fixed and may
  6784. // not change for the rest of the current build, to not break already
  6785. // transformed modules.
  6786. const fullyAnalyzedModules = Object.create(null);
  6787. const getTypeForFullyAnalyzedModule = (id) => {
  6788. const knownType = knownCjsModuleTypes[id];
  6789. if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
  6790. return knownType;
  6791. }
  6792. if (isCyclic(id)) {
  6793. return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
  6794. }
  6795. return knownType;
  6796. };
  6797. const setInitialParentType = (id, initialCommonJSType) => {
  6798. // Fully analyzed modules may never change type
  6799. if (fullyAnalyzedModules[id]) {
  6800. return;
  6801. }
  6802. knownCjsModuleTypes[id] = initialCommonJSType;
  6803. if (
  6804. detectCyclesAndConditional &&
  6805. knownCjsModuleTypes[id] === true &&
  6806. requiredIds[id] &&
  6807. !unconditionallyRequiredIds[id]
  6808. ) {
  6809. knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
  6810. }
  6811. };
  6812. const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
  6813. const childId = resolved.id;
  6814. requiredIds[childId] = true;
  6815. if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
  6816. unconditionallyRequiredIds[childId] = true;
  6817. }
  6818. getDependencies(parentId).add(childId);
  6819. if (!isCyclic(childId)) {
  6820. // This makes sure the current transform handler waits for all direct
  6821. // dependencies to be loaded and transformed and therefore for all
  6822. // transitive CommonJS dependencies to be loaded as well so that all
  6823. // cycles have been found and knownCjsModuleTypes is reliable.
  6824. await loadModule(resolved);
  6825. }
  6826. };
  6827. const getTypeForImportedModule = async (resolved, loadModule) => {
  6828. if (resolved.id in knownCjsModuleTypes) {
  6829. // This handles cyclic ES dependencies
  6830. return knownCjsModuleTypes[resolved.id];
  6831. }
  6832. const {
  6833. meta: { commonjs }
  6834. } = await loadModule(resolved);
  6835. return (commonjs && commonjs.isCommonJS) || false;
  6836. };
  6837. return {
  6838. getWrappedIds: () =>
  6839. Object.keys(knownCjsModuleTypes).filter(
  6840. (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
  6841. ),
  6842. isRequiredId: (id) => requiredIds[id],
  6843. async shouldTransformCachedModule({
  6844. id: parentId,
  6845. resolvedSources,
  6846. meta: { commonjs: parentMeta }
  6847. }) {
  6848. // We explicitly track ES modules to handle circular imports
  6849. if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
  6850. if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
  6851. const parentRequires = parentMeta && parentMeta.requires;
  6852. if (parentRequires) {
  6853. setInitialParentType(parentId, parentMeta.initialCommonJSType);
  6854. await Promise.all(
  6855. parentRequires.map(({ resolved, isConditional }) =>
  6856. analyzeRequiredModule(parentId, resolved, isConditional, this.load)
  6857. )
  6858. );
  6859. if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
  6860. return true;
  6861. }
  6862. for (const {
  6863. resolved: { id }
  6864. } of parentRequires) {
  6865. if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
  6866. return true;
  6867. }
  6868. }
  6869. // Now that we decided to go with the cached copy, neither the parent
  6870. // module nor any of its children may change types anymore
  6871. fullyAnalyzedModules[parentId] = true;
  6872. for (const {
  6873. resolved: { id }
  6874. } of parentRequires) {
  6875. fullyAnalyzedModules[id] = true;
  6876. }
  6877. }
  6878. const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
  6879. return (
  6880. await Promise.all(
  6881. Object.keys(resolvedSources)
  6882. .map((source) => resolvedSources[source])
  6883. .filter(({ id, external }) => !(external || parentRequireSet.has(id)))
  6884. .map(async (resolved) => {
  6885. if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
  6886. return (
  6887. (await getTypeForImportedModule(
  6888. (
  6889. await this.load({ id: resolved.id })
  6890. ).meta.commonjs.resolved,
  6891. this.load
  6892. )) !== IS_WRAPPED_COMMONJS
  6893. );
  6894. }
  6895. return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
  6896. })
  6897. )
  6898. ).some((shouldTransform) => shouldTransform);
  6899. },
  6900. /* eslint-disable no-param-reassign */
  6901. resolveRequireSourcesAndUpdateMeta:
  6902. (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
  6903. parentMeta.initialCommonJSType = isParentCommonJS;
  6904. parentMeta.requires = [];
  6905. parentMeta.isRequiredCommonJS = Object.create(null);
  6906. setInitialParentType(parentId, isParentCommonJS);
  6907. const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set();
  6908. currentlyResolving.set(parentId, currentlyResolvingForParent);
  6909. const requireTargets = await Promise.all(
  6910. sources.map(async ({ source, isConditional }) => {
  6911. // Never analyze or proxy internal modules
  6912. if (source.startsWith('\0')) {
  6913. return { id: source, allowProxy: false };
  6914. }
  6915. currentlyResolvingForParent.add(source);
  6916. const resolved =
  6917. (await rollupContext.resolve(source, parentId, {
  6918. custom: { 'node-resolve': { isRequire: true } }
  6919. })) || resolveExtensions(source, parentId, extensions);
  6920. currentlyResolvingForParent.delete(source);
  6921. if (!resolved) {
  6922. return { id: wrapId$1(source, EXTERNAL_SUFFIX), allowProxy: false };
  6923. }
  6924. const childId = resolved.id;
  6925. if (resolved.external) {
  6926. return { id: wrapId$1(childId, EXTERNAL_SUFFIX), allowProxy: false };
  6927. }
  6928. parentMeta.requires.push({ resolved, isConditional });
  6929. await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
  6930. return { id: childId, allowProxy: true };
  6931. })
  6932. );
  6933. parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
  6934. fullyAnalyzedModules[parentId] = true;
  6935. return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
  6936. // eslint-disable-next-line no-multi-assign
  6937. const isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] =
  6938. getTypeForFullyAnalyzedModule(dependencyId));
  6939. fullyAnalyzedModules[dependencyId] = true;
  6940. return {
  6941. source: sources[index].source,
  6942. id: allowProxy
  6943. ? isCommonJS === IS_WRAPPED_COMMONJS
  6944. ? wrapId$1(dependencyId, WRAPPED_SUFFIX)
  6945. : wrapId$1(dependencyId, PROXY_SUFFIX)
  6946. : dependencyId,
  6947. isCommonJS
  6948. };
  6949. });
  6950. },
  6951. isCurrentlyResolving(source, parentId) {
  6952. const currentlyResolvingForParent = currentlyResolving.get(parentId);
  6953. return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
  6954. }
  6955. };
  6956. }
  6957. function validateVersion(actualVersion, peerDependencyVersion, name) {
  6958. const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
  6959. let minMajor = Infinity;
  6960. let minMinor = Infinity;
  6961. let minPatch = Infinity;
  6962. let foundVersion;
  6963. // eslint-disable-next-line no-cond-assign
  6964. while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
  6965. const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
  6966. if (foundMajor < minMajor) {
  6967. minMajor = foundMajor;
  6968. minMinor = foundMinor;
  6969. minPatch = foundPatch;
  6970. }
  6971. }
  6972. if (!actualVersion) {
  6973. throw new Error(
  6974. `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
  6975. );
  6976. }
  6977. const [major, minor, patch] = actualVersion.split('.').map(Number);
  6978. if (
  6979. major < minMajor ||
  6980. (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
  6981. ) {
  6982. throw new Error(
  6983. `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
  6984. );
  6985. }
  6986. }
  6987. const operators = {
  6988. '==': (x) => equals(x.left, x.right, false),
  6989. '!=': (x) => not(operators['=='](x)),
  6990. '===': (x) => equals(x.left, x.right, true),
  6991. '!==': (x) => not(operators['==='](x)),
  6992. '!': (x) => isFalsy(x.argument),
  6993. '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
  6994. '||': (x) => isTruthy(x.left) || isTruthy(x.right)
  6995. };
  6996. function not(value) {
  6997. return value === null ? value : !value;
  6998. }
  6999. function equals(a, b, strict) {
  7000. if (a.type !== b.type) return null;
  7001. // eslint-disable-next-line eqeqeq
  7002. if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
  7003. return null;
  7004. }
  7005. function isTruthy(node) {
  7006. if (!node) return false;
  7007. if (node.type === 'Literal') return !!node.value;
  7008. if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
  7009. if (node.operator in operators) return operators[node.operator](node);
  7010. return null;
  7011. }
  7012. function isFalsy(node) {
  7013. return not(isTruthy(node));
  7014. }
  7015. function getKeypath(node) {
  7016. const parts = [];
  7017. while (node.type === 'MemberExpression') {
  7018. if (node.computed) return null;
  7019. parts.unshift(node.property.name);
  7020. // eslint-disable-next-line no-param-reassign
  7021. node = node.object;
  7022. }
  7023. if (node.type !== 'Identifier') return null;
  7024. const { name } = node;
  7025. parts.unshift(name);
  7026. return { name, keypath: parts.join('.') };
  7027. }
  7028. const KEY_COMPILED_ESM = '__esModule';
  7029. function getDefineCompiledEsmType(node) {
  7030. const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports');
  7031. const definedProperty =
  7032. definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports');
  7033. if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
  7034. return isTruthy(definedProperty.value)
  7035. ? definedPropertyWithExports
  7036. ? 'exports'
  7037. : 'module'
  7038. : false;
  7039. }
  7040. return false;
  7041. }
  7042. function getDefinePropertyCallName(node, targetName) {
  7043. const {
  7044. callee: { object, property }
  7045. } = node;
  7046. if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
  7047. if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
  7048. if (node.arguments.length !== 3) return;
  7049. const targetNames = targetName.split('.');
  7050. const [target, key, value] = node.arguments;
  7051. if (targetNames.length === 1) {
  7052. if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
  7053. return;
  7054. }
  7055. }
  7056. if (targetNames.length === 2) {
  7057. if (
  7058. target.type !== 'MemberExpression' ||
  7059. target.object.name !== targetNames[0] ||
  7060. target.property.name !== targetNames[1]
  7061. ) {
  7062. return;
  7063. }
  7064. }
  7065. if (value.type !== 'ObjectExpression' || !value.properties) return;
  7066. const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
  7067. if (!valueProperty || !valueProperty.value) return;
  7068. // eslint-disable-next-line consistent-return
  7069. return { key: key.value, value: valueProperty.value };
  7070. }
  7071. function isShorthandProperty(parent) {
  7072. return parent && parent.type === 'Property' && parent.shorthand;
  7073. }
  7074. function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
  7075. const args = [];
  7076. const passedArgs = [];
  7077. if (uses.module) {
  7078. args.push('module');
  7079. passedArgs.push(moduleName);
  7080. }
  7081. if (uses.exports) {
  7082. args.push('exports');
  7083. passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName);
  7084. }
  7085. magicString
  7086. .trim()
  7087. .indent('\t', { exclude: indentExclusionRanges })
  7088. .prepend(`(function (${args.join(', ')}) {\n`)
  7089. // For some reason, this line is only indented correctly when using a
  7090. // require-wrapper if we have this leading space
  7091. .append(` \n} (${passedArgs.join(', ')}));`);
  7092. }
  7093. function rewriteExportsAndGetExportsBlock(
  7094. magicString,
  7095. moduleName,
  7096. exportsName,
  7097. exportedExportsName,
  7098. wrapped,
  7099. moduleExportsAssignments,
  7100. firstTopLevelModuleExportsAssignment,
  7101. exportsAssignmentsByName,
  7102. topLevelAssignments,
  7103. defineCompiledEsmExpressions,
  7104. deconflictedExportNames,
  7105. code,
  7106. HELPERS_NAME,
  7107. exportMode,
  7108. defaultIsModuleExports,
  7109. usesRequireWrapper,
  7110. requireName
  7111. ) {
  7112. const exports = [];
  7113. const exportDeclarations = [];
  7114. if (usesRequireWrapper) {
  7115. getExportsWhenUsingRequireWrapper(
  7116. magicString,
  7117. wrapped,
  7118. exportMode,
  7119. exports,
  7120. moduleExportsAssignments,
  7121. exportsAssignmentsByName,
  7122. moduleName,
  7123. exportsName,
  7124. requireName,
  7125. defineCompiledEsmExpressions
  7126. );
  7127. } else if (exportMode === 'replace') {
  7128. getExportsForReplacedModuleExports(
  7129. magicString,
  7130. exports,
  7131. exportDeclarations,
  7132. moduleExportsAssignments,
  7133. firstTopLevelModuleExportsAssignment,
  7134. exportsName,
  7135. defaultIsModuleExports,
  7136. HELPERS_NAME
  7137. );
  7138. } else {
  7139. if (exportMode === 'module') {
  7140. exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`);
  7141. exports.push(`${exportedExportsName} as __moduleExports`);
  7142. } else {
  7143. exports.push(`${exportsName} as __moduleExports`);
  7144. }
  7145. if (wrapped) {
  7146. exportDeclarations.push(
  7147. getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
  7148. );
  7149. } else {
  7150. getExports(
  7151. magicString,
  7152. exports,
  7153. exportDeclarations,
  7154. moduleExportsAssignments,
  7155. exportsAssignmentsByName,
  7156. deconflictedExportNames,
  7157. topLevelAssignments,
  7158. moduleName,
  7159. exportsName,
  7160. exportedExportsName,
  7161. defineCompiledEsmExpressions,
  7162. HELPERS_NAME,
  7163. defaultIsModuleExports,
  7164. exportMode
  7165. );
  7166. }
  7167. }
  7168. if (exports.length) {
  7169. exportDeclarations.push(`export { ${exports.join(', ')} }`);
  7170. }
  7171. return `\n\n${exportDeclarations.join(';\n')};`;
  7172. }
  7173. function getExportsWhenUsingRequireWrapper(
  7174. magicString,
  7175. wrapped,
  7176. exportMode,
  7177. exports,
  7178. moduleExportsAssignments,
  7179. exportsAssignmentsByName,
  7180. moduleName,
  7181. exportsName,
  7182. requireName,
  7183. defineCompiledEsmExpressions
  7184. ) {
  7185. exports.push(`${requireName} as __require`);
  7186. if (wrapped) return;
  7187. if (exportMode === 'replace') {
  7188. rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName);
  7189. } else {
  7190. rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`);
  7191. // Collect and rewrite named exports
  7192. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  7193. for (const { node, type } of nodes) {
  7194. magicString.overwrite(
  7195. node.start,
  7196. node.left.end,
  7197. `${
  7198. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  7199. }.${exportName}`
  7200. );
  7201. }
  7202. }
  7203. replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  7204. defineCompiledEsmExpressions,
  7205. magicString,
  7206. exportMode,
  7207. moduleName,
  7208. exportsName
  7209. );
  7210. }
  7211. }
  7212. function getExportsForReplacedModuleExports(
  7213. magicString,
  7214. exports,
  7215. exportDeclarations,
  7216. moduleExportsAssignments,
  7217. firstTopLevelModuleExportsAssignment,
  7218. exportsName,
  7219. defaultIsModuleExports,
  7220. HELPERS_NAME
  7221. ) {
  7222. for (const { left } of moduleExportsAssignments) {
  7223. magicString.overwrite(left.start, left.end, exportsName);
  7224. }
  7225. magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
  7226. exports.push(`${exportsName} as __moduleExports`);
  7227. exportDeclarations.push(
  7228. getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME)
  7229. );
  7230. }
  7231. function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) {
  7232. return `export default ${
  7233. defaultIsModuleExports === true
  7234. ? exportedExportsName
  7235. : defaultIsModuleExports === false
  7236. ? `${exportedExportsName}.default`
  7237. : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`
  7238. }`;
  7239. }
  7240. function getExports(
  7241. magicString,
  7242. exports,
  7243. exportDeclarations,
  7244. moduleExportsAssignments,
  7245. exportsAssignmentsByName,
  7246. deconflictedExportNames,
  7247. topLevelAssignments,
  7248. moduleName,
  7249. exportsName,
  7250. exportedExportsName,
  7251. defineCompiledEsmExpressions,
  7252. HELPERS_NAME,
  7253. defaultIsModuleExports,
  7254. exportMode
  7255. ) {
  7256. let deconflictedDefaultExportName;
  7257. // Collect and rewrite module.exports assignments
  7258. for (const { left } of moduleExportsAssignments) {
  7259. magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
  7260. }
  7261. // Collect and rewrite named exports
  7262. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  7263. const deconflicted = deconflictedExportNames[exportName];
  7264. let needsDeclaration = true;
  7265. for (const { node, type } of nodes) {
  7266. let replacement = `${deconflicted} = ${
  7267. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  7268. }.${exportName}`;
  7269. if (needsDeclaration && topLevelAssignments.has(node)) {
  7270. replacement = `var ${replacement}`;
  7271. needsDeclaration = false;
  7272. }
  7273. magicString.overwrite(node.start, node.left.end, replacement);
  7274. }
  7275. if (needsDeclaration) {
  7276. magicString.prepend(`var ${deconflicted};\n`);
  7277. }
  7278. if (exportName === 'default') {
  7279. deconflictedDefaultExportName = deconflicted;
  7280. } else {
  7281. exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
  7282. }
  7283. }
  7284. const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  7285. defineCompiledEsmExpressions,
  7286. magicString,
  7287. exportMode,
  7288. moduleName,
  7289. exportsName
  7290. );
  7291. if (
  7292. defaultIsModuleExports === false ||
  7293. (defaultIsModuleExports === 'auto' &&
  7294. isRestorableCompiledEsm &&
  7295. moduleExportsAssignments.length === 0)
  7296. ) {
  7297. // If there is no deconflictedDefaultExportName, then we use the namespace as
  7298. // fallback because there can be no "default" property on the namespace
  7299. exports.push(`${deconflictedDefaultExportName || exportedExportsName} as default`);
  7300. } else if (
  7301. defaultIsModuleExports === true ||
  7302. (!isRestorableCompiledEsm && moduleExportsAssignments.length === 0)
  7303. ) {
  7304. exports.push(`${exportedExportsName} as default`);
  7305. } else {
  7306. exportDeclarations.push(
  7307. getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
  7308. );
  7309. }
  7310. }
  7311. function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) {
  7312. for (const { left } of moduleExportsAssignments) {
  7313. magicString.overwrite(left.start, left.end, exportsName);
  7314. }
  7315. }
  7316. function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  7317. defineCompiledEsmExpressions,
  7318. magicString,
  7319. exportMode,
  7320. moduleName,
  7321. exportsName
  7322. ) {
  7323. let isRestorableCompiledEsm = false;
  7324. for (const { node, type } of defineCompiledEsmExpressions) {
  7325. isRestorableCompiledEsm = true;
  7326. const moduleExportsExpression =
  7327. node.type === 'CallExpression' ? node.arguments[0] : node.left.object;
  7328. magicString.overwrite(
  7329. moduleExportsExpression.start,
  7330. moduleExportsExpression.end,
  7331. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  7332. );
  7333. }
  7334. return isRestorableCompiledEsm;
  7335. }
  7336. function isRequireExpression(node, scope) {
  7337. if (!node) return false;
  7338. if (node.type !== 'CallExpression') return false;
  7339. // Weird case of `require()` or `module.require()` without arguments
  7340. if (node.arguments.length === 0) return false;
  7341. return isRequire(node.callee, scope);
  7342. }
  7343. function isRequire(node, scope) {
  7344. return (
  7345. (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
  7346. (node.type === 'MemberExpression' && isModuleRequire(node, scope))
  7347. );
  7348. }
  7349. function isModuleRequire({ object, property }, scope) {
  7350. return (
  7351. object.type === 'Identifier' &&
  7352. object.name === 'module' &&
  7353. property.type === 'Identifier' &&
  7354. property.name === 'require' &&
  7355. !scope.contains('module')
  7356. );
  7357. }
  7358. function hasDynamicArguments(node) {
  7359. return (
  7360. node.arguments.length > 1 ||
  7361. (node.arguments[0].type !== 'Literal' &&
  7362. (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
  7363. );
  7364. }
  7365. const reservedMethod = { resolve: true, cache: true, main: true };
  7366. function isNodeRequirePropertyAccess(parent) {
  7367. return parent && parent.property && reservedMethod[parent.property.name];
  7368. }
  7369. function getRequireStringArg(node) {
  7370. return node.arguments[0].type === 'Literal'
  7371. ? node.arguments[0].value
  7372. : node.arguments[0].quasis[0].value.cooked;
  7373. }
  7374. function getRequireHandlers() {
  7375. const requireExpressions = [];
  7376. function addRequireExpression(
  7377. sourceId,
  7378. node,
  7379. scope,
  7380. usesReturnValue,
  7381. isInsideTryBlock,
  7382. isInsideConditional,
  7383. toBeRemoved
  7384. ) {
  7385. requireExpressions.push({
  7386. sourceId,
  7387. node,
  7388. scope,
  7389. usesReturnValue,
  7390. isInsideTryBlock,
  7391. isInsideConditional,
  7392. toBeRemoved
  7393. });
  7394. }
  7395. async function rewriteRequireExpressionsAndGetImportBlock(
  7396. magicString,
  7397. topLevelDeclarations,
  7398. reassignedNames,
  7399. helpersName,
  7400. dynamicRequireName,
  7401. moduleName,
  7402. exportsName,
  7403. id,
  7404. exportMode,
  7405. resolveRequireSourcesAndUpdateMeta,
  7406. needsRequireWrapper,
  7407. isEsModule,
  7408. isDynamicRequireModulesEnabled,
  7409. getIgnoreTryCatchRequireStatementMode,
  7410. commonjsMeta
  7411. ) {
  7412. const imports = [];
  7413. imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`);
  7414. if (dynamicRequireName) {
  7415. imports.push(
  7416. `import { ${
  7417. isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  7418. } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`
  7419. );
  7420. }
  7421. if (exportMode === 'module') {
  7422. imports.push(
  7423. `import { __module as ${moduleName} } from ${JSON.stringify(wrapId$1(id, MODULE_SUFFIX))}`,
  7424. `var ${exportsName} = ${moduleName}.exports`
  7425. );
  7426. } else if (exportMode === 'exports') {
  7427. imports.push(
  7428. `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId$1(id, EXPORTS_SUFFIX))}`
  7429. );
  7430. }
  7431. const requiresBySource = collectSources(requireExpressions);
  7432. const requireTargets = await resolveRequireSourcesAndUpdateMeta(
  7433. id,
  7434. needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
  7435. commonjsMeta,
  7436. Object.keys(requiresBySource).map((source) => {
  7437. return {
  7438. source,
  7439. isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
  7440. };
  7441. })
  7442. );
  7443. processRequireExpressions(
  7444. imports,
  7445. requireTargets,
  7446. requiresBySource,
  7447. getIgnoreTryCatchRequireStatementMode,
  7448. magicString
  7449. );
  7450. return imports.length ? `${imports.join(';\n')};\n\n` : '';
  7451. }
  7452. return {
  7453. addRequireExpression,
  7454. rewriteRequireExpressionsAndGetImportBlock
  7455. };
  7456. }
  7457. function collectSources(requireExpressions) {
  7458. const requiresBySource = Object.create(null);
  7459. for (const requireExpression of requireExpressions) {
  7460. const { sourceId } = requireExpression;
  7461. if (!requiresBySource[sourceId]) {
  7462. requiresBySource[sourceId] = [];
  7463. }
  7464. const requires = requiresBySource[sourceId];
  7465. requires.push(requireExpression);
  7466. }
  7467. return requiresBySource;
  7468. }
  7469. function processRequireExpressions(
  7470. imports,
  7471. requireTargets,
  7472. requiresBySource,
  7473. getIgnoreTryCatchRequireStatementMode,
  7474. magicString
  7475. ) {
  7476. const generateRequireName = getGenerateRequireName();
  7477. for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
  7478. const requires = requiresBySource[source];
  7479. const name = generateRequireName(requires);
  7480. let usesRequired = false;
  7481. let needsImport = false;
  7482. for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
  7483. const { canConvertRequire, shouldRemoveRequire } =
  7484. isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
  7485. ? getIgnoreTryCatchRequireStatementMode(source)
  7486. : { canConvertRequire: true, shouldRemoveRequire: false };
  7487. if (shouldRemoveRequire) {
  7488. if (usesReturnValue) {
  7489. magicString.overwrite(node.start, node.end, 'undefined');
  7490. } else {
  7491. magicString.remove(toBeRemoved.start, toBeRemoved.end);
  7492. }
  7493. } else if (canConvertRequire) {
  7494. needsImport = true;
  7495. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  7496. magicString.overwrite(node.start, node.end, `${name}()`);
  7497. } else if (usesReturnValue) {
  7498. usesRequired = true;
  7499. magicString.overwrite(node.start, node.end, name);
  7500. } else {
  7501. magicString.remove(toBeRemoved.start, toBeRemoved.end);
  7502. }
  7503. }
  7504. }
  7505. if (needsImport) {
  7506. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  7507. imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`);
  7508. } else {
  7509. imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)}`);
  7510. }
  7511. }
  7512. }
  7513. }
  7514. function getGenerateRequireName() {
  7515. let uid = 0;
  7516. return (requires) => {
  7517. let name;
  7518. const hasNameConflict = ({ scope }) => scope.contains(name);
  7519. do {
  7520. name = `require$$${uid}`;
  7521. uid += 1;
  7522. } while (requires.some(hasNameConflict));
  7523. return name;
  7524. };
  7525. }
  7526. /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
  7527. const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
  7528. const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
  7529. // There are three different types of CommonJS modules, described by their
  7530. // "exportMode":
  7531. // - exports: Only assignments to (module.)exports properties
  7532. // - replace: A single assignment to module.exports itself
  7533. // - module: Anything else
  7534. // Special cases:
  7535. // - usesRequireWrapper
  7536. // - isWrapped
  7537. async function transformCommonjs(
  7538. parse,
  7539. code,
  7540. id,
  7541. isEsModule,
  7542. ignoreGlobal,
  7543. ignoreRequire,
  7544. ignoreDynamicRequires,
  7545. getIgnoreTryCatchRequireStatementMode,
  7546. sourceMap,
  7547. isDynamicRequireModulesEnabled,
  7548. dynamicRequireModules,
  7549. commonDir,
  7550. astCache,
  7551. defaultIsModuleExports,
  7552. needsRequireWrapper,
  7553. resolveRequireSourcesAndUpdateMeta,
  7554. isRequired,
  7555. checkDynamicRequire,
  7556. commonjsMeta
  7557. ) {
  7558. const ast = astCache || tryParse(parse, code, id);
  7559. const magicString = new MagicString$1(code);
  7560. const uses = {
  7561. module: false,
  7562. exports: false,
  7563. global: false,
  7564. require: false
  7565. };
  7566. const virtualDynamicRequirePath =
  7567. isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$1(id), commonDir);
  7568. let scope = attachScopes(ast, 'scope');
  7569. let lexicalDepth = 0;
  7570. let programDepth = 0;
  7571. let currentTryBlockEnd = null;
  7572. let shouldWrap = false;
  7573. const globals = new Set();
  7574. // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
  7575. // or contains nested requires, those should be handled as function calls unless there is an
  7576. // unconditional require elsewhere.
  7577. let currentConditionalNodeEnd = null;
  7578. const conditionalNodes = new Set();
  7579. const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
  7580. // See which names are assigned to. This is necessary to prevent
  7581. // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
  7582. // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
  7583. const reassignedNames = new Set();
  7584. const topLevelDeclarations = [];
  7585. const skippedNodes = new Set();
  7586. const moduleAccessScopes = new Set([scope]);
  7587. const exportsAccessScopes = new Set([scope]);
  7588. const moduleExportsAssignments = [];
  7589. let firstTopLevelModuleExportsAssignment = null;
  7590. const exportsAssignmentsByName = new Map();
  7591. const topLevelAssignments = new Set();
  7592. const topLevelDefineCompiledEsmExpressions = [];
  7593. const replacedGlobal = [];
  7594. const replacedDynamicRequires = [];
  7595. const importedVariables = new Set();
  7596. const indentExclusionRanges = [];
  7597. walk$4(ast, {
  7598. enter(node, parent) {
  7599. if (skippedNodes.has(node)) {
  7600. this.skip();
  7601. return;
  7602. }
  7603. if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
  7604. currentTryBlockEnd = null;
  7605. }
  7606. if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
  7607. currentConditionalNodeEnd = null;
  7608. }
  7609. if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
  7610. currentConditionalNodeEnd = node.end;
  7611. }
  7612. programDepth += 1;
  7613. if (node.scope) ({ scope } = node);
  7614. if (functionType.test(node.type)) lexicalDepth += 1;
  7615. if (sourceMap) {
  7616. magicString.addSourcemapLocation(node.start);
  7617. magicString.addSourcemapLocation(node.end);
  7618. }
  7619. // eslint-disable-next-line default-case
  7620. switch (node.type) {
  7621. case 'AssignmentExpression':
  7622. if (node.left.type === 'MemberExpression') {
  7623. const flattened = getKeypath(node.left);
  7624. if (!flattened || scope.contains(flattened.name)) return;
  7625. const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
  7626. if (!exportsPatternMatch || flattened.keypath === 'exports') return;
  7627. const [, exportName] = exportsPatternMatch;
  7628. uses[flattened.name] = true;
  7629. // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
  7630. if (flattened.keypath === 'module.exports') {
  7631. moduleExportsAssignments.push(node);
  7632. if (programDepth > 3) {
  7633. moduleAccessScopes.add(scope);
  7634. } else if (!firstTopLevelModuleExportsAssignment) {
  7635. firstTopLevelModuleExportsAssignment = node;
  7636. }
  7637. } else if (exportName === KEY_COMPILED_ESM) {
  7638. if (programDepth > 3) {
  7639. shouldWrap = true;
  7640. } else {
  7641. // The "type" is either "module" or "exports" to discern
  7642. // assignments to module.exports vs exports if needed
  7643. topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name });
  7644. }
  7645. } else {
  7646. const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
  7647. nodes: [],
  7648. scopes: new Set()
  7649. };
  7650. exportsAssignments.nodes.push({ node, type: flattened.name });
  7651. exportsAssignments.scopes.add(scope);
  7652. exportsAccessScopes.add(scope);
  7653. exportsAssignmentsByName.set(exportName, exportsAssignments);
  7654. if (programDepth <= 3) {
  7655. topLevelAssignments.add(node);
  7656. }
  7657. }
  7658. skippedNodes.add(node.left);
  7659. } else {
  7660. for (const name of extractAssignedNames(node.left)) {
  7661. reassignedNames.add(name);
  7662. }
  7663. }
  7664. return;
  7665. case 'CallExpression': {
  7666. const defineCompiledEsmType = getDefineCompiledEsmType(node);
  7667. if (defineCompiledEsmType) {
  7668. if (programDepth === 3 && parent.type === 'ExpressionStatement') {
  7669. // skip special handling for [module.]exports until we know we render this
  7670. skippedNodes.add(node.arguments[0]);
  7671. topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType });
  7672. } else {
  7673. shouldWrap = true;
  7674. }
  7675. return;
  7676. }
  7677. // Transform require.resolve
  7678. if (
  7679. isDynamicRequireModulesEnabled &&
  7680. node.callee.object &&
  7681. isRequire(node.callee.object, scope) &&
  7682. node.callee.property.name === 'resolve'
  7683. ) {
  7684. checkDynamicRequire(node.start);
  7685. uses.require = true;
  7686. const requireNode = node.callee.object;
  7687. replacedDynamicRequires.push(requireNode);
  7688. skippedNodes.add(node.callee);
  7689. return;
  7690. }
  7691. if (!isRequireExpression(node, scope)) {
  7692. const keypath = getKeypath(node.callee);
  7693. if (keypath && importedVariables.has(keypath.name)) {
  7694. // Heuristic to deoptimize requires after a required function has been called
  7695. currentConditionalNodeEnd = Infinity;
  7696. }
  7697. return;
  7698. }
  7699. skippedNodes.add(node.callee);
  7700. uses.require = true;
  7701. if (hasDynamicArguments(node)) {
  7702. if (isDynamicRequireModulesEnabled) {
  7703. checkDynamicRequire(node.start);
  7704. }
  7705. if (!ignoreDynamicRequires) {
  7706. replacedDynamicRequires.push(node.callee);
  7707. }
  7708. return;
  7709. }
  7710. const requireStringArg = getRequireStringArg(node);
  7711. if (!ignoreRequire(requireStringArg)) {
  7712. const usesReturnValue = parent.type !== 'ExpressionStatement';
  7713. const toBeRemoved =
  7714. parent.type === 'ExpressionStatement' &&
  7715. (!currentConditionalNodeEnd ||
  7716. // We should completely remove requires directly in a try-catch
  7717. // so that Rollup can remove up the try-catch
  7718. (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd))
  7719. ? parent
  7720. : node;
  7721. addRequireExpression(
  7722. requireStringArg,
  7723. node,
  7724. scope,
  7725. usesReturnValue,
  7726. currentTryBlockEnd !== null,
  7727. currentConditionalNodeEnd !== null,
  7728. toBeRemoved
  7729. );
  7730. if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
  7731. for (const name of extractAssignedNames(parent.id)) {
  7732. importedVariables.add(name);
  7733. }
  7734. }
  7735. }
  7736. return;
  7737. }
  7738. case 'ConditionalExpression':
  7739. case 'IfStatement':
  7740. // skip dead branches
  7741. if (isFalsy(node.test)) {
  7742. skippedNodes.add(node.consequent);
  7743. } else if (isTruthy(node.test)) {
  7744. if (node.alternate) {
  7745. skippedNodes.add(node.alternate);
  7746. }
  7747. } else {
  7748. conditionalNodes.add(node.consequent);
  7749. if (node.alternate) {
  7750. conditionalNodes.add(node.alternate);
  7751. }
  7752. }
  7753. return;
  7754. case 'ArrowFunctionExpression':
  7755. case 'FunctionDeclaration':
  7756. case 'FunctionExpression':
  7757. // requires in functions should be conditional unless it is an IIFE
  7758. if (
  7759. currentConditionalNodeEnd === null &&
  7760. !(parent.type === 'CallExpression' && parent.callee === node)
  7761. ) {
  7762. currentConditionalNodeEnd = node.end;
  7763. }
  7764. return;
  7765. case 'Identifier': {
  7766. const { name } = node;
  7767. if (!isReference(node, parent) || scope.contains(name)) return;
  7768. switch (name) {
  7769. case 'require':
  7770. uses.require = true;
  7771. if (isNodeRequirePropertyAccess(parent)) {
  7772. return;
  7773. }
  7774. if (!ignoreDynamicRequires) {
  7775. if (isShorthandProperty(parent)) {
  7776. magicString.prependRight(node.start, 'require: ');
  7777. }
  7778. replacedDynamicRequires.push(node);
  7779. }
  7780. return;
  7781. case 'module':
  7782. case 'exports':
  7783. shouldWrap = true;
  7784. uses[name] = true;
  7785. return;
  7786. case 'global':
  7787. uses.global = true;
  7788. if (!ignoreGlobal) {
  7789. replacedGlobal.push(node);
  7790. }
  7791. return;
  7792. case 'define':
  7793. magicString.overwrite(node.start, node.end, 'undefined', {
  7794. storeName: true
  7795. });
  7796. return;
  7797. default:
  7798. globals.add(name);
  7799. return;
  7800. }
  7801. }
  7802. case 'LogicalExpression':
  7803. // skip dead branches
  7804. if (node.operator === '&&') {
  7805. if (isFalsy(node.left)) {
  7806. skippedNodes.add(node.right);
  7807. } else if (!isTruthy(node.left)) {
  7808. conditionalNodes.add(node.right);
  7809. }
  7810. } else if (node.operator === '||') {
  7811. if (isTruthy(node.left)) {
  7812. skippedNodes.add(node.right);
  7813. } else if (!isFalsy(node.left)) {
  7814. conditionalNodes.add(node.right);
  7815. }
  7816. }
  7817. return;
  7818. case 'MemberExpression':
  7819. if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
  7820. uses.require = true;
  7821. replacedDynamicRequires.push(node);
  7822. skippedNodes.add(node.object);
  7823. skippedNodes.add(node.property);
  7824. }
  7825. return;
  7826. case 'ReturnStatement':
  7827. // if top-level return, we need to wrap it
  7828. if (lexicalDepth === 0) {
  7829. shouldWrap = true;
  7830. }
  7831. return;
  7832. case 'ThisExpression':
  7833. // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
  7834. if (lexicalDepth === 0) {
  7835. uses.global = true;
  7836. if (!ignoreGlobal) {
  7837. replacedGlobal.push(node);
  7838. }
  7839. }
  7840. return;
  7841. case 'TryStatement':
  7842. if (currentTryBlockEnd === null) {
  7843. currentTryBlockEnd = node.block.end;
  7844. }
  7845. if (currentConditionalNodeEnd === null) {
  7846. currentConditionalNodeEnd = node.end;
  7847. }
  7848. return;
  7849. case 'UnaryExpression':
  7850. // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
  7851. if (node.operator === 'typeof') {
  7852. const flattened = getKeypath(node.argument);
  7853. if (!flattened) return;
  7854. if (scope.contains(flattened.name)) return;
  7855. if (
  7856. !isEsModule &&
  7857. (flattened.keypath === 'module.exports' ||
  7858. flattened.keypath === 'module' ||
  7859. flattened.keypath === 'exports')
  7860. ) {
  7861. magicString.overwrite(node.start, node.end, `'object'`, {
  7862. storeName: false
  7863. });
  7864. }
  7865. }
  7866. return;
  7867. case 'VariableDeclaration':
  7868. if (!scope.parent) {
  7869. topLevelDeclarations.push(node);
  7870. }
  7871. return;
  7872. case 'TemplateElement':
  7873. if (node.value.raw.includes('\n')) {
  7874. indentExclusionRanges.push([node.start, node.end]);
  7875. }
  7876. }
  7877. },
  7878. leave(node) {
  7879. programDepth -= 1;
  7880. if (node.scope) scope = scope.parent;
  7881. if (functionType.test(node.type)) lexicalDepth -= 1;
  7882. }
  7883. });
  7884. const nameBase = getName(id);
  7885. const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
  7886. const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
  7887. const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
  7888. const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
  7889. const helpersName = deconflict([scope], globals, 'commonjsHelpers');
  7890. const dynamicRequireName =
  7891. replacedDynamicRequires.length > 0 &&
  7892. deconflict(
  7893. [scope],
  7894. globals,
  7895. isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  7896. );
  7897. const deconflictedExportNames = Object.create(null);
  7898. for (const [exportName, { scopes }] of exportsAssignmentsByName) {
  7899. deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
  7900. }
  7901. for (const node of replacedGlobal) {
  7902. magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
  7903. storeName: true
  7904. });
  7905. }
  7906. for (const node of replacedDynamicRequires) {
  7907. magicString.overwrite(
  7908. node.start,
  7909. node.end,
  7910. isDynamicRequireModulesEnabled
  7911. ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
  7912. : dynamicRequireName,
  7913. {
  7914. contentOnly: true,
  7915. storeName: true
  7916. }
  7917. );
  7918. }
  7919. // We cannot wrap ES/mixed modules
  7920. shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
  7921. if (
  7922. !(
  7923. shouldWrap ||
  7924. isRequired ||
  7925. needsRequireWrapper ||
  7926. uses.module ||
  7927. uses.exports ||
  7928. uses.require ||
  7929. topLevelDefineCompiledEsmExpressions.length > 0
  7930. ) &&
  7931. (ignoreGlobal || !uses.global)
  7932. ) {
  7933. return { meta: { commonjs: { isCommonJS: false } } };
  7934. }
  7935. let leadingComment = '';
  7936. if (code.startsWith('/*')) {
  7937. const commentEnd = code.indexOf('*/', 2) + 2;
  7938. leadingComment = `${code.slice(0, commentEnd)}\n`;
  7939. magicString.remove(0, commentEnd).trim();
  7940. }
  7941. const exportMode = isEsModule
  7942. ? 'none'
  7943. : shouldWrap
  7944. ? uses.module
  7945. ? 'module'
  7946. : 'exports'
  7947. : firstTopLevelModuleExportsAssignment
  7948. ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
  7949. ? 'replace'
  7950. : 'module'
  7951. : moduleExportsAssignments.length === 0
  7952. ? 'exports'
  7953. : 'module';
  7954. const exportedExportsName =
  7955. exportMode === 'module' ? deconflict([], globals, `${nameBase}Exports`) : exportsName;
  7956. const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
  7957. magicString,
  7958. topLevelDeclarations,
  7959. reassignedNames,
  7960. helpersName,
  7961. dynamicRequireName,
  7962. moduleName,
  7963. exportsName,
  7964. id,
  7965. exportMode,
  7966. resolveRequireSourcesAndUpdateMeta,
  7967. needsRequireWrapper,
  7968. isEsModule,
  7969. isDynamicRequireModulesEnabled,
  7970. getIgnoreTryCatchRequireStatementMode,
  7971. commonjsMeta
  7972. );
  7973. const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
  7974. const exportBlock = isEsModule
  7975. ? ''
  7976. : rewriteExportsAndGetExportsBlock(
  7977. magicString,
  7978. moduleName,
  7979. exportsName,
  7980. exportedExportsName,
  7981. shouldWrap,
  7982. moduleExportsAssignments,
  7983. firstTopLevelModuleExportsAssignment,
  7984. exportsAssignmentsByName,
  7985. topLevelAssignments,
  7986. topLevelDefineCompiledEsmExpressions,
  7987. deconflictedExportNames,
  7988. code,
  7989. helpersName,
  7990. exportMode,
  7991. defaultIsModuleExports,
  7992. usesRequireWrapper,
  7993. requireName
  7994. );
  7995. if (shouldWrap) {
  7996. wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
  7997. }
  7998. if (usesRequireWrapper) {
  7999. magicString.trim().indent('\t', {
  8000. exclude: indentExclusionRanges
  8001. });
  8002. const exported = exportMode === 'module' ? `${moduleName}.exports` : exportsName;
  8003. magicString.prepend(
  8004. `var ${isRequiredName};
  8005. function ${requireName} () {
  8006. \tif (${isRequiredName}) return ${exported};
  8007. \t${isRequiredName} = 1;
  8008. `
  8009. ).append(`
  8010. \treturn ${exported};
  8011. }`);
  8012. if (exportMode === 'replace') {
  8013. magicString.prepend(`var ${exportsName};\n`);
  8014. }
  8015. }
  8016. magicString
  8017. .trim()
  8018. .prepend(leadingComment + importBlock)
  8019. .append(exportBlock);
  8020. return {
  8021. code: magicString.toString(),
  8022. map: sourceMap ? magicString.generateMap() : null,
  8023. syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
  8024. meta: { commonjs: commonjsMeta }
  8025. };
  8026. }
  8027. const PLUGIN_NAME = 'commonjs';
  8028. function commonjs(options = {}) {
  8029. const {
  8030. ignoreGlobal,
  8031. ignoreDynamicRequires,
  8032. requireReturnsDefault: requireReturnsDefaultOption,
  8033. defaultIsModuleExports: defaultIsModuleExportsOption,
  8034. esmExternals
  8035. } = options;
  8036. const extensions = options.extensions || ['.js'];
  8037. const filter = createFilter$1(options.include, options.exclude);
  8038. const isPossibleCjsId = (id) => {
  8039. const extName = extname(id);
  8040. return extName === '.cjs' || (extensions.includes(extName) && filter(id));
  8041. };
  8042. const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
  8043. const getRequireReturnsDefault =
  8044. typeof requireReturnsDefaultOption === 'function'
  8045. ? requireReturnsDefaultOption
  8046. : () => requireReturnsDefaultOption;
  8047. let esmExternalIds;
  8048. const isEsmExternal =
  8049. typeof esmExternals === 'function'
  8050. ? esmExternals
  8051. : Array.isArray(esmExternals)
  8052. ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
  8053. : () => esmExternals;
  8054. const getDefaultIsModuleExports =
  8055. typeof defaultIsModuleExportsOption === 'function'
  8056. ? defaultIsModuleExportsOption
  8057. : () =>
  8058. typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
  8059. const dynamicRequireRoot =
  8060. typeof options.dynamicRequireRoot === 'string'
  8061. ? resolve$3(options.dynamicRequireRoot)
  8062. : process.cwd();
  8063. const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
  8064. options.dynamicRequireTargets,
  8065. dynamicRequireRoot
  8066. );
  8067. const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
  8068. const ignoreRequire =
  8069. typeof options.ignore === 'function'
  8070. ? options.ignore
  8071. : Array.isArray(options.ignore)
  8072. ? (id) => options.ignore.includes(id)
  8073. : () => false;
  8074. const getIgnoreTryCatchRequireStatementMode = (id) => {
  8075. const mode =
  8076. typeof options.ignoreTryCatch === 'function'
  8077. ? options.ignoreTryCatch(id)
  8078. : Array.isArray(options.ignoreTryCatch)
  8079. ? options.ignoreTryCatch.includes(id)
  8080. : typeof options.ignoreTryCatch !== 'undefined'
  8081. ? options.ignoreTryCatch
  8082. : true;
  8083. return {
  8084. canConvertRequire: mode !== 'remove' && mode !== true,
  8085. shouldRemoveRequire: mode === 'remove'
  8086. };
  8087. };
  8088. const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId);
  8089. const sourceMap = options.sourceMap !== false;
  8090. // Initialized in buildStart
  8091. let requireResolver;
  8092. function transformAndCheckExports(code, id) {
  8093. const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
  8094. this.parse,
  8095. code,
  8096. id
  8097. );
  8098. const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
  8099. if (hasDefaultExport) {
  8100. commonjsMeta.hasDefaultExport = true;
  8101. }
  8102. if (hasNamedExports) {
  8103. commonjsMeta.hasNamedExports = true;
  8104. }
  8105. if (
  8106. !dynamicRequireModules.has(normalizePathSlashes(id)) &&
  8107. (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
  8108. (isEsModule && !options.transformMixedEsModules))
  8109. ) {
  8110. commonjsMeta.isCommonJS = false;
  8111. return { meta: { commonjs: commonjsMeta } };
  8112. }
  8113. const needsRequireWrapper =
  8114. !isEsModule &&
  8115. (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
  8116. const checkDynamicRequire = (position) => {
  8117. if (id.indexOf(dynamicRequireRoot) !== 0) {
  8118. this.error(
  8119. {
  8120. code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
  8121. id,
  8122. dynamicRequireRoot,
  8123. message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1(
  8124. id
  8125. )}" or one of its parent directories.`
  8126. },
  8127. position
  8128. );
  8129. }
  8130. };
  8131. return transformCommonjs(
  8132. this.parse,
  8133. code,
  8134. id,
  8135. isEsModule,
  8136. ignoreGlobal || isEsModule,
  8137. ignoreRequire,
  8138. ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
  8139. getIgnoreTryCatchRequireStatementMode,
  8140. sourceMap,
  8141. isDynamicRequireModulesEnabled,
  8142. dynamicRequireModules,
  8143. commonDir,
  8144. ast,
  8145. getDefaultIsModuleExports(id),
  8146. needsRequireWrapper,
  8147. requireResolver.resolveRequireSourcesAndUpdateMeta(this),
  8148. requireResolver.isRequiredId(id),
  8149. checkDynamicRequire,
  8150. commonjsMeta
  8151. );
  8152. }
  8153. return {
  8154. name: PLUGIN_NAME,
  8155. version: version$3,
  8156. options(rawOptions) {
  8157. // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
  8158. // do not prevent our plugin from resolving entry points ot proxies.
  8159. const plugins = Array.isArray(rawOptions.plugins)
  8160. ? [...rawOptions.plugins]
  8161. : rawOptions.plugins
  8162. ? [rawOptions.plugins]
  8163. : [];
  8164. plugins.unshift({
  8165. name: 'commonjs--resolver',
  8166. resolveId
  8167. });
  8168. return { ...rawOptions, plugins };
  8169. },
  8170. buildStart({ plugins }) {
  8171. validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
  8172. const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
  8173. if (nodeResolve) {
  8174. validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
  8175. }
  8176. if (options.namedExports != null) {
  8177. this.warn(
  8178. 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
  8179. );
  8180. }
  8181. requireResolver = getRequireResolver(
  8182. extensions,
  8183. detectCyclesAndConditional,
  8184. currentlyResolving
  8185. );
  8186. },
  8187. buildEnd() {
  8188. if (options.strictRequires === 'debug') {
  8189. const wrappedIds = requireResolver.getWrappedIds();
  8190. if (wrappedIds.length) {
  8191. this.warn({
  8192. code: 'WRAPPED_IDS',
  8193. ids: wrappedIds,
  8194. message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
  8195. .map((id) => `\t${JSON.stringify(relative$1(process.cwd(), id))}`)
  8196. .join(',\n')}\n]`
  8197. });
  8198. } else {
  8199. this.warn({
  8200. code: 'WRAPPED_IDS',
  8201. ids: wrappedIds,
  8202. message: 'The commonjs plugin did not wrap any files.'
  8203. });
  8204. }
  8205. }
  8206. },
  8207. load(id) {
  8208. if (id === HELPERS_ID) {
  8209. return getHelpersModule();
  8210. }
  8211. if (isWrappedId(id, MODULE_SUFFIX)) {
  8212. const name = getName(unwrapId$1(id, MODULE_SUFFIX));
  8213. return {
  8214. code: `var ${name} = {exports: {}}; export {${name} as __module}`,
  8215. meta: { commonjs: { isCommonJS: false } }
  8216. };
  8217. }
  8218. if (isWrappedId(id, EXPORTS_SUFFIX)) {
  8219. const name = getName(unwrapId$1(id, EXPORTS_SUFFIX));
  8220. return {
  8221. code: `var ${name} = {}; export {${name} as __exports}`,
  8222. meta: { commonjs: { isCommonJS: false } }
  8223. };
  8224. }
  8225. if (isWrappedId(id, EXTERNAL_SUFFIX)) {
  8226. const actualId = unwrapId$1(id, EXTERNAL_SUFFIX);
  8227. return getUnknownRequireProxy(
  8228. actualId,
  8229. isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
  8230. );
  8231. }
  8232. // entry suffix is just appended to not mess up relative external resolution
  8233. if (id.endsWith(ENTRY_SUFFIX)) {
  8234. const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
  8235. return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo);
  8236. }
  8237. if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
  8238. const actualId = unwrapId$1(id, ES_IMPORT_SUFFIX);
  8239. return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId));
  8240. }
  8241. if (id === DYNAMIC_MODULES_ID) {
  8242. return getDynamicModuleRegistry(
  8243. isDynamicRequireModulesEnabled,
  8244. dynamicRequireModules,
  8245. commonDir,
  8246. ignoreDynamicRequires
  8247. );
  8248. }
  8249. if (isWrappedId(id, PROXY_SUFFIX)) {
  8250. const actualId = unwrapId$1(id, PROXY_SUFFIX);
  8251. return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
  8252. }
  8253. return null;
  8254. },
  8255. shouldTransformCachedModule(...args) {
  8256. return requireResolver.shouldTransformCachedModule.call(this, ...args);
  8257. },
  8258. transform(code, id) {
  8259. if (!isPossibleCjsId(id)) return null;
  8260. try {
  8261. return transformAndCheckExports.call(this, code, id);
  8262. } catch (err) {
  8263. return this.error(err, err.loc);
  8264. }
  8265. }
  8266. };
  8267. }
  8268. // Matches the scheme of a URL, eg "http://"
  8269. const schemeRegex = /^[\w+.-]+:\/\//;
  8270. /**
  8271. * Matches the parts of a URL:
  8272. * 1. Scheme, including ":", guaranteed.
  8273. * 2. User/password, including "@", optional.
  8274. * 3. Host, guaranteed.
  8275. * 4. Port, including ":", optional.
  8276. * 5. Path, including "/", optional.
  8277. * 6. Query, including "?", optional.
  8278. * 7. Hash, including "#", optional.
  8279. */
  8280. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  8281. /**
  8282. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  8283. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  8284. *
  8285. * 1. Host, optional.
  8286. * 2. Path, which may include "/", guaranteed.
  8287. * 3. Query, including "?", optional.
  8288. * 4. Hash, including "#", optional.
  8289. */
  8290. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  8291. var UrlType;
  8292. (function (UrlType) {
  8293. UrlType[UrlType["Empty"] = 1] = "Empty";
  8294. UrlType[UrlType["Hash"] = 2] = "Hash";
  8295. UrlType[UrlType["Query"] = 3] = "Query";
  8296. UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
  8297. UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
  8298. UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
  8299. UrlType[UrlType["Absolute"] = 7] = "Absolute";
  8300. })(UrlType || (UrlType = {}));
  8301. function isAbsoluteUrl(input) {
  8302. return schemeRegex.test(input);
  8303. }
  8304. function isSchemeRelativeUrl(input) {
  8305. return input.startsWith('//');
  8306. }
  8307. function isAbsolutePath(input) {
  8308. return input.startsWith('/');
  8309. }
  8310. function isFileUrl(input) {
  8311. return input.startsWith('file:');
  8312. }
  8313. function isRelative(input) {
  8314. return /^[.?#]/.test(input);
  8315. }
  8316. function parseAbsoluteUrl(input) {
  8317. const match = urlRegex.exec(input);
  8318. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
  8319. }
  8320. function parseFileUrl(input) {
  8321. const match = fileRegex.exec(input);
  8322. const path = match[2];
  8323. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
  8324. }
  8325. function makeUrl(scheme, user, host, port, path, query, hash) {
  8326. return {
  8327. scheme,
  8328. user,
  8329. host,
  8330. port,
  8331. path,
  8332. query,
  8333. hash,
  8334. type: UrlType.Absolute,
  8335. };
  8336. }
  8337. function parseUrl$2(input) {
  8338. if (isSchemeRelativeUrl(input)) {
  8339. const url = parseAbsoluteUrl('http:' + input);
  8340. url.scheme = '';
  8341. url.type = UrlType.SchemeRelative;
  8342. return url;
  8343. }
  8344. if (isAbsolutePath(input)) {
  8345. const url = parseAbsoluteUrl('http://foo.com' + input);
  8346. url.scheme = '';
  8347. url.host = '';
  8348. url.type = UrlType.AbsolutePath;
  8349. return url;
  8350. }
  8351. if (isFileUrl(input))
  8352. return parseFileUrl(input);
  8353. if (isAbsoluteUrl(input))
  8354. return parseAbsoluteUrl(input);
  8355. const url = parseAbsoluteUrl('http://foo.com/' + input);
  8356. url.scheme = '';
  8357. url.host = '';
  8358. url.type = input
  8359. ? input.startsWith('?')
  8360. ? UrlType.Query
  8361. : input.startsWith('#')
  8362. ? UrlType.Hash
  8363. : UrlType.RelativePath
  8364. : UrlType.Empty;
  8365. return url;
  8366. }
  8367. function stripPathFilename(path) {
  8368. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  8369. // paths. It's not a file, so we can't strip it.
  8370. if (path.endsWith('/..'))
  8371. return path;
  8372. const index = path.lastIndexOf('/');
  8373. return path.slice(0, index + 1);
  8374. }
  8375. function mergePaths(url, base) {
  8376. normalizePath$4(base, base.type);
  8377. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  8378. // path).
  8379. if (url.path === '/') {
  8380. url.path = base.path;
  8381. }
  8382. else {
  8383. // Resolution happens relative to the base path's directory, not the file.
  8384. url.path = stripPathFilename(base.path) + url.path;
  8385. }
  8386. }
  8387. /**
  8388. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  8389. * "foo/.". We need to normalize to a standard representation.
  8390. */
  8391. function normalizePath$4(url, type) {
  8392. const rel = type <= UrlType.RelativePath;
  8393. const pieces = url.path.split('/');
  8394. // We need to preserve the first piece always, so that we output a leading slash. The item at
  8395. // pieces[0] is an empty string.
  8396. let pointer = 1;
  8397. // Positive is the number of real directories we've output, used for popping a parent directory.
  8398. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  8399. let positive = 0;
  8400. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  8401. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  8402. // real directory, we won't need to append, unless the other conditions happen again.
  8403. let addTrailingSlash = false;
  8404. for (let i = 1; i < pieces.length; i++) {
  8405. const piece = pieces[i];
  8406. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  8407. if (!piece) {
  8408. addTrailingSlash = true;
  8409. continue;
  8410. }
  8411. // If we encounter a real directory, then we don't need to append anymore.
  8412. addTrailingSlash = false;
  8413. // A current directory, which we can always drop.
  8414. if (piece === '.')
  8415. continue;
  8416. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  8417. // have an excess of parents, and we'll need to keep the "..".
  8418. if (piece === '..') {
  8419. if (positive) {
  8420. addTrailingSlash = true;
  8421. positive--;
  8422. pointer--;
  8423. }
  8424. else if (rel) {
  8425. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  8426. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  8427. pieces[pointer++] = piece;
  8428. }
  8429. continue;
  8430. }
  8431. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  8432. // any popped or dropped directories.
  8433. pieces[pointer++] = piece;
  8434. positive++;
  8435. }
  8436. let path = '';
  8437. for (let i = 1; i < pointer; i++) {
  8438. path += '/' + pieces[i];
  8439. }
  8440. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  8441. path += '/';
  8442. }
  8443. url.path = path;
  8444. }
  8445. /**
  8446. * Attempts to resolve `input` URL/path relative to `base`.
  8447. */
  8448. function resolve$2(input, base) {
  8449. if (!input && !base)
  8450. return '';
  8451. const url = parseUrl$2(input);
  8452. let inputType = url.type;
  8453. if (base && inputType !== UrlType.Absolute) {
  8454. const baseUrl = parseUrl$2(base);
  8455. const baseType = baseUrl.type;
  8456. switch (inputType) {
  8457. case UrlType.Empty:
  8458. url.hash = baseUrl.hash;
  8459. // fall through
  8460. case UrlType.Hash:
  8461. url.query = baseUrl.query;
  8462. // fall through
  8463. case UrlType.Query:
  8464. case UrlType.RelativePath:
  8465. mergePaths(url, baseUrl);
  8466. // fall through
  8467. case UrlType.AbsolutePath:
  8468. // The host, user, and port are joined, you can't copy one without the others.
  8469. url.user = baseUrl.user;
  8470. url.host = baseUrl.host;
  8471. url.port = baseUrl.port;
  8472. // fall through
  8473. case UrlType.SchemeRelative:
  8474. // The input doesn't have a schema at least, so we need to copy at least that over.
  8475. url.scheme = baseUrl.scheme;
  8476. }
  8477. if (baseType > inputType)
  8478. inputType = baseType;
  8479. }
  8480. normalizePath$4(url, inputType);
  8481. const queryHash = url.query + url.hash;
  8482. switch (inputType) {
  8483. // This is impossible, because of the empty checks at the start of the function.
  8484. // case UrlType.Empty:
  8485. case UrlType.Hash:
  8486. case UrlType.Query:
  8487. return queryHash;
  8488. case UrlType.RelativePath: {
  8489. // The first char is always a "/", and we need it to be relative.
  8490. const path = url.path.slice(1);
  8491. if (!path)
  8492. return queryHash || '.';
  8493. if (isRelative(base || input) && !isRelative(path)) {
  8494. // If base started with a leading ".", or there is no base and input started with a ".",
  8495. // then we need to ensure that the relative path starts with a ".". We don't know if
  8496. // relative starts with a "..", though, so check before prepending.
  8497. return './' + path + queryHash;
  8498. }
  8499. return path + queryHash;
  8500. }
  8501. case UrlType.AbsolutePath:
  8502. return url.path + queryHash;
  8503. default:
  8504. return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
  8505. }
  8506. }
  8507. function resolve$1(input, base) {
  8508. // The base is always treated as a directory, if it's not empty.
  8509. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  8510. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  8511. if (base && !base.endsWith('/'))
  8512. base += '/';
  8513. return resolve$2(input, base);
  8514. }
  8515. /**
  8516. * Removes everything after the last "/", but leaves the slash.
  8517. */
  8518. function stripFilename(path) {
  8519. if (!path)
  8520. return '';
  8521. const index = path.lastIndexOf('/');
  8522. return path.slice(0, index + 1);
  8523. }
  8524. const COLUMN$1 = 0;
  8525. const SOURCES_INDEX$1 = 1;
  8526. const SOURCE_LINE$1 = 2;
  8527. const SOURCE_COLUMN$1 = 3;
  8528. const NAMES_INDEX$1 = 4;
  8529. function maybeSort(mappings, owned) {
  8530. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  8531. if (unsortedIndex === mappings.length)
  8532. return mappings;
  8533. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  8534. // not, we do not want to modify the consumer's input array.
  8535. if (!owned)
  8536. mappings = mappings.slice();
  8537. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  8538. mappings[i] = sortSegments(mappings[i], owned);
  8539. }
  8540. return mappings;
  8541. }
  8542. function nextUnsortedSegmentLine(mappings, start) {
  8543. for (let i = start; i < mappings.length; i++) {
  8544. if (!isSorted(mappings[i]))
  8545. return i;
  8546. }
  8547. return mappings.length;
  8548. }
  8549. function isSorted(line) {
  8550. for (let j = 1; j < line.length; j++) {
  8551. if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
  8552. return false;
  8553. }
  8554. }
  8555. return true;
  8556. }
  8557. function sortSegments(line, owned) {
  8558. if (!owned)
  8559. line = line.slice();
  8560. return line.sort(sortComparator);
  8561. }
  8562. function sortComparator(a, b) {
  8563. return a[COLUMN$1] - b[COLUMN$1];
  8564. }
  8565. let found = false;
  8566. /**
  8567. * A binary search implementation that returns the index if a match is found.
  8568. * If no match is found, then the left-index (the index associated with the item that comes just
  8569. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  8570. * the next index:
  8571. *
  8572. * ```js
  8573. * const array = [1, 3];
  8574. * const needle = 2;
  8575. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  8576. *
  8577. * assert.equal(index, 0);
  8578. * array.splice(index + 1, 0, needle);
  8579. * assert.deepEqual(array, [1, 2, 3]);
  8580. * ```
  8581. */
  8582. function binarySearch(haystack, needle, low, high) {
  8583. while (low <= high) {
  8584. const mid = low + ((high - low) >> 1);
  8585. const cmp = haystack[mid][COLUMN$1] - needle;
  8586. if (cmp === 0) {
  8587. found = true;
  8588. return mid;
  8589. }
  8590. if (cmp < 0) {
  8591. low = mid + 1;
  8592. }
  8593. else {
  8594. high = mid - 1;
  8595. }
  8596. }
  8597. found = false;
  8598. return low - 1;
  8599. }
  8600. function upperBound(haystack, needle, index) {
  8601. for (let i = index + 1; i < haystack.length; index = i++) {
  8602. if (haystack[i][COLUMN$1] !== needle)
  8603. break;
  8604. }
  8605. return index;
  8606. }
  8607. function lowerBound(haystack, needle, index) {
  8608. for (let i = index - 1; i >= 0; index = i--) {
  8609. if (haystack[i][COLUMN$1] !== needle)
  8610. break;
  8611. }
  8612. return index;
  8613. }
  8614. function memoizedState() {
  8615. return {
  8616. lastKey: -1,
  8617. lastNeedle: -1,
  8618. lastIndex: -1,
  8619. };
  8620. }
  8621. /**
  8622. * This overly complicated beast is just to record the last tested line/column and the resulting
  8623. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  8624. */
  8625. function memoizedBinarySearch(haystack, needle, state, key) {
  8626. const { lastKey, lastNeedle, lastIndex } = state;
  8627. let low = 0;
  8628. let high = haystack.length - 1;
  8629. if (key === lastKey) {
  8630. if (needle === lastNeedle) {
  8631. found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
  8632. return lastIndex;
  8633. }
  8634. if (needle >= lastNeedle) {
  8635. // lastIndex may be -1 if the previous needle was not found.
  8636. low = lastIndex === -1 ? 0 : lastIndex;
  8637. }
  8638. else {
  8639. high = lastIndex;
  8640. }
  8641. }
  8642. state.lastKey = key;
  8643. state.lastNeedle = needle;
  8644. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  8645. }
  8646. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  8647. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  8648. const LEAST_UPPER_BOUND = -1;
  8649. const GREATEST_LOWER_BOUND = 1;
  8650. /**
  8651. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  8652. */
  8653. let decodedMappings;
  8654. /**
  8655. * A low-level API to find the segment associated with a generated line/column (think, from a
  8656. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  8657. */
  8658. let traceSegment;
  8659. /**
  8660. * A higher-level API to find the source/line/column associated with a generated line/column
  8661. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  8662. * `source-map` library.
  8663. */
  8664. let originalPositionFor$1;
  8665. class TraceMap {
  8666. constructor(map, mapUrl) {
  8667. const isString = typeof map === 'string';
  8668. if (!isString && map._decodedMemo)
  8669. return map;
  8670. const parsed = (isString ? JSON.parse(map) : map);
  8671. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  8672. this.version = version;
  8673. this.file = file;
  8674. this.names = names;
  8675. this.sourceRoot = sourceRoot;
  8676. this.sources = sources;
  8677. this.sourcesContent = sourcesContent;
  8678. const from = resolve$1(sourceRoot || '', stripFilename(mapUrl));
  8679. this.resolvedSources = sources.map((s) => resolve$1(s || '', from));
  8680. const { mappings } = parsed;
  8681. if (typeof mappings === 'string') {
  8682. this._encoded = mappings;
  8683. this._decoded = undefined;
  8684. }
  8685. else {
  8686. this._encoded = undefined;
  8687. this._decoded = maybeSort(mappings, isString);
  8688. }
  8689. this._decodedMemo = memoizedState();
  8690. this._bySources = undefined;
  8691. this._bySourceMemos = undefined;
  8692. }
  8693. }
  8694. (() => {
  8695. decodedMappings = (map) => {
  8696. return (map._decoded || (map._decoded = decode(map._encoded)));
  8697. };
  8698. traceSegment = (map, line, column) => {
  8699. const decoded = decodedMappings(map);
  8700. // It's common for parent source maps to have pointers to lines that have no
  8701. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  8702. if (line >= decoded.length)
  8703. return null;
  8704. const segments = decoded[line];
  8705. const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  8706. return index === -1 ? null : segments[index];
  8707. };
  8708. originalPositionFor$1 = (map, { line, column, bias }) => {
  8709. line--;
  8710. if (line < 0)
  8711. throw new Error(LINE_GTR_ZERO);
  8712. if (column < 0)
  8713. throw new Error(COL_GTR_EQ_ZERO);
  8714. const decoded = decodedMappings(map);
  8715. // It's common for parent source maps to have pointers to lines that have no
  8716. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  8717. if (line >= decoded.length)
  8718. return OMapping(null, null, null, null);
  8719. const segments = decoded[line];
  8720. const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  8721. if (index === -1)
  8722. return OMapping(null, null, null, null);
  8723. const segment = segments[index];
  8724. if (segment.length === 1)
  8725. return OMapping(null, null, null, null);
  8726. const { names, resolvedSources } = map;
  8727. return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null);
  8728. };
  8729. })();
  8730. function OMapping(source, line, column, name) {
  8731. return { source, line, column, name };
  8732. }
  8733. function traceSegmentInternal(segments, memo, line, column, bias) {
  8734. let index = memoizedBinarySearch(segments, column, memo, line);
  8735. if (found) {
  8736. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  8737. }
  8738. else if (bias === LEAST_UPPER_BOUND)
  8739. index++;
  8740. if (index === -1 || index === segments.length)
  8741. return -1;
  8742. return index;
  8743. }
  8744. /**
  8745. * Gets the index associated with `key` in the backing array, if it is already present.
  8746. */
  8747. let get;
  8748. /**
  8749. * Puts `key` into the backing array, if it is not already present. Returns
  8750. * the index of the `key` in the backing array.
  8751. */
  8752. let put;
  8753. /**
  8754. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  8755. * index of the `key` in the backing array.
  8756. *
  8757. * This is designed to allow synchronizing a second array with the contents of the backing array,
  8758. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  8759. * and there are never duplicates.
  8760. */
  8761. class SetArray {
  8762. constructor() {
  8763. this._indexes = { __proto__: null };
  8764. this.array = [];
  8765. }
  8766. }
  8767. (() => {
  8768. get = (strarr, key) => strarr._indexes[key];
  8769. put = (strarr, key) => {
  8770. // The key may or may not be present. If it is present, it's a number.
  8771. const index = get(strarr, key);
  8772. if (index !== undefined)
  8773. return index;
  8774. const { array, _indexes: indexes } = strarr;
  8775. return (indexes[key] = array.push(key) - 1);
  8776. };
  8777. })();
  8778. const COLUMN = 0;
  8779. const SOURCES_INDEX = 1;
  8780. const SOURCE_LINE = 2;
  8781. const SOURCE_COLUMN = 3;
  8782. const NAMES_INDEX = 4;
  8783. const NO_NAME = -1;
  8784. /**
  8785. * Same as `addSegment`, but will only add the segment if it generates useful information in the
  8786. * resulting map. This only works correctly if segments are added **in order**, meaning you should
  8787. * not add a segment with a lower generated line/column than one that came before.
  8788. */
  8789. let maybeAddSegment;
  8790. /**
  8791. * Adds/removes the content of the source file to the source map.
  8792. */
  8793. let setSourceContent;
  8794. /**
  8795. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  8796. * a sourcemap, or to JSON.stringify.
  8797. */
  8798. let toDecodedMap;
  8799. /**
  8800. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  8801. * a sourcemap, or to JSON.stringify.
  8802. */
  8803. let toEncodedMap;
  8804. // This split declaration is only so that terser can elminiate the static initialization block.
  8805. let addSegmentInternal;
  8806. /**
  8807. * Provides the state to generate a sourcemap.
  8808. */
  8809. class GenMapping {
  8810. constructor({ file, sourceRoot } = {}) {
  8811. this._names = new SetArray();
  8812. this._sources = new SetArray();
  8813. this._sourcesContent = [];
  8814. this._mappings = [];
  8815. this.file = file;
  8816. this.sourceRoot = sourceRoot;
  8817. }
  8818. }
  8819. (() => {
  8820. maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  8821. return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
  8822. };
  8823. setSourceContent = (map, source, content) => {
  8824. const { _sources: sources, _sourcesContent: sourcesContent } = map;
  8825. sourcesContent[put(sources, source)] = content;
  8826. };
  8827. toDecodedMap = (map) => {
  8828. const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  8829. removeEmptyFinalLines(mappings);
  8830. return {
  8831. version: 3,
  8832. file: file || undefined,
  8833. names: names.array,
  8834. sourceRoot: sourceRoot || undefined,
  8835. sources: sources.array,
  8836. sourcesContent,
  8837. mappings,
  8838. };
  8839. };
  8840. toEncodedMap = (map) => {
  8841. const decoded = toDecodedMap(map);
  8842. return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) });
  8843. };
  8844. // Internal helpers
  8845. addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  8846. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  8847. const line = getLine(mappings, genLine);
  8848. const index = getColumnIndex(line, genColumn);
  8849. if (!source) {
  8850. if (skipable && skipSourceless(line, index))
  8851. return;
  8852. return insert(line, index, [genColumn]);
  8853. }
  8854. const sourcesIndex = put(sources, source);
  8855. const namesIndex = name ? put(names, name) : NO_NAME;
  8856. if (sourcesIndex === sourcesContent.length)
  8857. sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
  8858. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
  8859. return;
  8860. }
  8861. return insert(line, index, name
  8862. ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
  8863. : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
  8864. };
  8865. })();
  8866. function getLine(mappings, index) {
  8867. for (let i = mappings.length; i <= index; i++) {
  8868. mappings[i] = [];
  8869. }
  8870. return mappings[index];
  8871. }
  8872. function getColumnIndex(line, genColumn) {
  8873. let index = line.length;
  8874. for (let i = index - 1; i >= 0; index = i--) {
  8875. const current = line[i];
  8876. if (genColumn >= current[COLUMN])
  8877. break;
  8878. }
  8879. return index;
  8880. }
  8881. function insert(array, index, value) {
  8882. for (let i = array.length; i > index; i--) {
  8883. array[i] = array[i - 1];
  8884. }
  8885. array[index] = value;
  8886. }
  8887. function removeEmptyFinalLines(mappings) {
  8888. const { length } = mappings;
  8889. let len = length;
  8890. for (let i = len - 1; i >= 0; len = i, i--) {
  8891. if (mappings[i].length > 0)
  8892. break;
  8893. }
  8894. if (len < length)
  8895. mappings.length = len;
  8896. }
  8897. function skipSourceless(line, index) {
  8898. // The start of a line is already sourceless, so adding a sourceless segment to the beginning
  8899. // doesn't generate any useful information.
  8900. if (index === 0)
  8901. return true;
  8902. const prev = line[index - 1];
  8903. // If the previous segment is also sourceless, then adding another sourceless segment doesn't
  8904. // genrate any new information. Else, this segment will end the source/named segment and point to
  8905. // a sourceless position, which is useful.
  8906. return prev.length === 1;
  8907. }
  8908. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  8909. // A source/named segment at the start of a line gives position at that genColumn
  8910. if (index === 0)
  8911. return false;
  8912. const prev = line[index - 1];
  8913. // If the previous segment is sourceless, then we're transitioning to a source.
  8914. if (prev.length === 1)
  8915. return false;
  8916. // If the previous segment maps to the exact same source position, then this segment doesn't
  8917. // provide any new position information.
  8918. return (sourcesIndex === prev[SOURCES_INDEX] &&
  8919. sourceLine === prev[SOURCE_LINE] &&
  8920. sourceColumn === prev[SOURCE_COLUMN] &&
  8921. namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
  8922. }
  8923. const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);
  8924. const EMPTY_SOURCES = [];
  8925. function SegmentObject(source, line, column, name, content) {
  8926. return { source, line, column, name, content };
  8927. }
  8928. function Source(map, sources, source, content) {
  8929. return {
  8930. map,
  8931. sources,
  8932. source,
  8933. content,
  8934. };
  8935. }
  8936. /**
  8937. * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
  8938. * (which may themselves be SourceMapTrees).
  8939. */
  8940. function MapSource(map, sources) {
  8941. return Source(map, sources, '', null);
  8942. }
  8943. /**
  8944. * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
  8945. * segment tracing ends at the `OriginalSource`.
  8946. */
  8947. function OriginalSource(source, content) {
  8948. return Source(null, EMPTY_SOURCES, source, content);
  8949. }
  8950. /**
  8951. * traceMappings is only called on the root level SourceMapTree, and begins the process of
  8952. * resolving each mapping in terms of the original source files.
  8953. */
  8954. function traceMappings(tree) {
  8955. // TODO: Eventually support sourceRoot, which has to be removed because the sources are already
  8956. // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.
  8957. const gen = new GenMapping({ file: tree.map.file });
  8958. const { sources: rootSources, map } = tree;
  8959. const rootNames = map.names;
  8960. const rootMappings = decodedMappings(map);
  8961. for (let i = 0; i < rootMappings.length; i++) {
  8962. const segments = rootMappings[i];
  8963. for (let j = 0; j < segments.length; j++) {
  8964. const segment = segments[j];
  8965. const genCol = segment[0];
  8966. let traced = SOURCELESS_MAPPING;
  8967. // 1-length segments only move the current generated column, there's no source information
  8968. // to gather from it.
  8969. if (segment.length !== 1) {
  8970. const source = rootSources[segment[1]];
  8971. traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
  8972. // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
  8973. // respective segment into an original source.
  8974. if (traced == null)
  8975. continue;
  8976. }
  8977. const { column, line, name, content, source } = traced;
  8978. maybeAddSegment(gen, i, genCol, source, line, column, name);
  8979. if (source && content != null)
  8980. setSourceContent(gen, source, content);
  8981. }
  8982. }
  8983. return gen;
  8984. }
  8985. /**
  8986. * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
  8987. * child SourceMapTrees, until we find the original source map.
  8988. */
  8989. function originalPositionFor(source, line, column, name) {
  8990. if (!source.map) {
  8991. return SegmentObject(source.source, line, column, name, source.content);
  8992. }
  8993. const segment = traceSegment(source.map, line, column);
  8994. // If we couldn't find a segment, then this doesn't exist in the sourcemap.
  8995. if (segment == null)
  8996. return null;
  8997. // 1-length segments only move the current generated column, there's no source information
  8998. // to gather from it.
  8999. if (segment.length === 1)
  9000. return SOURCELESS_MAPPING;
  9001. return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  9002. }
  9003. function asArray(value) {
  9004. if (Array.isArray(value))
  9005. return value;
  9006. return [value];
  9007. }
  9008. /**
  9009. * Recursively builds a tree structure out of sourcemap files, with each node
  9010. * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
  9011. * `OriginalSource`s and `SourceMapTree`s.
  9012. *
  9013. * Every sourcemap is composed of a collection of source files and mappings
  9014. * into locations of those source files. When we generate a `SourceMapTree` for
  9015. * the sourcemap, we attempt to load each source file's own sourcemap. If it
  9016. * does not have an associated sourcemap, it is considered an original,
  9017. * unmodified source file.
  9018. */
  9019. function buildSourceMapTree(input, loader) {
  9020. const maps = asArray(input).map((m) => new TraceMap(m, ''));
  9021. const map = maps.pop();
  9022. for (let i = 0; i < maps.length; i++) {
  9023. if (maps[i].sources.length > 1) {
  9024. throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
  9025. 'Did you specify these with the most recent transformation maps first?');
  9026. }
  9027. }
  9028. let tree = build$2(map, loader, '', 0);
  9029. for (let i = maps.length - 1; i >= 0; i--) {
  9030. tree = MapSource(maps[i], [tree]);
  9031. }
  9032. return tree;
  9033. }
  9034. function build$2(map, loader, importer, importerDepth) {
  9035. const { resolvedSources, sourcesContent } = map;
  9036. const depth = importerDepth + 1;
  9037. const children = resolvedSources.map((sourceFile, i) => {
  9038. // The loading context gives the loader more information about why this file is being loaded
  9039. // (eg, from which importer). It also allows the loader to override the location of the loaded
  9040. // sourcemap/original source, or to override the content in the sourcesContent field if it's
  9041. // an unmodified source file.
  9042. const ctx = {
  9043. importer,
  9044. depth,
  9045. source: sourceFile || '',
  9046. content: undefined,
  9047. };
  9048. // Use the provided loader callback to retrieve the file's sourcemap.
  9049. // TODO: We should eventually support async loading of sourcemap files.
  9050. const sourceMap = loader(ctx.source, ctx);
  9051. const { source, content } = ctx;
  9052. // If there is a sourcemap, then we need to recurse into it to load its source files.
  9053. if (sourceMap)
  9054. return build$2(new TraceMap(sourceMap, source), loader, source, depth);
  9055. // Else, it's an an unmodified source file.
  9056. // The contents of this unmodified source file can be overridden via the loader context,
  9057. // allowing it to be explicitly null or a string. If it remains undefined, we fall back to
  9058. // the importing sourcemap's `sourcesContent` field.
  9059. const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;
  9060. return OriginalSource(source, sourceContent);
  9061. });
  9062. return MapSource(map, children);
  9063. }
  9064. /**
  9065. * A SourceMap v3 compatible sourcemap, which only includes fields that were
  9066. * provided to it.
  9067. */
  9068. let SourceMap$1 = class SourceMap {
  9069. constructor(map, options) {
  9070. const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
  9071. this.version = out.version; // SourceMap spec says this should be first.
  9072. this.file = out.file;
  9073. this.mappings = out.mappings;
  9074. this.names = out.names;
  9075. this.sourceRoot = out.sourceRoot;
  9076. this.sources = out.sources;
  9077. if (!options.excludeContent) {
  9078. this.sourcesContent = out.sourcesContent;
  9079. }
  9080. }
  9081. toString() {
  9082. return JSON.stringify(this);
  9083. }
  9084. };
  9085. /**
  9086. * Traces through all the mappings in the root sourcemap, through the sources
  9087. * (and their sourcemaps), all the way back to the original source location.
  9088. *
  9089. * `loader` will be called every time we encounter a source file. If it returns
  9090. * a sourcemap, we will recurse into that sourcemap to continue the trace. If
  9091. * it returns a falsey value, that source file is treated as an original,
  9092. * unmodified source file.
  9093. *
  9094. * Pass `excludeContent` to exclude any self-containing source file content
  9095. * from the output sourcemap.
  9096. *
  9097. * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
  9098. * VLQ encoded) mappings.
  9099. */
  9100. function remapping(input, loader, options) {
  9101. const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
  9102. const tree = buildSourceMapTree(input, loader);
  9103. return new SourceMap$1(traceMappings(tree), opts);
  9104. }
  9105. var src$2 = {exports: {}};
  9106. var browser$2 = {exports: {}};
  9107. /**
  9108. * Helpers.
  9109. */
  9110. var ms$1;
  9111. var hasRequiredMs$1;
  9112. function requireMs$1 () {
  9113. if (hasRequiredMs$1) return ms$1;
  9114. hasRequiredMs$1 = 1;
  9115. var s = 1000;
  9116. var m = s * 60;
  9117. var h = m * 60;
  9118. var d = h * 24;
  9119. var w = d * 7;
  9120. var y = d * 365.25;
  9121. /**
  9122. * Parse or format the given `val`.
  9123. *
  9124. * Options:
  9125. *
  9126. * - `long` verbose formatting [false]
  9127. *
  9128. * @param {String|Number} val
  9129. * @param {Object} [options]
  9130. * @throws {Error} throw an error if val is not a non-empty string or a number
  9131. * @return {String|Number}
  9132. * @api public
  9133. */
  9134. ms$1 = function(val, options) {
  9135. options = options || {};
  9136. var type = typeof val;
  9137. if (type === 'string' && val.length > 0) {
  9138. return parse(val);
  9139. } else if (type === 'number' && isFinite(val)) {
  9140. return options.long ? fmtLong(val) : fmtShort(val);
  9141. }
  9142. throw new Error(
  9143. 'val is not a non-empty string or a valid number. val=' +
  9144. JSON.stringify(val)
  9145. );
  9146. };
  9147. /**
  9148. * Parse the given `str` and return milliseconds.
  9149. *
  9150. * @param {String} str
  9151. * @return {Number}
  9152. * @api private
  9153. */
  9154. function parse(str) {
  9155. str = String(str);
  9156. if (str.length > 100) {
  9157. return;
  9158. }
  9159. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  9160. str
  9161. );
  9162. if (!match) {
  9163. return;
  9164. }
  9165. var n = parseFloat(match[1]);
  9166. var type = (match[2] || 'ms').toLowerCase();
  9167. switch (type) {
  9168. case 'years':
  9169. case 'year':
  9170. case 'yrs':
  9171. case 'yr':
  9172. case 'y':
  9173. return n * y;
  9174. case 'weeks':
  9175. case 'week':
  9176. case 'w':
  9177. return n * w;
  9178. case 'days':
  9179. case 'day':
  9180. case 'd':
  9181. return n * d;
  9182. case 'hours':
  9183. case 'hour':
  9184. case 'hrs':
  9185. case 'hr':
  9186. case 'h':
  9187. return n * h;
  9188. case 'minutes':
  9189. case 'minute':
  9190. case 'mins':
  9191. case 'min':
  9192. case 'm':
  9193. return n * m;
  9194. case 'seconds':
  9195. case 'second':
  9196. case 'secs':
  9197. case 'sec':
  9198. case 's':
  9199. return n * s;
  9200. case 'milliseconds':
  9201. case 'millisecond':
  9202. case 'msecs':
  9203. case 'msec':
  9204. case 'ms':
  9205. return n;
  9206. default:
  9207. return undefined;
  9208. }
  9209. }
  9210. /**
  9211. * Short format for `ms`.
  9212. *
  9213. * @param {Number} ms
  9214. * @return {String}
  9215. * @api private
  9216. */
  9217. function fmtShort(ms) {
  9218. var msAbs = Math.abs(ms);
  9219. if (msAbs >= d) {
  9220. return Math.round(ms / d) + 'd';
  9221. }
  9222. if (msAbs >= h) {
  9223. return Math.round(ms / h) + 'h';
  9224. }
  9225. if (msAbs >= m) {
  9226. return Math.round(ms / m) + 'm';
  9227. }
  9228. if (msAbs >= s) {
  9229. return Math.round(ms / s) + 's';
  9230. }
  9231. return ms + 'ms';
  9232. }
  9233. /**
  9234. * Long format for `ms`.
  9235. *
  9236. * @param {Number} ms
  9237. * @return {String}
  9238. * @api private
  9239. */
  9240. function fmtLong(ms) {
  9241. var msAbs = Math.abs(ms);
  9242. if (msAbs >= d) {
  9243. return plural(ms, msAbs, d, 'day');
  9244. }
  9245. if (msAbs >= h) {
  9246. return plural(ms, msAbs, h, 'hour');
  9247. }
  9248. if (msAbs >= m) {
  9249. return plural(ms, msAbs, m, 'minute');
  9250. }
  9251. if (msAbs >= s) {
  9252. return plural(ms, msAbs, s, 'second');
  9253. }
  9254. return ms + ' ms';
  9255. }
  9256. /**
  9257. * Pluralization helper.
  9258. */
  9259. function plural(ms, msAbs, n, name) {
  9260. var isPlural = msAbs >= n * 1.5;
  9261. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  9262. }
  9263. return ms$1;
  9264. }
  9265. var common$b;
  9266. var hasRequiredCommon;
  9267. function requireCommon () {
  9268. if (hasRequiredCommon) return common$b;
  9269. hasRequiredCommon = 1;
  9270. /**
  9271. * This is the common logic for both the Node.js and web browser
  9272. * implementations of `debug()`.
  9273. */
  9274. function setup(env) {
  9275. createDebug.debug = createDebug;
  9276. createDebug.default = createDebug;
  9277. createDebug.coerce = coerce;
  9278. createDebug.disable = disable;
  9279. createDebug.enable = enable;
  9280. createDebug.enabled = enabled;
  9281. createDebug.humanize = requireMs$1();
  9282. createDebug.destroy = destroy;
  9283. Object.keys(env).forEach(key => {
  9284. createDebug[key] = env[key];
  9285. });
  9286. /**
  9287. * The currently active debug mode names, and names to skip.
  9288. */
  9289. createDebug.names = [];
  9290. createDebug.skips = [];
  9291. /**
  9292. * Map of special "%n" handling functions, for the debug "format" argument.
  9293. *
  9294. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  9295. */
  9296. createDebug.formatters = {};
  9297. /**
  9298. * Selects a color for a debug namespace
  9299. * @param {String} namespace The namespace string for the debug instance to be colored
  9300. * @return {Number|String} An ANSI color code for the given namespace
  9301. * @api private
  9302. */
  9303. function selectColor(namespace) {
  9304. let hash = 0;
  9305. for (let i = 0; i < namespace.length; i++) {
  9306. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  9307. hash |= 0; // Convert to 32bit integer
  9308. }
  9309. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  9310. }
  9311. createDebug.selectColor = selectColor;
  9312. /**
  9313. * Create a debugger with the given `namespace`.
  9314. *
  9315. * @param {String} namespace
  9316. * @return {Function}
  9317. * @api public
  9318. */
  9319. function createDebug(namespace) {
  9320. let prevTime;
  9321. let enableOverride = null;
  9322. let namespacesCache;
  9323. let enabledCache;
  9324. function debug(...args) {
  9325. // Disabled?
  9326. if (!debug.enabled) {
  9327. return;
  9328. }
  9329. const self = debug;
  9330. // Set `diff` timestamp
  9331. const curr = Number(new Date());
  9332. const ms = curr - (prevTime || curr);
  9333. self.diff = ms;
  9334. self.prev = prevTime;
  9335. self.curr = curr;
  9336. prevTime = curr;
  9337. args[0] = createDebug.coerce(args[0]);
  9338. if (typeof args[0] !== 'string') {
  9339. // Anything else let's inspect with %O
  9340. args.unshift('%O');
  9341. }
  9342. // Apply any `formatters` transformations
  9343. let index = 0;
  9344. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  9345. // If we encounter an escaped % then don't increase the array index
  9346. if (match === '%%') {
  9347. return '%';
  9348. }
  9349. index++;
  9350. const formatter = createDebug.formatters[format];
  9351. if (typeof formatter === 'function') {
  9352. const val = args[index];
  9353. match = formatter.call(self, val);
  9354. // Now we need to remove `args[index]` since it's inlined in the `format`
  9355. args.splice(index, 1);
  9356. index--;
  9357. }
  9358. return match;
  9359. });
  9360. // Apply env-specific formatting (colors, etc.)
  9361. createDebug.formatArgs.call(self, args);
  9362. const logFn = self.log || createDebug.log;
  9363. logFn.apply(self, args);
  9364. }
  9365. debug.namespace = namespace;
  9366. debug.useColors = createDebug.useColors();
  9367. debug.color = createDebug.selectColor(namespace);
  9368. debug.extend = extend;
  9369. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  9370. Object.defineProperty(debug, 'enabled', {
  9371. enumerable: true,
  9372. configurable: false,
  9373. get: () => {
  9374. if (enableOverride !== null) {
  9375. return enableOverride;
  9376. }
  9377. if (namespacesCache !== createDebug.namespaces) {
  9378. namespacesCache = createDebug.namespaces;
  9379. enabledCache = createDebug.enabled(namespace);
  9380. }
  9381. return enabledCache;
  9382. },
  9383. set: v => {
  9384. enableOverride = v;
  9385. }
  9386. });
  9387. // Env-specific initialization logic for debug instances
  9388. if (typeof createDebug.init === 'function') {
  9389. createDebug.init(debug);
  9390. }
  9391. return debug;
  9392. }
  9393. function extend(namespace, delimiter) {
  9394. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  9395. newDebug.log = this.log;
  9396. return newDebug;
  9397. }
  9398. /**
  9399. * Enables a debug mode by namespaces. This can include modes
  9400. * separated by a colon and wildcards.
  9401. *
  9402. * @param {String} namespaces
  9403. * @api public
  9404. */
  9405. function enable(namespaces) {
  9406. createDebug.save(namespaces);
  9407. createDebug.namespaces = namespaces;
  9408. createDebug.names = [];
  9409. createDebug.skips = [];
  9410. let i;
  9411. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  9412. const len = split.length;
  9413. for (i = 0; i < len; i++) {
  9414. if (!split[i]) {
  9415. // ignore empty strings
  9416. continue;
  9417. }
  9418. namespaces = split[i].replace(/\*/g, '.*?');
  9419. if (namespaces[0] === '-') {
  9420. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  9421. } else {
  9422. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  9423. }
  9424. }
  9425. }
  9426. /**
  9427. * Disable debug output.
  9428. *
  9429. * @return {String} namespaces
  9430. * @api public
  9431. */
  9432. function disable() {
  9433. const namespaces = [
  9434. ...createDebug.names.map(toNamespace),
  9435. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  9436. ].join(',');
  9437. createDebug.enable('');
  9438. return namespaces;
  9439. }
  9440. /**
  9441. * Returns true if the given mode name is enabled, false otherwise.
  9442. *
  9443. * @param {String} name
  9444. * @return {Boolean}
  9445. * @api public
  9446. */
  9447. function enabled(name) {
  9448. if (name[name.length - 1] === '*') {
  9449. return true;
  9450. }
  9451. let i;
  9452. let len;
  9453. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  9454. if (createDebug.skips[i].test(name)) {
  9455. return false;
  9456. }
  9457. }
  9458. for (i = 0, len = createDebug.names.length; i < len; i++) {
  9459. if (createDebug.names[i].test(name)) {
  9460. return true;
  9461. }
  9462. }
  9463. return false;
  9464. }
  9465. /**
  9466. * Convert regexp to namespace
  9467. *
  9468. * @param {RegExp} regxep
  9469. * @return {String} namespace
  9470. * @api private
  9471. */
  9472. function toNamespace(regexp) {
  9473. return regexp.toString()
  9474. .substring(2, regexp.toString().length - 2)
  9475. .replace(/\.\*\?$/, '*');
  9476. }
  9477. /**
  9478. * Coerce `val`.
  9479. *
  9480. * @param {Mixed} val
  9481. * @return {Mixed}
  9482. * @api private
  9483. */
  9484. function coerce(val) {
  9485. if (val instanceof Error) {
  9486. return val.stack || val.message;
  9487. }
  9488. return val;
  9489. }
  9490. /**
  9491. * XXX DO NOT USE. This is a temporary stub function.
  9492. * XXX It WILL be removed in the next major release.
  9493. */
  9494. function destroy() {
  9495. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  9496. }
  9497. createDebug.enable(createDebug.load());
  9498. return createDebug;
  9499. }
  9500. common$b = setup;
  9501. return common$b;
  9502. }
  9503. /* eslint-env browser */
  9504. var hasRequiredBrowser$1;
  9505. function requireBrowser$1 () {
  9506. if (hasRequiredBrowser$1) return browser$2.exports;
  9507. hasRequiredBrowser$1 = 1;
  9508. (function (module, exports) {
  9509. /**
  9510. * This is the web browser implementation of `debug()`.
  9511. */
  9512. exports.formatArgs = formatArgs;
  9513. exports.save = save;
  9514. exports.load = load;
  9515. exports.useColors = useColors;
  9516. exports.storage = localstorage();
  9517. exports.destroy = (() => {
  9518. let warned = false;
  9519. return () => {
  9520. if (!warned) {
  9521. warned = true;
  9522. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  9523. }
  9524. };
  9525. })();
  9526. /**
  9527. * Colors.
  9528. */
  9529. exports.colors = [
  9530. '#0000CC',
  9531. '#0000FF',
  9532. '#0033CC',
  9533. '#0033FF',
  9534. '#0066CC',
  9535. '#0066FF',
  9536. '#0099CC',
  9537. '#0099FF',
  9538. '#00CC00',
  9539. '#00CC33',
  9540. '#00CC66',
  9541. '#00CC99',
  9542. '#00CCCC',
  9543. '#00CCFF',
  9544. '#3300CC',
  9545. '#3300FF',
  9546. '#3333CC',
  9547. '#3333FF',
  9548. '#3366CC',
  9549. '#3366FF',
  9550. '#3399CC',
  9551. '#3399FF',
  9552. '#33CC00',
  9553. '#33CC33',
  9554. '#33CC66',
  9555. '#33CC99',
  9556. '#33CCCC',
  9557. '#33CCFF',
  9558. '#6600CC',
  9559. '#6600FF',
  9560. '#6633CC',
  9561. '#6633FF',
  9562. '#66CC00',
  9563. '#66CC33',
  9564. '#9900CC',
  9565. '#9900FF',
  9566. '#9933CC',
  9567. '#9933FF',
  9568. '#99CC00',
  9569. '#99CC33',
  9570. '#CC0000',
  9571. '#CC0033',
  9572. '#CC0066',
  9573. '#CC0099',
  9574. '#CC00CC',
  9575. '#CC00FF',
  9576. '#CC3300',
  9577. '#CC3333',
  9578. '#CC3366',
  9579. '#CC3399',
  9580. '#CC33CC',
  9581. '#CC33FF',
  9582. '#CC6600',
  9583. '#CC6633',
  9584. '#CC9900',
  9585. '#CC9933',
  9586. '#CCCC00',
  9587. '#CCCC33',
  9588. '#FF0000',
  9589. '#FF0033',
  9590. '#FF0066',
  9591. '#FF0099',
  9592. '#FF00CC',
  9593. '#FF00FF',
  9594. '#FF3300',
  9595. '#FF3333',
  9596. '#FF3366',
  9597. '#FF3399',
  9598. '#FF33CC',
  9599. '#FF33FF',
  9600. '#FF6600',
  9601. '#FF6633',
  9602. '#FF9900',
  9603. '#FF9933',
  9604. '#FFCC00',
  9605. '#FFCC33'
  9606. ];
  9607. /**
  9608. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  9609. * and the Firebug extension (any Firefox version) are known
  9610. * to support "%c" CSS customizations.
  9611. *
  9612. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  9613. */
  9614. // eslint-disable-next-line complexity
  9615. function useColors() {
  9616. // NB: In an Electron preload script, document will be defined but not fully
  9617. // initialized. Since we know we're in Chrome, we'll just detect this case
  9618. // explicitly
  9619. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  9620. return true;
  9621. }
  9622. // Internet Explorer and Edge do not support colors.
  9623. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  9624. return false;
  9625. }
  9626. // Is webkit? http://stackoverflow.com/a/16459606/376773
  9627. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  9628. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  9629. // Is firebug? http://stackoverflow.com/a/398120/376773
  9630. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  9631. // Is firefox >= v31?
  9632. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  9633. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  9634. // Double check webkit in userAgent just in case we are in a worker
  9635. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  9636. }
  9637. /**
  9638. * Colorize log arguments if enabled.
  9639. *
  9640. * @api public
  9641. */
  9642. function formatArgs(args) {
  9643. args[0] = (this.useColors ? '%c' : '') +
  9644. this.namespace +
  9645. (this.useColors ? ' %c' : ' ') +
  9646. args[0] +
  9647. (this.useColors ? '%c ' : ' ') +
  9648. '+' + module.exports.humanize(this.diff);
  9649. if (!this.useColors) {
  9650. return;
  9651. }
  9652. const c = 'color: ' + this.color;
  9653. args.splice(1, 0, c, 'color: inherit');
  9654. // The final "%c" is somewhat tricky, because there could be other
  9655. // arguments passed either before or after the %c, so we need to
  9656. // figure out the correct index to insert the CSS into
  9657. let index = 0;
  9658. let lastC = 0;
  9659. args[0].replace(/%[a-zA-Z%]/g, match => {
  9660. if (match === '%%') {
  9661. return;
  9662. }
  9663. index++;
  9664. if (match === '%c') {
  9665. // We only are interested in the *last* %c
  9666. // (the user may have provided their own)
  9667. lastC = index;
  9668. }
  9669. });
  9670. args.splice(lastC, 0, c);
  9671. }
  9672. /**
  9673. * Invokes `console.debug()` when available.
  9674. * No-op when `console.debug` is not a "function".
  9675. * If `console.debug` is not available, falls back
  9676. * to `console.log`.
  9677. *
  9678. * @api public
  9679. */
  9680. exports.log = console.debug || console.log || (() => {});
  9681. /**
  9682. * Save `namespaces`.
  9683. *
  9684. * @param {String} namespaces
  9685. * @api private
  9686. */
  9687. function save(namespaces) {
  9688. try {
  9689. if (namespaces) {
  9690. exports.storage.setItem('debug', namespaces);
  9691. } else {
  9692. exports.storage.removeItem('debug');
  9693. }
  9694. } catch (error) {
  9695. // Swallow
  9696. // XXX (@Qix-) should we be logging these?
  9697. }
  9698. }
  9699. /**
  9700. * Load `namespaces`.
  9701. *
  9702. * @return {String} returns the previously persisted debug modes
  9703. * @api private
  9704. */
  9705. function load() {
  9706. let r;
  9707. try {
  9708. r = exports.storage.getItem('debug');
  9709. } catch (error) {
  9710. // Swallow
  9711. // XXX (@Qix-) should we be logging these?
  9712. }
  9713. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  9714. if (!r && typeof process !== 'undefined' && 'env' in process) {
  9715. r = process.env.DEBUG;
  9716. }
  9717. return r;
  9718. }
  9719. /**
  9720. * Localstorage attempts to return the localstorage.
  9721. *
  9722. * This is necessary because safari throws
  9723. * when a user disables cookies/localstorage
  9724. * and you attempt to access it.
  9725. *
  9726. * @return {LocalStorage}
  9727. * @api private
  9728. */
  9729. function localstorage() {
  9730. try {
  9731. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  9732. // The Browser also has localStorage in the global context.
  9733. return localStorage;
  9734. } catch (error) {
  9735. // Swallow
  9736. // XXX (@Qix-) should we be logging these?
  9737. }
  9738. }
  9739. module.exports = requireCommon()(exports);
  9740. const {formatters} = module.exports;
  9741. /**
  9742. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  9743. */
  9744. formatters.j = function (v) {
  9745. try {
  9746. return JSON.stringify(v);
  9747. } catch (error) {
  9748. return '[UnexpectedJSONParseError]: ' + error.message;
  9749. }
  9750. };
  9751. } (browser$2, browser$2.exports));
  9752. return browser$2.exports;
  9753. }
  9754. var node$1 = {exports: {}};
  9755. /**
  9756. * Module dependencies.
  9757. */
  9758. var hasRequiredNode$1;
  9759. function requireNode$1 () {
  9760. if (hasRequiredNode$1) return node$1.exports;
  9761. hasRequiredNode$1 = 1;
  9762. (function (module, exports) {
  9763. const tty = require$$0$3;
  9764. const util = require$$0$6;
  9765. /**
  9766. * This is the Node.js implementation of `debug()`.
  9767. */
  9768. exports.init = init;
  9769. exports.log = log;
  9770. exports.formatArgs = formatArgs;
  9771. exports.save = save;
  9772. exports.load = load;
  9773. exports.useColors = useColors;
  9774. exports.destroy = util.deprecate(
  9775. () => {},
  9776. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  9777. );
  9778. /**
  9779. * Colors.
  9780. */
  9781. exports.colors = [6, 2, 3, 4, 5, 1];
  9782. try {
  9783. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  9784. // eslint-disable-next-line import/no-extraneous-dependencies
  9785. const supportsColor = require('supports-color');
  9786. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  9787. exports.colors = [
  9788. 20,
  9789. 21,
  9790. 26,
  9791. 27,
  9792. 32,
  9793. 33,
  9794. 38,
  9795. 39,
  9796. 40,
  9797. 41,
  9798. 42,
  9799. 43,
  9800. 44,
  9801. 45,
  9802. 56,
  9803. 57,
  9804. 62,
  9805. 63,
  9806. 68,
  9807. 69,
  9808. 74,
  9809. 75,
  9810. 76,
  9811. 77,
  9812. 78,
  9813. 79,
  9814. 80,
  9815. 81,
  9816. 92,
  9817. 93,
  9818. 98,
  9819. 99,
  9820. 112,
  9821. 113,
  9822. 128,
  9823. 129,
  9824. 134,
  9825. 135,
  9826. 148,
  9827. 149,
  9828. 160,
  9829. 161,
  9830. 162,
  9831. 163,
  9832. 164,
  9833. 165,
  9834. 166,
  9835. 167,
  9836. 168,
  9837. 169,
  9838. 170,
  9839. 171,
  9840. 172,
  9841. 173,
  9842. 178,
  9843. 179,
  9844. 184,
  9845. 185,
  9846. 196,
  9847. 197,
  9848. 198,
  9849. 199,
  9850. 200,
  9851. 201,
  9852. 202,
  9853. 203,
  9854. 204,
  9855. 205,
  9856. 206,
  9857. 207,
  9858. 208,
  9859. 209,
  9860. 214,
  9861. 215,
  9862. 220,
  9863. 221
  9864. ];
  9865. }
  9866. } catch (error) {
  9867. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  9868. }
  9869. /**
  9870. * Build up the default `inspectOpts` object from the environment variables.
  9871. *
  9872. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  9873. */
  9874. exports.inspectOpts = Object.keys(process.env).filter(key => {
  9875. return /^debug_/i.test(key);
  9876. }).reduce((obj, key) => {
  9877. // Camel-case
  9878. const prop = key
  9879. .substring(6)
  9880. .toLowerCase()
  9881. .replace(/_([a-z])/g, (_, k) => {
  9882. return k.toUpperCase();
  9883. });
  9884. // Coerce string value into JS value
  9885. let val = process.env[key];
  9886. if (/^(yes|on|true|enabled)$/i.test(val)) {
  9887. val = true;
  9888. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  9889. val = false;
  9890. } else if (val === 'null') {
  9891. val = null;
  9892. } else {
  9893. val = Number(val);
  9894. }
  9895. obj[prop] = val;
  9896. return obj;
  9897. }, {});
  9898. /**
  9899. * Is stdout a TTY? Colored output is enabled when `true`.
  9900. */
  9901. function useColors() {
  9902. return 'colors' in exports.inspectOpts ?
  9903. Boolean(exports.inspectOpts.colors) :
  9904. tty.isatty(process.stderr.fd);
  9905. }
  9906. /**
  9907. * Adds ANSI color escape codes if enabled.
  9908. *
  9909. * @api public
  9910. */
  9911. function formatArgs(args) {
  9912. const {namespace: name, useColors} = this;
  9913. if (useColors) {
  9914. const c = this.color;
  9915. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  9916. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  9917. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  9918. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  9919. } else {
  9920. args[0] = getDate() + name + ' ' + args[0];
  9921. }
  9922. }
  9923. function getDate() {
  9924. if (exports.inspectOpts.hideDate) {
  9925. return '';
  9926. }
  9927. return new Date().toISOString() + ' ';
  9928. }
  9929. /**
  9930. * Invokes `util.format()` with the specified arguments and writes to stderr.
  9931. */
  9932. function log(...args) {
  9933. return process.stderr.write(util.format(...args) + '\n');
  9934. }
  9935. /**
  9936. * Save `namespaces`.
  9937. *
  9938. * @param {String} namespaces
  9939. * @api private
  9940. */
  9941. function save(namespaces) {
  9942. if (namespaces) {
  9943. process.env.DEBUG = namespaces;
  9944. } else {
  9945. // If you set a process.env field to null or undefined, it gets cast to the
  9946. // string 'null' or 'undefined'. Just delete instead.
  9947. delete process.env.DEBUG;
  9948. }
  9949. }
  9950. /**
  9951. * Load `namespaces`.
  9952. *
  9953. * @return {String} returns the previously persisted debug modes
  9954. * @api private
  9955. */
  9956. function load() {
  9957. return process.env.DEBUG;
  9958. }
  9959. /**
  9960. * Init logic for `debug` instances.
  9961. *
  9962. * Create a new `inspectOpts` object in case `useColors` is set
  9963. * differently for a particular `debug` instance.
  9964. */
  9965. function init(debug) {
  9966. debug.inspectOpts = {};
  9967. const keys = Object.keys(exports.inspectOpts);
  9968. for (let i = 0; i < keys.length; i++) {
  9969. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  9970. }
  9971. }
  9972. module.exports = requireCommon()(exports);
  9973. const {formatters} = module.exports;
  9974. /**
  9975. * Map %o to `util.inspect()`, all on a single line.
  9976. */
  9977. formatters.o = function (v) {
  9978. this.inspectOpts.colors = this.useColors;
  9979. return util.inspect(v, this.inspectOpts)
  9980. .split('\n')
  9981. .map(str => str.trim())
  9982. .join(' ');
  9983. };
  9984. /**
  9985. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  9986. */
  9987. formatters.O = function (v) {
  9988. this.inspectOpts.colors = this.useColors;
  9989. return util.inspect(v, this.inspectOpts);
  9990. };
  9991. } (node$1, node$1.exports));
  9992. return node$1.exports;
  9993. }
  9994. /**
  9995. * Detect Electron renderer / nwjs process, which is node, but we should
  9996. * treat as a browser.
  9997. */
  9998. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  9999. src$2.exports = requireBrowser$1();
  10000. } else {
  10001. src$2.exports = requireNode$1();
  10002. }
  10003. var srcExports$1 = src$2.exports;
  10004. var debug$g = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1);
  10005. // eslint-disable-next-line @typescript-eslint/consistent-type-imports
  10006. let pnp;
  10007. if (process.versions.pnp) {
  10008. try {
  10009. pnp = createRequire$1(import.meta.url)('pnpapi');
  10010. }
  10011. catch { }
  10012. }
  10013. function invalidatePackageData(packageCache, pkgPath) {
  10014. const pkgDir = path$o.dirname(pkgPath);
  10015. packageCache.forEach((pkg, cacheKey) => {
  10016. if (pkg.dir === pkgDir) {
  10017. packageCache.delete(cacheKey);
  10018. }
  10019. });
  10020. }
  10021. function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
  10022. if (pnp) {
  10023. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  10024. if (packageCache?.has(cacheKey))
  10025. return packageCache.get(cacheKey);
  10026. let pkg;
  10027. try {
  10028. pkg = pnp.resolveToUnqualified(pkgName, basedir, {
  10029. considerBuiltins: false,
  10030. });
  10031. }
  10032. catch {
  10033. return null;
  10034. }
  10035. if (!pkg)
  10036. return null;
  10037. const pkgData = loadPackageData(path$o.join(pkg, 'package.json'));
  10038. packageCache?.set(cacheKey, pkgData);
  10039. return pkgData;
  10040. }
  10041. const originalBasedir = basedir;
  10042. while (basedir) {
  10043. if (packageCache) {
  10044. const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks);
  10045. if (cached)
  10046. return cached;
  10047. }
  10048. const pkg = path$o.join(basedir, 'node_modules', pkgName, 'package.json');
  10049. try {
  10050. if (fs$l.existsSync(pkg)) {
  10051. const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
  10052. const pkgData = loadPackageData(pkgPath);
  10053. if (packageCache) {
  10054. setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks);
  10055. }
  10056. return pkgData;
  10057. }
  10058. }
  10059. catch { }
  10060. const nextBasedir = path$o.dirname(basedir);
  10061. if (nextBasedir === basedir)
  10062. break;
  10063. basedir = nextBasedir;
  10064. }
  10065. return null;
  10066. }
  10067. function findNearestPackageData(basedir, packageCache) {
  10068. const originalBasedir = basedir;
  10069. while (basedir) {
  10070. if (packageCache) {
  10071. const cached = getFnpdCache(packageCache, basedir, originalBasedir);
  10072. if (cached)
  10073. return cached;
  10074. }
  10075. const pkgPath = path$o.join(basedir, 'package.json');
  10076. try {
  10077. if (fs$l.statSync(pkgPath, { throwIfNoEntry: false })?.isFile()) {
  10078. const pkgData = loadPackageData(pkgPath);
  10079. if (packageCache) {
  10080. setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
  10081. }
  10082. return pkgData;
  10083. }
  10084. }
  10085. catch { }
  10086. const nextBasedir = path$o.dirname(basedir);
  10087. if (nextBasedir === basedir)
  10088. break;
  10089. basedir = nextBasedir;
  10090. }
  10091. return null;
  10092. }
  10093. // Finds the nearest package.json with a `name` field
  10094. function findNearestMainPackageData(basedir, packageCache) {
  10095. const nearestPackage = findNearestPackageData(basedir, packageCache);
  10096. return (nearestPackage &&
  10097. (nearestPackage.data.name
  10098. ? nearestPackage
  10099. : findNearestMainPackageData(path$o.dirname(nearestPackage.dir), packageCache)));
  10100. }
  10101. function loadPackageData(pkgPath) {
  10102. const data = JSON.parse(fs$l.readFileSync(pkgPath, 'utf-8'));
  10103. const pkgDir = path$o.dirname(pkgPath);
  10104. const { sideEffects } = data;
  10105. let hasSideEffects;
  10106. if (typeof sideEffects === 'boolean') {
  10107. hasSideEffects = () => sideEffects;
  10108. }
  10109. else if (Array.isArray(sideEffects)) {
  10110. const finalPackageSideEffects = sideEffects.map((sideEffect) => {
  10111. /*
  10112. * The array accepts simple glob patterns to the relevant files... Patterns like *.css, which do not include a /, will be treated like **\/*.css.
  10113. * https://webpack.js.org/guides/tree-shaking/
  10114. * https://github.com/vitejs/vite/pull/11807
  10115. */
  10116. if (sideEffect.includes('/')) {
  10117. return sideEffect;
  10118. }
  10119. return `**/${sideEffect}`;
  10120. });
  10121. hasSideEffects = createFilter(finalPackageSideEffects, null, {
  10122. resolve: pkgDir,
  10123. });
  10124. }
  10125. else {
  10126. hasSideEffects = () => true;
  10127. }
  10128. const pkg = {
  10129. dir: pkgDir,
  10130. data,
  10131. hasSideEffects,
  10132. webResolvedImports: {},
  10133. nodeResolvedImports: {},
  10134. setResolvedCache(key, entry, targetWeb) {
  10135. if (targetWeb) {
  10136. pkg.webResolvedImports[key] = entry;
  10137. }
  10138. else {
  10139. pkg.nodeResolvedImports[key] = entry;
  10140. }
  10141. },
  10142. getResolvedCache(key, targetWeb) {
  10143. if (targetWeb) {
  10144. return pkg.webResolvedImports[key];
  10145. }
  10146. else {
  10147. return pkg.nodeResolvedImports[key];
  10148. }
  10149. },
  10150. };
  10151. return pkg;
  10152. }
  10153. function watchPackageDataPlugin(packageCache) {
  10154. // a list of files to watch before the plugin is ready
  10155. const watchQueue = new Set();
  10156. const watchedDirs = new Set();
  10157. const watchFileStub = (id) => {
  10158. watchQueue.add(id);
  10159. };
  10160. let watchFile = watchFileStub;
  10161. const setPackageData = packageCache.set.bind(packageCache);
  10162. packageCache.set = (id, pkg) => {
  10163. if (!isInNodeModules(pkg.dir) && !watchedDirs.has(pkg.dir)) {
  10164. watchedDirs.add(pkg.dir);
  10165. watchFile(path$o.join(pkg.dir, 'package.json'));
  10166. }
  10167. return setPackageData(id, pkg);
  10168. };
  10169. return {
  10170. name: 'vite:watch-package-data',
  10171. buildStart() {
  10172. watchFile = this.addWatchFile.bind(this);
  10173. watchQueue.forEach(watchFile);
  10174. watchQueue.clear();
  10175. },
  10176. buildEnd() {
  10177. watchFile = watchFileStub;
  10178. },
  10179. watchChange(id) {
  10180. if (id.endsWith('/package.json')) {
  10181. invalidatePackageData(packageCache, path$o.normalize(id));
  10182. }
  10183. },
  10184. handleHotUpdate({ file }) {
  10185. if (file.endsWith('/package.json')) {
  10186. invalidatePackageData(packageCache, path$o.normalize(file));
  10187. }
  10188. },
  10189. };
  10190. }
  10191. /**
  10192. * Get cached `resolvePackageData` value based on `basedir`. When one is found,
  10193. * and we've already traversed some directories between `basedir` and `originalBasedir`,
  10194. * we cache the value for those in-between directories as well.
  10195. *
  10196. * This makes it so the fs is only read once for a shared `basedir`.
  10197. */
  10198. function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
  10199. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  10200. const pkgData = packageCache.get(cacheKey);
  10201. if (pkgData) {
  10202. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  10203. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  10204. });
  10205. return pkgData;
  10206. }
  10207. }
  10208. function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
  10209. packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
  10210. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  10211. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  10212. });
  10213. }
  10214. // package cache key for `resolvePackageData`
  10215. function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
  10216. return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
  10217. }
  10218. /**
  10219. * Get cached `findNearestPackageData` value based on `basedir`. When one is found,
  10220. * and we've already traversed some directories between `basedir` and `originalBasedir`,
  10221. * we cache the value for those in-between directories as well.
  10222. *
  10223. * This makes it so the fs is only read once for a shared `basedir`.
  10224. */
  10225. function getFnpdCache(packageCache, basedir, originalBasedir) {
  10226. const cacheKey = getFnpdCacheKey(basedir);
  10227. const pkgData = packageCache.get(cacheKey);
  10228. if (pkgData) {
  10229. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  10230. packageCache.set(getFnpdCacheKey(dir), pkgData);
  10231. });
  10232. return pkgData;
  10233. }
  10234. }
  10235. function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
  10236. packageCache.set(getFnpdCacheKey(basedir), pkgData);
  10237. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  10238. packageCache.set(getFnpdCacheKey(dir), pkgData);
  10239. });
  10240. }
  10241. // package cache key for `findNearestPackageData`
  10242. function getFnpdCacheKey(basedir) {
  10243. return `fnpd_${basedir}`;
  10244. }
  10245. /**
  10246. * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
  10247. * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
  10248. * @param shorterDir Shorter dir path, e.g. `/User/foo`
  10249. */
  10250. function traverseBetweenDirs(longerDir, shorterDir, cb) {
  10251. while (longerDir !== shorterDir) {
  10252. cb(longerDir);
  10253. longerDir = path$o.dirname(longerDir);
  10254. }
  10255. }
  10256. const createFilter = createFilter$1;
  10257. const windowsSlashRE = /\\/g;
  10258. function slash$1(p) {
  10259. return p.replace(windowsSlashRE, '/');
  10260. }
  10261. /**
  10262. * Prepend `/@id/` and replace null byte so the id is URL-safe.
  10263. * This is prepended to resolved ids that are not valid browser
  10264. * import specifiers by the importAnalysis plugin.
  10265. */
  10266. function wrapId(id) {
  10267. return id.startsWith(VALID_ID_PREFIX)
  10268. ? id
  10269. : VALID_ID_PREFIX + id.replace('\0', NULL_BYTE_PLACEHOLDER);
  10270. }
  10271. /**
  10272. * Undo {@link wrapId}'s `/@id/` and null byte replacements.
  10273. */
  10274. function unwrapId(id) {
  10275. return id.startsWith(VALID_ID_PREFIX)
  10276. ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, '\0')
  10277. : id;
  10278. }
  10279. const replaceSlashOrColonRE = /[/:]/g;
  10280. const replaceDotRE = /\./g;
  10281. const replaceNestedIdRE = /(\s*>\s*)/g;
  10282. const replaceHashRE = /#/g;
  10283. const flattenId = (id) => id
  10284. .replace(replaceSlashOrColonRE, '_')
  10285. .replace(replaceDotRE, '__')
  10286. .replace(replaceNestedIdRE, '___')
  10287. .replace(replaceHashRE, '____');
  10288. const normalizeId = (id) => id.replace(replaceNestedIdRE, ' > ');
  10289. //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
  10290. const builtins = new Set([
  10291. ...builtinModules,
  10292. 'assert/strict',
  10293. 'diagnostics_channel',
  10294. 'dns/promises',
  10295. 'fs/promises',
  10296. 'path/posix',
  10297. 'path/win32',
  10298. 'readline/promises',
  10299. 'stream/consumers',
  10300. 'stream/promises',
  10301. 'stream/web',
  10302. 'timers/promises',
  10303. 'util/types',
  10304. 'wasi',
  10305. ]);
  10306. const NODE_BUILTIN_NAMESPACE = 'node:';
  10307. function isBuiltin(id) {
  10308. return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE)
  10309. ? id.slice(NODE_BUILTIN_NAMESPACE.length)
  10310. : id);
  10311. }
  10312. function isInNodeModules(id) {
  10313. return id.includes('node_modules');
  10314. }
  10315. function moduleListContains(moduleList, id) {
  10316. return moduleList?.some((m) => m === id || id.startsWith(m + '/'));
  10317. }
  10318. function isOptimizable(id, optimizeDeps) {
  10319. const { extensions } = optimizeDeps;
  10320. return (OPTIMIZABLE_ENTRY_RE.test(id) ||
  10321. (extensions?.some((ext) => id.endsWith(ext)) ?? false));
  10322. }
  10323. const bareImportRE = /^[\w@](?!.*:\/\/)/;
  10324. const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
  10325. // TODO: use import()
  10326. const _require$3 = createRequire$1(import.meta.url);
  10327. // set in bin/vite.js
  10328. const filter = process.env.VITE_DEBUG_FILTER;
  10329. const DEBUG = process.env.DEBUG;
  10330. function createDebugger(namespace, options = {}) {
  10331. const log = debug$g(namespace);
  10332. const { onlyWhenFocused } = options;
  10333. let enabled = log.enabled;
  10334. if (enabled && onlyWhenFocused) {
  10335. const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace;
  10336. enabled = !!DEBUG?.includes(ns);
  10337. }
  10338. if (enabled) {
  10339. return (...args) => {
  10340. if (!filter || args.some((a) => a?.includes?.(filter))) {
  10341. log(...args);
  10342. }
  10343. };
  10344. }
  10345. }
  10346. function testCaseInsensitiveFS() {
  10347. if (!CLIENT_ENTRY.endsWith('client.mjs')) {
  10348. throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`);
  10349. }
  10350. if (!fs$l.existsSync(CLIENT_ENTRY)) {
  10351. throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' +
  10352. CLIENT_ENTRY);
  10353. }
  10354. return fs$l.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'));
  10355. }
  10356. function isUrl(path) {
  10357. try {
  10358. new URL$3(path);
  10359. return true;
  10360. }
  10361. catch {
  10362. return false;
  10363. }
  10364. }
  10365. const isCaseInsensitiveFS = testCaseInsensitiveFS();
  10366. const isWindows$4 = os$3.platform() === 'win32';
  10367. const VOLUME_RE = /^[A-Z]:/i;
  10368. function normalizePath$3(id) {
  10369. return path$o.posix.normalize(isWindows$4 ? slash$1(id) : id);
  10370. }
  10371. function fsPathFromId(id) {
  10372. const fsPath = normalizePath$3(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
  10373. return fsPath[0] === '/' || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`;
  10374. }
  10375. function fsPathFromUrl(url) {
  10376. return fsPathFromId(cleanUrl(url));
  10377. }
  10378. /**
  10379. * Check if dir is a parent of file
  10380. *
  10381. * Warning: parameters are not validated, only works with normalized absolute paths
  10382. *
  10383. * @param dir - normalized absolute path
  10384. * @param file - normalized absolute path
  10385. * @returns true if dir is a parent of file
  10386. */
  10387. function isParentDirectory(dir, file) {
  10388. if (dir[dir.length - 1] !== '/') {
  10389. dir = `${dir}/`;
  10390. }
  10391. return (file.startsWith(dir) ||
  10392. (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
  10393. }
  10394. const queryRE = /\?.*$/s;
  10395. const postfixRE = /[?#].*$/s;
  10396. function cleanUrl(url) {
  10397. return url.replace(postfixRE, '');
  10398. }
  10399. const externalRE = /^(https?:)?\/\//;
  10400. const isExternalUrl = (url) => externalRE.test(url);
  10401. const dataUrlRE = /^\s*data:/i;
  10402. const isDataUrl = (url) => dataUrlRE.test(url);
  10403. const virtualModuleRE = /^virtual-module:.*/;
  10404. const virtualModulePrefix = 'virtual-module:';
  10405. const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba)(?:$|\?)/;
  10406. const isJSRequest = (url) => {
  10407. url = cleanUrl(url);
  10408. if (knownJsSrcRE.test(url)) {
  10409. return true;
  10410. }
  10411. if (!path$o.extname(url) && url[url.length - 1] !== '/') {
  10412. return true;
  10413. }
  10414. return false;
  10415. };
  10416. const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/;
  10417. const isTsRequest = (url) => knownTsRE.test(url);
  10418. const importQueryRE = /(\?|&)import=?(?:&|$)/;
  10419. const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
  10420. const internalPrefixes = [
  10421. FS_PREFIX,
  10422. VALID_ID_PREFIX,
  10423. CLIENT_PUBLIC_PATH,
  10424. ENV_PUBLIC_PATH,
  10425. ];
  10426. const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`);
  10427. const trailingSeparatorRE = /[?&]$/;
  10428. const isImportRequest = (url) => importQueryRE.test(url);
  10429. const isInternalRequest = (url) => InternalPrefixRE.test(url);
  10430. function removeImportQuery(url) {
  10431. return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, '');
  10432. }
  10433. function removeDirectQuery(url) {
  10434. return url.replace(directRequestRE$1, '$1').replace(trailingSeparatorRE, '');
  10435. }
  10436. const replacePercentageRE = /%/g;
  10437. function injectQuery(url, queryToInject) {
  10438. // encode percents for consistent behavior with pathToFileURL
  10439. // see #2614 for details
  10440. const resolvedUrl = new URL$3(url.replace(replacePercentageRE, '%25'), 'relative:///');
  10441. const { search, hash } = resolvedUrl;
  10442. let pathname = cleanUrl(url);
  10443. pathname = isWindows$4 ? slash$1(pathname) : pathname;
  10444. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash ?? ''}`;
  10445. }
  10446. const timestampRE = /\bt=\d{13}&?\b/;
  10447. function removeTimestampQuery(url) {
  10448. return url.replace(timestampRE, '').replace(trailingSeparatorRE, '');
  10449. }
  10450. async function asyncReplace(input, re, replacer) {
  10451. let match;
  10452. let remaining = input;
  10453. let rewritten = '';
  10454. while ((match = re.exec(remaining))) {
  10455. rewritten += remaining.slice(0, match.index);
  10456. rewritten += await replacer(match);
  10457. remaining = remaining.slice(match.index + match[0].length);
  10458. }
  10459. rewritten += remaining;
  10460. return rewritten;
  10461. }
  10462. function timeFrom(start, subtract = 0) {
  10463. const time = performance$1.now() - start - subtract;
  10464. const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' ');
  10465. if (time < 10) {
  10466. return colors$1.green(timeString);
  10467. }
  10468. else if (time < 50) {
  10469. return colors$1.yellow(timeString);
  10470. }
  10471. else {
  10472. return colors$1.red(timeString);
  10473. }
  10474. }
  10475. /**
  10476. * pretty url for logging.
  10477. */
  10478. function prettifyUrl(url, root) {
  10479. url = removeTimestampQuery(url);
  10480. const isAbsoluteFile = url.startsWith(root);
  10481. if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
  10482. const file = path$o.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
  10483. return colors$1.dim(file);
  10484. }
  10485. else {
  10486. return colors$1.dim(url);
  10487. }
  10488. }
  10489. function isObject$2(value) {
  10490. return Object.prototype.toString.call(value) === '[object Object]';
  10491. }
  10492. function isDefined(value) {
  10493. return value != null;
  10494. }
  10495. function tryStatSync(file) {
  10496. try {
  10497. return fs$l.statSync(file, { throwIfNoEntry: false });
  10498. }
  10499. catch {
  10500. // Ignore errors
  10501. }
  10502. }
  10503. function lookupFile(dir, fileNames) {
  10504. while (dir) {
  10505. for (const fileName of fileNames) {
  10506. const fullPath = path$o.join(dir, fileName);
  10507. if (tryStatSync(fullPath)?.isFile())
  10508. return fullPath;
  10509. }
  10510. const parentDir = path$o.dirname(dir);
  10511. if (parentDir === dir)
  10512. return;
  10513. dir = parentDir;
  10514. }
  10515. }
  10516. const splitRE = /\r?\n/;
  10517. const range = 2;
  10518. function pad$1(source, n = 2) {
  10519. const lines = source.split(splitRE);
  10520. return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
  10521. }
  10522. function posToNumber(source, pos) {
  10523. if (typeof pos === 'number')
  10524. return pos;
  10525. const lines = source.split(splitRE);
  10526. const { line, column } = pos;
  10527. let start = 0;
  10528. for (let i = 0; i < line - 1 && i < lines.length; i++) {
  10529. start += lines[i].length + 1;
  10530. }
  10531. return start + column;
  10532. }
  10533. function numberToPos(source, offset) {
  10534. if (typeof offset !== 'number')
  10535. return offset;
  10536. if (offset > source.length) {
  10537. throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
  10538. }
  10539. const lines = source.split(splitRE);
  10540. let counted = 0;
  10541. let line = 0;
  10542. let column = 0;
  10543. for (; line < lines.length; line++) {
  10544. const lineLength = lines[line].length + 1;
  10545. if (counted + lineLength >= offset) {
  10546. column = offset - counted + 1;
  10547. break;
  10548. }
  10549. counted += lineLength;
  10550. }
  10551. return { line: line + 1, column };
  10552. }
  10553. function generateCodeFrame(source, start = 0, end) {
  10554. start = posToNumber(source, start);
  10555. end = end || start;
  10556. const lines = source.split(splitRE);
  10557. let count = 0;
  10558. const res = [];
  10559. for (let i = 0; i < lines.length; i++) {
  10560. count += lines[i].length + 1;
  10561. if (count >= start) {
  10562. for (let j = i - range; j <= i + range || end > count; j++) {
  10563. if (j < 0 || j >= lines.length)
  10564. continue;
  10565. const line = j + 1;
  10566. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  10567. const lineLength = lines[j].length;
  10568. if (j === i) {
  10569. // push underline
  10570. const pad = Math.max(start - (count - lineLength) + 1, 0);
  10571. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  10572. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  10573. }
  10574. else if (j > i) {
  10575. if (end > count) {
  10576. const length = Math.max(Math.min(end - count, lineLength), 1);
  10577. res.push(` | ` + '^'.repeat(length));
  10578. }
  10579. count += lineLength + 1;
  10580. }
  10581. }
  10582. break;
  10583. }
  10584. }
  10585. return res.join('\n');
  10586. }
  10587. function isFileReadable(filename) {
  10588. try {
  10589. // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
  10590. if (!fs$l.statSync(filename, { throwIfNoEntry: false })) {
  10591. return false;
  10592. }
  10593. // Check if current process has read permission to the file
  10594. fs$l.accessSync(filename, fs$l.constants.R_OK);
  10595. return true;
  10596. }
  10597. catch {
  10598. return false;
  10599. }
  10600. }
  10601. const splitFirstDirRE = /(.+?)[\\/](.+)/;
  10602. /**
  10603. * Delete every file and subdirectory. **The given directory must exist.**
  10604. * Pass an optional `skip` array to preserve files under the root directory.
  10605. */
  10606. function emptyDir(dir, skip) {
  10607. const skipInDir = [];
  10608. let nested = null;
  10609. if (skip?.length) {
  10610. for (const file of skip) {
  10611. if (path$o.dirname(file) !== '.') {
  10612. const matched = file.match(splitFirstDirRE);
  10613. if (matched) {
  10614. nested ?? (nested = new Map());
  10615. const [, nestedDir, skipPath] = matched;
  10616. let nestedSkip = nested.get(nestedDir);
  10617. if (!nestedSkip) {
  10618. nestedSkip = [];
  10619. nested.set(nestedDir, nestedSkip);
  10620. }
  10621. if (!nestedSkip.includes(skipPath)) {
  10622. nestedSkip.push(skipPath);
  10623. }
  10624. }
  10625. }
  10626. else {
  10627. skipInDir.push(file);
  10628. }
  10629. }
  10630. }
  10631. for (const file of fs$l.readdirSync(dir)) {
  10632. if (skipInDir.includes(file)) {
  10633. continue;
  10634. }
  10635. if (nested?.has(file)) {
  10636. emptyDir(path$o.resolve(dir, file), nested.get(file));
  10637. }
  10638. else {
  10639. fs$l.rmSync(path$o.resolve(dir, file), { recursive: true, force: true });
  10640. }
  10641. }
  10642. }
  10643. function copyDir(srcDir, destDir) {
  10644. fs$l.mkdirSync(destDir, { recursive: true });
  10645. for (const file of fs$l.readdirSync(srcDir)) {
  10646. const srcFile = path$o.resolve(srcDir, file);
  10647. if (srcFile === destDir) {
  10648. continue;
  10649. }
  10650. const destFile = path$o.resolve(destDir, file);
  10651. const stat = fs$l.statSync(srcFile);
  10652. if (stat.isDirectory()) {
  10653. copyDir(srcFile, destFile);
  10654. }
  10655. else {
  10656. fs$l.copyFileSync(srcFile, destFile);
  10657. }
  10658. }
  10659. }
  10660. // `fs.realpathSync.native` resolves differently in Windows network drive,
  10661. // causing file read errors. skip for now.
  10662. // https://github.com/nodejs/node/issues/37737
  10663. let safeRealpathSync = isWindows$4
  10664. ? windowsSafeRealPathSync
  10665. : fs$l.realpathSync.native;
  10666. // Based on https://github.com/larrybahr/windows-network-drive
  10667. // MIT License, Copyright (c) 2017 Larry Bahr
  10668. const windowsNetworkMap = new Map();
  10669. function windowsMappedRealpathSync(path) {
  10670. const realPath = fs$l.realpathSync.native(path);
  10671. if (realPath.startsWith('\\\\')) {
  10672. for (const [network, volume] of windowsNetworkMap) {
  10673. if (realPath.startsWith(network))
  10674. return realPath.replace(network, volume);
  10675. }
  10676. }
  10677. return realPath;
  10678. }
  10679. const parseNetUseRE = /^(\w+)? +(\w:) +([^ ]+)\s/;
  10680. let firstSafeRealPathSyncRun = false;
  10681. function windowsSafeRealPathSync(path) {
  10682. if (!firstSafeRealPathSyncRun) {
  10683. optimizeSafeRealPathSync();
  10684. firstSafeRealPathSyncRun = true;
  10685. }
  10686. return fs$l.realpathSync(path);
  10687. }
  10688. function optimizeSafeRealPathSync() {
  10689. // Skip if using Node <16.18 due to MAX_PATH issue: https://github.com/vitejs/vite/issues/12931
  10690. const nodeVersion = process.versions.node.split('.').map(Number);
  10691. if (nodeVersion[0] < 16 || (nodeVersion[0] === 16 && nodeVersion[1] < 18)) {
  10692. safeRealpathSync = fs$l.realpathSync;
  10693. return;
  10694. }
  10695. exec('net use', (error, stdout) => {
  10696. if (error)
  10697. return;
  10698. const lines = stdout.split('\n');
  10699. // OK Y: \\NETWORKA\Foo Microsoft Windows Network
  10700. // OK Z: \\NETWORKA\Bar Microsoft Windows Network
  10701. for (const line of lines) {
  10702. const m = line.match(parseNetUseRE);
  10703. if (m)
  10704. windowsNetworkMap.set(m[3], m[2]);
  10705. }
  10706. if (windowsNetworkMap.size === 0) {
  10707. safeRealpathSync = fs$l.realpathSync.native;
  10708. }
  10709. else {
  10710. safeRealpathSync = windowsMappedRealpathSync;
  10711. }
  10712. });
  10713. }
  10714. function ensureWatchedFile(watcher, file, root) {
  10715. if (file &&
  10716. // only need to watch if out of root
  10717. !file.startsWith(root + '/') &&
  10718. // some rollup plugins use null bytes for private resolved Ids
  10719. !file.includes('\0') &&
  10720. fs$l.existsSync(file)) {
  10721. // resolve file to normalized system path
  10722. watcher.add(path$o.resolve(file));
  10723. }
  10724. }
  10725. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  10726. const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/;
  10727. function reduceSrcset(ret) {
  10728. return ret.reduce((prev, { url, descriptor }, index) => {
  10729. descriptor ?? (descriptor = '');
  10730. return (prev +=
  10731. url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`);
  10732. }, '');
  10733. }
  10734. function splitSrcSetDescriptor(srcs) {
  10735. return splitSrcSet(srcs)
  10736. .map((s) => {
  10737. const src = s.replace(escapedSpaceCharacters, ' ').trim();
  10738. const [url] = imageSetUrlRE.exec(src) || [''];
  10739. return {
  10740. url,
  10741. descriptor: src?.slice(url.length).trim(),
  10742. };
  10743. })
  10744. .filter(({ url }) => !!url);
  10745. }
  10746. function processSrcSet(srcs, replacer) {
  10747. return Promise.all(splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({
  10748. url: await replacer({ url, descriptor }),
  10749. descriptor,
  10750. }))).then((ret) => reduceSrcset(ret));
  10751. }
  10752. function processSrcSetSync(srcs, replacer) {
  10753. return reduceSrcset(splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({
  10754. url: replacer({ url, descriptor }),
  10755. descriptor,
  10756. })));
  10757. }
  10758. const cleanSrcSetRE = /(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g;
  10759. function splitSrcSet(srcs) {
  10760. const parts = [];
  10761. // There could be a ',' inside of url(data:...), linear-gradient(...) or "data:..."
  10762. const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer);
  10763. let startIndex = 0;
  10764. let splitIndex;
  10765. do {
  10766. splitIndex = cleanedSrcs.indexOf(',', startIndex);
  10767. parts.push(srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined));
  10768. startIndex = splitIndex + 1;
  10769. } while (splitIndex !== -1);
  10770. return parts;
  10771. }
  10772. const windowsDriveRE = /^[A-Z]:/;
  10773. const replaceWindowsDriveRE = /^([A-Z]):\//;
  10774. const linuxAbsolutePathRE = /^\/[^/]/;
  10775. function escapeToLinuxLikePath(path) {
  10776. if (windowsDriveRE.test(path)) {
  10777. return path.replace(replaceWindowsDriveRE, '/windows/$1/');
  10778. }
  10779. if (linuxAbsolutePathRE.test(path)) {
  10780. return `/linux${path}`;
  10781. }
  10782. return path;
  10783. }
  10784. const revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
  10785. function unescapeToLinuxLikePath(path) {
  10786. if (path.startsWith('/linux/')) {
  10787. return path.slice('/linux'.length);
  10788. }
  10789. if (path.startsWith('/windows/')) {
  10790. return path.replace(revertWindowsDriveRE, '$1:/');
  10791. }
  10792. return path;
  10793. }
  10794. // based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221
  10795. const nullSourceMap = {
  10796. names: [],
  10797. sources: [],
  10798. mappings: '',
  10799. version: 3,
  10800. };
  10801. function combineSourcemaps(filename, sourcemapList, excludeContent = true) {
  10802. if (sourcemapList.length === 0 ||
  10803. sourcemapList.every((m) => m.sources.length === 0)) {
  10804. return { ...nullSourceMap };
  10805. }
  10806. // hack for parse broken with normalized absolute paths on windows (C:/path/to/something).
  10807. // escape them to linux like paths
  10808. // also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442)
  10809. sourcemapList = sourcemapList.map((sourcemap) => {
  10810. const newSourcemaps = { ...sourcemap };
  10811. newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null);
  10812. if (sourcemap.sourceRoot) {
  10813. newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
  10814. }
  10815. return newSourcemaps;
  10816. });
  10817. const escapedFilename = escapeToLinuxLikePath(filename);
  10818. // We don't declare type here so we can convert/fake/map as RawSourceMap
  10819. let map; //: SourceMap
  10820. let mapIndex = 1;
  10821. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined;
  10822. if (useArrayInterface) {
  10823. map = remapping(sourcemapList, () => null, excludeContent);
  10824. }
  10825. else {
  10826. map = remapping(sourcemapList[0], function loader(sourcefile) {
  10827. if (sourcefile === escapedFilename && sourcemapList[mapIndex]) {
  10828. return sourcemapList[mapIndex++];
  10829. }
  10830. else {
  10831. return null;
  10832. }
  10833. }, excludeContent);
  10834. }
  10835. if (!map.file) {
  10836. delete map.file;
  10837. }
  10838. // unescape the previous hack
  10839. map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source);
  10840. map.file = filename;
  10841. return map;
  10842. }
  10843. function unique(arr) {
  10844. return Array.from(new Set(arr));
  10845. }
  10846. /**
  10847. * Returns resolved localhost address when `dns.lookup` result differs from DNS
  10848. *
  10849. * `dns.lookup` result is same when defaultResultOrder is `verbatim`.
  10850. * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
  10851. * For example, when IPv6 is not supported on that machine/network.
  10852. */
  10853. async function getLocalhostAddressIfDiffersFromDNS() {
  10854. const [nodeResult, dnsResult] = await Promise.all([
  10855. promises.lookup('localhost'),
  10856. promises.lookup('localhost', { verbatim: true }),
  10857. ]);
  10858. const isSame = nodeResult.family === dnsResult.family &&
  10859. nodeResult.address === dnsResult.address;
  10860. return isSame ? undefined : nodeResult.address;
  10861. }
  10862. function diffDnsOrderChange(oldUrls, newUrls) {
  10863. return !(oldUrls === newUrls ||
  10864. (oldUrls &&
  10865. newUrls &&
  10866. arrayEqual(oldUrls.local, newUrls.local) &&
  10867. arrayEqual(oldUrls.network, newUrls.network)));
  10868. }
  10869. async function resolveHostname(optionsHost) {
  10870. let host;
  10871. if (optionsHost === undefined || optionsHost === false) {
  10872. // Use a secure default
  10873. host = 'localhost';
  10874. }
  10875. else if (optionsHost === true) {
  10876. // If passed --host in the CLI without arguments
  10877. host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
  10878. }
  10879. else {
  10880. host = optionsHost;
  10881. }
  10882. // Set host name to localhost when possible
  10883. let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host;
  10884. if (host === 'localhost') {
  10885. // See #8647 for more details.
  10886. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
  10887. if (localhostAddr) {
  10888. name = localhostAddr;
  10889. }
  10890. }
  10891. return { host, name };
  10892. }
  10893. async function resolveServerUrls(server, options, config) {
  10894. const address = server.address();
  10895. const isAddressInfo = (x) => x?.address;
  10896. if (!isAddressInfo(address)) {
  10897. return { local: [], network: [] };
  10898. }
  10899. const local = [];
  10900. const network = [];
  10901. const hostname = await resolveHostname(options.host);
  10902. const protocol = options.https ? 'https' : 'http';
  10903. const port = address.port;
  10904. const base = config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase;
  10905. if (hostname.host && loopbackHosts.has(hostname.host)) {
  10906. let hostnameName = hostname.name;
  10907. // ipv6 host
  10908. if (hostnameName.includes(':')) {
  10909. hostnameName = `[${hostnameName}]`;
  10910. }
  10911. local.push(`${protocol}://${hostnameName}:${port}${base}`);
  10912. }
  10913. else {
  10914. Object.values(os$3.networkInterfaces())
  10915. .flatMap((nInterface) => nInterface ?? [])
  10916. .filter((detail) => detail &&
  10917. detail.address &&
  10918. (detail.family === 'IPv4' ||
  10919. // @ts-expect-error Node 18.0 - 18.3 returns number
  10920. detail.family === 4))
  10921. .forEach((detail) => {
  10922. let host = detail.address.replace('127.0.0.1', hostname.name);
  10923. // ipv6 host
  10924. if (host.includes(':')) {
  10925. host = `[${host}]`;
  10926. }
  10927. const url = `${protocol}://${host}:${port}${base}`;
  10928. if (detail.address.includes('127.0.0.1')) {
  10929. local.push(url);
  10930. }
  10931. else {
  10932. network.push(url);
  10933. }
  10934. });
  10935. }
  10936. return { local, network };
  10937. }
  10938. function arraify(target) {
  10939. return Array.isArray(target) ? target : [target];
  10940. }
  10941. // Taken from https://stackoverflow.com/a/36328890
  10942. const multilineCommentsRE$1 = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
  10943. const singlelineCommentsRE$1 = /\/\/.*/g;
  10944. const requestQuerySplitRE = /\?(?!.*[/|}])/;
  10945. // @ts-expect-error jest only exists when running Jest
  10946. const usingDynamicImport = typeof jest === 'undefined';
  10947. /**
  10948. * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup.
  10949. *
  10950. * As a temporary workaround for Jest's lack of stable ESM support, we fallback to require
  10951. * if we're in a Jest environment.
  10952. * See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077
  10953. *
  10954. * @param file File path to import.
  10955. */
  10956. const dynamicImport = usingDynamicImport
  10957. ? new Function('file', 'return import(file)')
  10958. : _require$3;
  10959. function parseRequest(id) {
  10960. const [_, search] = id.split(requestQuerySplitRE, 2);
  10961. if (!search) {
  10962. return null;
  10963. }
  10964. return Object.fromEntries(new URLSearchParams(search));
  10965. }
  10966. const blankReplacer = (match) => ' '.repeat(match.length);
  10967. function getHash(text) {
  10968. return createHash$2('sha256').update(text).digest('hex').substring(0, 8);
  10969. }
  10970. const _dirname = path$o.dirname(fileURLToPath(import.meta.url));
  10971. const requireResolveFromRootWithFallback = (root, id) => {
  10972. // check existence first, so if the package is not found,
  10973. // it won't be cached by nodejs, since there isn't a way to invalidate them:
  10974. // https://github.com/nodejs/node/issues/44663
  10975. const found = resolvePackageData(id, root) || resolvePackageData(id, _dirname);
  10976. if (!found) {
  10977. const error = new Error(`${JSON.stringify(id)} not found.`);
  10978. error.code = 'MODULE_NOT_FOUND';
  10979. throw error;
  10980. }
  10981. // actually resolve
  10982. // Search in the root directory first, and fallback to the default require paths.
  10983. return _require$3.resolve(id, { paths: [root, _dirname] });
  10984. };
  10985. function emptyCssComments(raw) {
  10986. return raw.replace(multilineCommentsRE$1, (s) => ' '.repeat(s.length));
  10987. }
  10988. function removeComments(raw) {
  10989. return raw.replace(multilineCommentsRE$1, '').replace(singlelineCommentsRE$1, '');
  10990. }
  10991. function mergeConfigRecursively(defaults, overrides, rootPath) {
  10992. const merged = { ...defaults };
  10993. for (const key in overrides) {
  10994. const value = overrides[key];
  10995. if (value == null) {
  10996. continue;
  10997. }
  10998. const existing = merged[key];
  10999. if (existing == null) {
  11000. merged[key] = value;
  11001. continue;
  11002. }
  11003. // fields that require special handling
  11004. if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
  11005. merged[key] = mergeAlias(existing, value);
  11006. continue;
  11007. }
  11008. else if (key === 'assetsInclude' && rootPath === '') {
  11009. merged[key] = [].concat(existing, value);
  11010. continue;
  11011. }
  11012. else if (key === 'noExternal' &&
  11013. rootPath === 'ssr' &&
  11014. (existing === true || value === true)) {
  11015. merged[key] = true;
  11016. continue;
  11017. }
  11018. if (Array.isArray(existing) || Array.isArray(value)) {
  11019. merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])];
  11020. continue;
  11021. }
  11022. if (isObject$2(existing) && isObject$2(value)) {
  11023. merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
  11024. continue;
  11025. }
  11026. merged[key] = value;
  11027. }
  11028. return merged;
  11029. }
  11030. function mergeConfig(defaults, overrides, isRoot = true) {
  11031. return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.');
  11032. }
  11033. function mergeAlias(a, b) {
  11034. if (!a)
  11035. return b;
  11036. if (!b)
  11037. return a;
  11038. if (isObject$2(a) && isObject$2(b)) {
  11039. return { ...a, ...b };
  11040. }
  11041. // the order is flipped because the alias is resolved from top-down,
  11042. // where the later should have higher priority
  11043. return [...normalizeAlias(b), ...normalizeAlias(a)];
  11044. }
  11045. function normalizeAlias(o = []) {
  11046. return Array.isArray(o)
  11047. ? o.map(normalizeSingleAlias)
  11048. : Object.keys(o).map((find) => normalizeSingleAlias({
  11049. find,
  11050. replacement: o[find],
  11051. }));
  11052. }
  11053. // https://github.com/vitejs/vite/issues/1363
  11054. // work around https://github.com/rollup/plugins/issues/759
  11055. function normalizeSingleAlias({ find, replacement, customResolver, }) {
  11056. if (typeof find === 'string' &&
  11057. find[find.length - 1] === '/' &&
  11058. replacement[replacement.length - 1] === '/') {
  11059. find = find.slice(0, find.length - 1);
  11060. replacement = replacement.slice(0, replacement.length - 1);
  11061. }
  11062. const alias = {
  11063. find,
  11064. replacement,
  11065. };
  11066. if (customResolver) {
  11067. alias.customResolver = customResolver;
  11068. }
  11069. return alias;
  11070. }
  11071. /**
  11072. * Transforms transpiled code result where line numbers aren't altered,
  11073. * so we can skip sourcemap generation during dev
  11074. */
  11075. function transformStableResult(s, id, config) {
  11076. return {
  11077. code: s.toString(),
  11078. map: config.command === 'build' && config.build.sourcemap
  11079. ? s.generateMap({ hires: true, source: id })
  11080. : null,
  11081. };
  11082. }
  11083. async function asyncFlatten(arr) {
  11084. do {
  11085. arr = (await Promise.all(arr)).flat(Infinity);
  11086. } while (arr.some((v) => v?.then));
  11087. return arr;
  11088. }
  11089. // strip UTF-8 BOM
  11090. function stripBomTag(content) {
  11091. if (content.charCodeAt(0) === 0xfeff) {
  11092. return content.slice(1);
  11093. }
  11094. return content;
  11095. }
  11096. const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
  11097. /**
  11098. * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something)
  11099. * this function returns false for them but true for absolute paths (e.g. C:/something)
  11100. */
  11101. const isNonDriveRelativeAbsolutePath = (p) => {
  11102. if (!isWindows$4)
  11103. return p[0] === '/';
  11104. return windowsDrivePathPrefixRE.test(p);
  11105. };
  11106. /**
  11107. * Determine if a file is being requested with the correct case, to ensure
  11108. * consistent behaviour between dev and prod and across operating systems.
  11109. */
  11110. function shouldServeFile(filePath, root) {
  11111. // can skip case check on Linux
  11112. if (!isCaseInsensitiveFS)
  11113. return true;
  11114. return hasCorrectCase(filePath, root);
  11115. }
  11116. /**
  11117. * Note that we can't use realpath here, because we don't want to follow
  11118. * symlinks.
  11119. */
  11120. function hasCorrectCase(file, assets) {
  11121. if (file === assets)
  11122. return true;
  11123. const parent = path$o.dirname(file);
  11124. if (fs$l.readdirSync(parent).includes(path$o.basename(file))) {
  11125. return hasCorrectCase(parent, assets);
  11126. }
  11127. return false;
  11128. }
  11129. function joinUrlSegments(a, b) {
  11130. if (!a || !b) {
  11131. return a || b || '';
  11132. }
  11133. if (a[a.length - 1] === '/') {
  11134. a = a.substring(0, a.length - 1);
  11135. }
  11136. if (b[0] !== '/') {
  11137. b = '/' + b;
  11138. }
  11139. return a + b;
  11140. }
  11141. function removeLeadingSlash(str) {
  11142. return str[0] === '/' ? str.slice(1) : str;
  11143. }
  11144. function stripBase(path, base) {
  11145. if (path === base) {
  11146. return '/';
  11147. }
  11148. const devBase = base[base.length - 1] === '/' ? base : base + '/';
  11149. return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
  11150. }
  11151. function arrayEqual(a, b) {
  11152. if (a === b)
  11153. return true;
  11154. if (a.length !== b.length)
  11155. return false;
  11156. for (let i = 0; i < a.length; i++) {
  11157. if (a[i] !== b[i])
  11158. return false;
  11159. }
  11160. return true;
  11161. }
  11162. function evalValue(rawValue) {
  11163. const fn = new Function(`
  11164. var console, exports, global, module, process, require
  11165. return (\n${rawValue}\n)
  11166. `);
  11167. return fn();
  11168. }
  11169. const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
  11170. function escapeRegex(str) {
  11171. return str.replace(escapeRegexRE, '\\$&');
  11172. }
  11173. /* eslint no-console: 0 */
  11174. const LogLevels = {
  11175. silent: 0,
  11176. error: 1,
  11177. warn: 2,
  11178. info: 3,
  11179. };
  11180. let lastType;
  11181. let lastMsg;
  11182. let sameCount = 0;
  11183. function clearScreen() {
  11184. const repeatCount = process.stdout.rows - 2;
  11185. const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : '';
  11186. console.log(blank);
  11187. readline.cursorTo(process.stdout, 0, 0);
  11188. readline.clearScreenDown(process.stdout);
  11189. }
  11190. function createLogger(level = 'info', options = {}) {
  11191. if (options.customLogger) {
  11192. return options.customLogger;
  11193. }
  11194. const loggedErrors = new WeakSet();
  11195. const { prefix = '[vite]', allowClearScreen = true } = options;
  11196. const thresh = LogLevels[level];
  11197. const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  11198. const clear = canClearScreen ? clearScreen : () => { };
  11199. function output(type, msg, options = {}) {
  11200. if (thresh >= LogLevels[type]) {
  11201. const method = type === 'info' ? 'log' : type;
  11202. const format = () => {
  11203. if (options.timestamp) {
  11204. const tag = type === 'info'
  11205. ? colors$1.cyan(colors$1.bold(prefix))
  11206. : type === 'warn'
  11207. ? colors$1.yellow(colors$1.bold(prefix))
  11208. : colors$1.red(colors$1.bold(prefix));
  11209. return `${colors$1.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`;
  11210. }
  11211. else {
  11212. return msg;
  11213. }
  11214. };
  11215. if (options.error) {
  11216. loggedErrors.add(options.error);
  11217. }
  11218. if (canClearScreen) {
  11219. if (type === lastType && msg === lastMsg) {
  11220. sameCount++;
  11221. clear();
  11222. console[method](format(), colors$1.yellow(`(x${sameCount + 1})`));
  11223. }
  11224. else {
  11225. sameCount = 0;
  11226. lastMsg = msg;
  11227. lastType = type;
  11228. if (options.clear) {
  11229. clear();
  11230. }
  11231. console[method](format());
  11232. }
  11233. }
  11234. else {
  11235. console[method](format());
  11236. }
  11237. }
  11238. }
  11239. const warnedMessages = new Set();
  11240. const logger = {
  11241. hasWarned: false,
  11242. info(msg, opts) {
  11243. output('info', msg, opts);
  11244. },
  11245. warn(msg, opts) {
  11246. logger.hasWarned = true;
  11247. output('warn', msg, opts);
  11248. },
  11249. warnOnce(msg, opts) {
  11250. if (warnedMessages.has(msg))
  11251. return;
  11252. logger.hasWarned = true;
  11253. output('warn', msg, opts);
  11254. warnedMessages.add(msg);
  11255. },
  11256. error(msg, opts) {
  11257. logger.hasWarned = true;
  11258. output('error', msg, opts);
  11259. },
  11260. clearScreen(type) {
  11261. if (thresh >= LogLevels[type]) {
  11262. clear();
  11263. }
  11264. },
  11265. hasErrorLogged(error) {
  11266. return loggedErrors.has(error);
  11267. },
  11268. };
  11269. return logger;
  11270. }
  11271. function printServerUrls(urls, optionsHost, info) {
  11272. const colorUrl = (url) => colors$1.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors$1.bold(port)}/`));
  11273. for (const url of urls.local) {
  11274. info(` ${colors$1.green('➜')} ${colors$1.bold('Local')}: ${colorUrl(url)}`);
  11275. }
  11276. for (const url of urls.network) {
  11277. info(` ${colors$1.green('➜')} ${colors$1.bold('Network')}: ${colorUrl(url)}`);
  11278. }
  11279. if (urls.network.length === 0 && optionsHost === undefined) {
  11280. info(colors$1.dim(` ${colors$1.green('➜')} ${colors$1.bold('Network')}: use `) +
  11281. colors$1.bold('--host') +
  11282. colors$1.dim(' to expose'));
  11283. }
  11284. }
  11285. const groups = [
  11286. { name: 'Assets', color: colors$1.green },
  11287. { name: 'CSS', color: colors$1.magenta },
  11288. { name: 'JS', color: colors$1.cyan },
  11289. ];
  11290. const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/;
  11291. function buildReporterPlugin(config) {
  11292. const compress = promisify$4(gzip);
  11293. const chunkLimit = config.build.chunkSizeWarningLimit;
  11294. const tty = process.stdout.isTTY && !process.env.CI;
  11295. const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info;
  11296. let hasTransformed = false;
  11297. let hasRenderedChunk = false;
  11298. let hasCompressChunk = false;
  11299. let transformedCount = 0;
  11300. let chunkCount = 0;
  11301. let compressedCount = 0;
  11302. let startTime = Date.now();
  11303. async function getCompressedSize(code) {
  11304. if (config.build.ssr || !config.build.reportCompressedSize) {
  11305. return null;
  11306. }
  11307. if (shouldLogInfo && !hasCompressChunk) {
  11308. if (!tty) {
  11309. config.logger.info('computing gzip size...');
  11310. }
  11311. else {
  11312. writeLine('computing gzip size (0)...');
  11313. }
  11314. hasCompressChunk = true;
  11315. }
  11316. const compressed = await compress(typeof code === 'string' ? code : Buffer.from(code));
  11317. compressedCount++;
  11318. if (shouldLogInfo && tty) {
  11319. writeLine(`computing gzip size (${compressedCount})...`);
  11320. }
  11321. return compressed.length;
  11322. }
  11323. const logTransform = throttle((id) => {
  11324. writeLine(`transforming (${transformedCount}) ${colors$1.dim(path$o.relative(config.root, id))}`);
  11325. });
  11326. return {
  11327. name: 'vite:reporter',
  11328. transform(_, id) {
  11329. transformedCount++;
  11330. if (shouldLogInfo) {
  11331. if (!tty) {
  11332. if (!hasTransformed) {
  11333. config.logger.info(`transforming...`);
  11334. }
  11335. }
  11336. else {
  11337. if (id.includes(`?`))
  11338. return;
  11339. logTransform(id);
  11340. }
  11341. hasTransformed = true;
  11342. }
  11343. return null;
  11344. },
  11345. options() {
  11346. startTime = Date.now();
  11347. },
  11348. buildStart() {
  11349. transformedCount = 0;
  11350. },
  11351. buildEnd() {
  11352. if (shouldLogInfo) {
  11353. if (tty) {
  11354. process.stdout.clearLine(0);
  11355. process.stdout.cursorTo(0);
  11356. }
  11357. config.logger.info(`${colors$1.green(`✓`)} ${transformedCount} modules transformed.`);
  11358. }
  11359. },
  11360. renderStart() {
  11361. chunkCount = 0;
  11362. compressedCount = 0;
  11363. },
  11364. renderChunk() {
  11365. chunkCount++;
  11366. if (shouldLogInfo) {
  11367. if (!tty) {
  11368. if (!hasRenderedChunk) {
  11369. config.logger.info('rendering chunks...');
  11370. }
  11371. }
  11372. else {
  11373. writeLine(`rendering chunks (${chunkCount})...`);
  11374. }
  11375. hasRenderedChunk = true;
  11376. }
  11377. return null;
  11378. },
  11379. generateBundle() {
  11380. if (shouldLogInfo && tty)
  11381. clearLine();
  11382. },
  11383. async writeBundle({ dir: outDir }, output) {
  11384. let hasLargeChunks = false;
  11385. if (shouldLogInfo) {
  11386. const entries = (await Promise.all(Object.values(output).map(async (chunk) => {
  11387. if (chunk.type === 'chunk') {
  11388. return {
  11389. name: chunk.fileName,
  11390. group: 'JS',
  11391. size: chunk.code.length,
  11392. compressedSize: await getCompressedSize(chunk.code),
  11393. mapSize: chunk.map ? chunk.map.toString().length : null,
  11394. };
  11395. }
  11396. else {
  11397. if (chunk.fileName.endsWith('.map'))
  11398. return null;
  11399. const isCSS = chunk.fileName.endsWith('.css');
  11400. const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName);
  11401. return {
  11402. name: chunk.fileName,
  11403. group: isCSS ? 'CSS' : 'Assets',
  11404. size: chunk.source.length,
  11405. mapSize: null,
  11406. compressedSize: isCompressible
  11407. ? await getCompressedSize(chunk.source)
  11408. : null,
  11409. };
  11410. }
  11411. }))).filter(isDefined);
  11412. if (tty)
  11413. clearLine();
  11414. let longest = 0;
  11415. let biggestSize = 0;
  11416. let biggestMap = 0;
  11417. let biggestCompressSize = 0;
  11418. for (const entry of entries) {
  11419. if (entry.name.length > longest)
  11420. longest = entry.name.length;
  11421. if (entry.size > biggestSize)
  11422. biggestSize = entry.size;
  11423. if (entry.mapSize && entry.mapSize > biggestMap) {
  11424. biggestMap = entry.mapSize;
  11425. }
  11426. if (entry.compressedSize &&
  11427. entry.compressedSize > biggestCompressSize) {
  11428. biggestCompressSize = entry.compressedSize;
  11429. }
  11430. }
  11431. const sizePad = displaySize(biggestSize).length;
  11432. const mapPad = displaySize(biggestMap).length;
  11433. const compressPad = displaySize(biggestCompressSize).length;
  11434. const relativeOutDir = normalizePath$3(path$o.relative(config.root, path$o.resolve(config.root, outDir ?? config.build.outDir)));
  11435. const assetsDir = path$o.join(config.build.assetsDir, '/');
  11436. for (const group of groups) {
  11437. const filtered = entries.filter((e) => e.group === group.name);
  11438. if (!filtered.length)
  11439. continue;
  11440. for (const entry of filtered.sort((a, z) => a.size - z.size)) {
  11441. const isLarge = group.name === 'JS' && entry.size / 1000 > chunkLimit;
  11442. if (isLarge)
  11443. hasLargeChunks = true;
  11444. const sizeColor = isLarge ? colors$1.yellow : colors$1.dim;
  11445. let log = colors$1.dim(relativeOutDir + '/');
  11446. log +=
  11447. !config.build.lib && entry.name.startsWith(assetsDir)
  11448. ? colors$1.dim(assetsDir) +
  11449. group.color(entry.name
  11450. .slice(assetsDir.length)
  11451. .padEnd(longest + 2 - assetsDir.length))
  11452. : group.color(entry.name.padEnd(longest + 2));
  11453. log += colors$1.bold(sizeColor(displaySize(entry.size).padStart(sizePad)));
  11454. if (entry.compressedSize) {
  11455. log += colors$1.dim(` │ gzip: ${displaySize(entry.compressedSize).padStart(compressPad)}`);
  11456. }
  11457. if (entry.mapSize) {
  11458. log += colors$1.dim(` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`);
  11459. }
  11460. config.logger.info(log);
  11461. }
  11462. }
  11463. }
  11464. else {
  11465. hasLargeChunks = Object.values(output).some((chunk) => {
  11466. return chunk.type === 'chunk' && chunk.code.length / 1000 > chunkLimit;
  11467. });
  11468. }
  11469. if (hasLargeChunks &&
  11470. config.build.minify &&
  11471. !config.build.lib &&
  11472. !config.build.ssr) {
  11473. config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kBs after minification. Consider:\n` +
  11474. `- Using dynamic import() to code-split the application\n` +
  11475. `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` +
  11476. `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`));
  11477. }
  11478. },
  11479. closeBundle() {
  11480. if (shouldLogInfo && !config.build.watch) {
  11481. config.logger.info(`${colors$1.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`);
  11482. }
  11483. },
  11484. };
  11485. }
  11486. function writeLine(output) {
  11487. clearLine();
  11488. if (output.length < process.stdout.columns) {
  11489. process.stdout.write(output);
  11490. }
  11491. else {
  11492. process.stdout.write(output.substring(0, process.stdout.columns - 1));
  11493. }
  11494. }
  11495. function clearLine() {
  11496. process.stdout.clearLine(0);
  11497. process.stdout.cursorTo(0);
  11498. }
  11499. function throttle(fn) {
  11500. let timerHandle = null;
  11501. return (...args) => {
  11502. if (timerHandle)
  11503. return;
  11504. fn(...args);
  11505. timerHandle = setTimeout(() => {
  11506. timerHandle = null;
  11507. }, 100);
  11508. };
  11509. }
  11510. function displaySize(bytes) {
  11511. return `${(bytes / 1000).toLocaleString('en', {
  11512. maximumFractionDigits: 2,
  11513. minimumFractionDigits: 2,
  11514. })} kB`;
  11515. }
  11516. function displayTime(time) {
  11517. // display: {X}ms
  11518. if (time < 1000) {
  11519. return `${time}ms`;
  11520. }
  11521. time = time / 1000;
  11522. // display: {X}s
  11523. if (time < 60) {
  11524. return `${time.toFixed(2)}s`;
  11525. }
  11526. const mins = parseInt((time / 60).toString());
  11527. const seconds = time % 60;
  11528. // display: {X}m {Y}s
  11529. return `${mins}m${seconds < 1 ? '' : ` ${seconds.toFixed(0)}s`}`;
  11530. }
  11531. // src/find.ts
  11532. async function find(filename, options) {
  11533. let dir = require$$0$4.dirname(require$$0$4.resolve(filename));
  11534. const root = (options == null ? void 0 : options.root) ? require$$0$4.resolve(options.root) : null;
  11535. while (dir) {
  11536. const tsconfig = await tsconfigInDir(dir, options);
  11537. if (tsconfig) {
  11538. return tsconfig;
  11539. } else {
  11540. if (root === dir) {
  11541. break;
  11542. }
  11543. const parent = require$$0$4.dirname(dir);
  11544. if (parent === dir) {
  11545. break;
  11546. } else {
  11547. dir = parent;
  11548. }
  11549. }
  11550. }
  11551. throw new Error(`no tsconfig file found for ${filename}`);
  11552. }
  11553. async function tsconfigInDir(dir, options) {
  11554. const tsconfig = require$$0$4.join(dir, "tsconfig.json");
  11555. if (options == null ? void 0 : options.tsConfigPaths) {
  11556. return options.tsConfigPaths.has(tsconfig) ? tsconfig : void 0;
  11557. }
  11558. try {
  11559. const stat = await promises$1.stat(tsconfig);
  11560. if (stat.isFile() || stat.isFIFO()) {
  11561. return tsconfig;
  11562. }
  11563. } catch (e) {
  11564. if (e.code !== "ENOENT") {
  11565. throw e;
  11566. }
  11567. }
  11568. }
  11569. var sep = require$$0$4.sep;
  11570. async function findAll(dir, options) {
  11571. const state = {
  11572. files: [],
  11573. calls: 0,
  11574. skip: options == null ? void 0 : options.skip,
  11575. err: false
  11576. };
  11577. return new Promise((resolve, reject) => {
  11578. walk$3(require$$0$4.resolve(dir), state, (err, files) => err ? reject(err) : resolve(files));
  11579. });
  11580. }
  11581. function walk$3(dir, state, done) {
  11582. if (state.err) {
  11583. return;
  11584. }
  11585. state.calls++;
  11586. readdir$4(dir, { withFileTypes: true }, (err, entries = []) => {
  11587. var _a;
  11588. if (state.err) {
  11589. return;
  11590. }
  11591. if (err && !(err.code === "ENOENT" || err.code === "EACCES")) {
  11592. state.err = true;
  11593. done(err);
  11594. } else {
  11595. for (const ent of entries) {
  11596. if (ent.isDirectory() && !((_a = state.skip) == null ? void 0 : _a.call(state, ent.name))) {
  11597. walk$3(`${dir}${sep}${ent.name}`, state, done);
  11598. } else if (ent.isFile() && ent.name === "tsconfig.json") {
  11599. state.files.push(`${dir}${sep}tsconfig.json`);
  11600. }
  11601. }
  11602. if (--state.calls === 0) {
  11603. if (!state.err) {
  11604. done(null, state.files);
  11605. }
  11606. }
  11607. }
  11608. });
  11609. }
  11610. // src/to-json.ts
  11611. function toJson(tsconfigJson) {
  11612. const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
  11613. if (stripped.trim() === "") {
  11614. return "{}";
  11615. } else {
  11616. return stripped;
  11617. }
  11618. }
  11619. function stripDanglingComma(pseudoJson) {
  11620. let insideString = false;
  11621. let offset = 0;
  11622. let result = "";
  11623. let danglingCommaPos = null;
  11624. for (let i = 0; i < pseudoJson.length; i++) {
  11625. const currentCharacter = pseudoJson[i];
  11626. if (currentCharacter === '"') {
  11627. const escaped = isEscaped(pseudoJson, i);
  11628. if (!escaped) {
  11629. insideString = !insideString;
  11630. }
  11631. }
  11632. if (insideString) {
  11633. danglingCommaPos = null;
  11634. continue;
  11635. }
  11636. if (currentCharacter === ",") {
  11637. danglingCommaPos = i;
  11638. continue;
  11639. }
  11640. if (danglingCommaPos) {
  11641. if (currentCharacter === "}" || currentCharacter === "]") {
  11642. result += pseudoJson.slice(offset, danglingCommaPos) + " ";
  11643. offset = danglingCommaPos + 1;
  11644. danglingCommaPos = null;
  11645. } else if (!currentCharacter.match(/\s/)) {
  11646. danglingCommaPos = null;
  11647. }
  11648. }
  11649. }
  11650. return result + pseudoJson.substring(offset);
  11651. }
  11652. function isEscaped(jsonString, quotePosition) {
  11653. let index = quotePosition - 1;
  11654. let backslashCount = 0;
  11655. while (jsonString[index] === "\\") {
  11656. index -= 1;
  11657. backslashCount += 1;
  11658. }
  11659. return Boolean(backslashCount % 2);
  11660. }
  11661. function strip(string, start, end) {
  11662. return string.slice(start, end).replace(/\S/g, " ");
  11663. }
  11664. var singleComment = Symbol("singleComment");
  11665. var multiComment = Symbol("multiComment");
  11666. function stripJsonComments(jsonString) {
  11667. let isInsideString = false;
  11668. let isInsideComment = false;
  11669. let offset = 0;
  11670. let result = "";
  11671. for (let index = 0; index < jsonString.length; index++) {
  11672. const currentCharacter = jsonString[index];
  11673. const nextCharacter = jsonString[index + 1];
  11674. if (!isInsideComment && currentCharacter === '"') {
  11675. const escaped = isEscaped(jsonString, index);
  11676. if (!escaped) {
  11677. isInsideString = !isInsideString;
  11678. }
  11679. }
  11680. if (isInsideString) {
  11681. continue;
  11682. }
  11683. if (!isInsideComment && currentCharacter + nextCharacter === "//") {
  11684. result += jsonString.slice(offset, index);
  11685. offset = index;
  11686. isInsideComment = singleComment;
  11687. index++;
  11688. } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
  11689. index++;
  11690. isInsideComment = false;
  11691. result += strip(jsonString, offset, index);
  11692. offset = index;
  11693. } else if (isInsideComment === singleComment && currentCharacter === "\n") {
  11694. isInsideComment = false;
  11695. result += strip(jsonString, offset, index);
  11696. offset = index;
  11697. } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
  11698. result += jsonString.slice(offset, index);
  11699. offset = index;
  11700. isInsideComment = multiComment;
  11701. index++;
  11702. } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
  11703. index++;
  11704. isInsideComment = false;
  11705. result += strip(jsonString, offset, index + 1);
  11706. offset = index + 1;
  11707. }
  11708. }
  11709. return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
  11710. }
  11711. function stripBom(string) {
  11712. if (string.charCodeAt(0) === 65279) {
  11713. return string.slice(1);
  11714. }
  11715. return string;
  11716. }
  11717. var POSIX_SEP_RE = new RegExp("\\" + require$$0$4.posix.sep, "g");
  11718. var NATIVE_SEP_RE = new RegExp("\\" + require$$0$4.sep, "g");
  11719. var PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
  11720. var GLOB_ALL_PATTERN = `**/*`;
  11721. var DEFAULT_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
  11722. var DEFAULT_EXTENSIONS_RE_GROUP = `\\.(?:${DEFAULT_EXTENSIONS.map((ext) => ext.substring(1)).join(
  11723. "|"
  11724. )})`;
  11725. new Function("path", "return import(path).then(m => m.default)");
  11726. async function resolveTSConfig(filename) {
  11727. if (require$$0$4.extname(filename) !== ".json") {
  11728. return;
  11729. }
  11730. const tsconfig = require$$0$4.resolve(filename);
  11731. try {
  11732. const stat = await promises$1.stat(tsconfig);
  11733. if (stat.isFile() || stat.isFIFO()) {
  11734. return tsconfig;
  11735. }
  11736. } catch (e) {
  11737. if (e.code !== "ENOENT") {
  11738. throw e;
  11739. }
  11740. }
  11741. throw new Error(`no tsconfig file found for ${filename}`);
  11742. }
  11743. function posix2native(filename) {
  11744. return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.posix.sep) ? filename.replace(POSIX_SEP_RE, require$$0$4.sep) : filename;
  11745. }
  11746. function native2posix(filename) {
  11747. return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.sep) ? filename.replace(NATIVE_SEP_RE, require$$0$4.posix.sep) : filename;
  11748. }
  11749. function resolve2posix(dir, filename) {
  11750. if (require$$0$4.sep === require$$0$4.posix.sep) {
  11751. return dir ? require$$0$4.resolve(dir, filename) : require$$0$4.resolve(filename);
  11752. }
  11753. return native2posix(
  11754. dir ? require$$0$4.resolve(posix2native(dir), posix2native(filename)) : require$$0$4.resolve(posix2native(filename))
  11755. );
  11756. }
  11757. function resolveReferencedTSConfigFiles(result) {
  11758. const dir = require$$0$4.dirname(result.tsconfigFile);
  11759. return result.tsconfig.references.map((ref) => {
  11760. const refPath = ref.path.endsWith(".json") ? ref.path : require$$0$4.join(ref.path, "tsconfig.json");
  11761. return resolve2posix(dir, refPath);
  11762. });
  11763. }
  11764. function resolveSolutionTSConfig(filename, result) {
  11765. if (result.referenced && DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) {
  11766. const solutionTSConfig = result.referenced.find(
  11767. (referenced) => isIncluded(filename, referenced)
  11768. );
  11769. if (solutionTSConfig) {
  11770. return {
  11771. ...solutionTSConfig,
  11772. solution: result
  11773. };
  11774. }
  11775. }
  11776. return result;
  11777. }
  11778. function isIncluded(filename, result) {
  11779. const dir = native2posix(require$$0$4.dirname(result.tsconfigFile));
  11780. const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
  11781. const absoluteFilename = resolve2posix(null, filename);
  11782. if (files.includes(filename)) {
  11783. return true;
  11784. }
  11785. const isIncluded2 = isGlobMatch(
  11786. absoluteFilename,
  11787. dir,
  11788. result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN])
  11789. );
  11790. if (isIncluded2) {
  11791. const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || []);
  11792. return !isExcluded;
  11793. }
  11794. return false;
  11795. }
  11796. function isGlobMatch(filename, dir, patterns) {
  11797. return patterns.some((pattern) => {
  11798. let lastWildcardIndex = pattern.length;
  11799. let hasWildcard = false;
  11800. for (let i = pattern.length - 1; i > -1; i--) {
  11801. if (pattern[i] === "*" || pattern[i] === "?") {
  11802. lastWildcardIndex = i;
  11803. hasWildcard = true;
  11804. break;
  11805. }
  11806. }
  11807. if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) {
  11808. return false;
  11809. }
  11810. if (pattern.endsWith("*") && !DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext))) {
  11811. return false;
  11812. }
  11813. if (pattern === GLOB_ALL_PATTERN) {
  11814. return filename.startsWith(`${dir}/`);
  11815. }
  11816. const resolvedPattern = resolve2posix(dir, pattern);
  11817. let firstWildcardIndex = -1;
  11818. for (let i = 0; i < resolvedPattern.length; i++) {
  11819. if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
  11820. firstWildcardIndex = i;
  11821. hasWildcard = true;
  11822. break;
  11823. }
  11824. }
  11825. if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) {
  11826. return false;
  11827. }
  11828. if (!hasWildcard) {
  11829. return filename === resolvedPattern;
  11830. }
  11831. if (PATTERN_REGEX_CACHE.has(resolvedPattern)) {
  11832. return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
  11833. }
  11834. const regex = pattern2regex(resolvedPattern);
  11835. PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
  11836. return regex.test(filename);
  11837. });
  11838. }
  11839. function pattern2regex(resolvedPattern) {
  11840. let regexStr = "^";
  11841. for (let i = 0; i < resolvedPattern.length; i++) {
  11842. const char = resolvedPattern[i];
  11843. if (char === "?") {
  11844. regexStr += "[^\\/]";
  11845. continue;
  11846. }
  11847. if (char === "*") {
  11848. if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
  11849. i += 2;
  11850. regexStr += "(?:[^\\/]*\\/)*";
  11851. continue;
  11852. }
  11853. regexStr += "[^\\/]*";
  11854. continue;
  11855. }
  11856. if ("/.+^${}()|[]\\".includes(char)) {
  11857. regexStr += `\\`;
  11858. }
  11859. regexStr += char;
  11860. }
  11861. if (resolvedPattern.endsWith("*")) {
  11862. regexStr += DEFAULT_EXTENSIONS_RE_GROUP;
  11863. }
  11864. regexStr += "$";
  11865. return new RegExp(regexStr);
  11866. }
  11867. // src/parse.ts
  11868. async function parse$f(filename, options) {
  11869. const cache = options == null ? void 0 : options.cache;
  11870. if (cache == null ? void 0 : cache.has(filename)) {
  11871. return cache.get(filename);
  11872. }
  11873. let tsconfigFile;
  11874. if (options == null ? void 0 : options.resolveWithEmptyIfConfigNotFound) {
  11875. try {
  11876. tsconfigFile = await resolveTSConfig(filename) || await find(filename, options);
  11877. } catch (e) {
  11878. const notFoundResult = {
  11879. tsconfigFile: "no_tsconfig_file_found",
  11880. tsconfig: {}
  11881. };
  11882. cache == null ? void 0 : cache.set(filename, notFoundResult);
  11883. return notFoundResult;
  11884. }
  11885. } else {
  11886. tsconfigFile = await resolveTSConfig(filename) || await find(filename, options);
  11887. }
  11888. let result;
  11889. if (cache == null ? void 0 : cache.has(tsconfigFile)) {
  11890. result = cache.get(tsconfigFile);
  11891. } else {
  11892. result = await parseFile$1(tsconfigFile, cache);
  11893. await Promise.all([parseExtends(result, cache), parseReferences(result, cache)]);
  11894. cache == null ? void 0 : cache.set(tsconfigFile, result);
  11895. }
  11896. result = resolveSolutionTSConfig(filename, result);
  11897. cache == null ? void 0 : cache.set(filename, result);
  11898. return result;
  11899. }
  11900. async function parseFile$1(tsconfigFile, cache) {
  11901. if (cache == null ? void 0 : cache.has(tsconfigFile)) {
  11902. return cache.get(tsconfigFile);
  11903. }
  11904. try {
  11905. const tsconfigJson = await promises$1.readFile(tsconfigFile, "utf-8");
  11906. const json = toJson(tsconfigJson);
  11907. const result = {
  11908. tsconfigFile,
  11909. tsconfig: normalizeTSConfig(JSON.parse(json), require$$0$4.dirname(tsconfigFile))
  11910. };
  11911. cache == null ? void 0 : cache.set(tsconfigFile, result);
  11912. return result;
  11913. } catch (e) {
  11914. throw new TSConfckParseError(
  11915. `parsing ${tsconfigFile} failed: ${e}`,
  11916. "PARSE_FILE",
  11917. tsconfigFile,
  11918. e
  11919. );
  11920. }
  11921. }
  11922. function normalizeTSConfig(tsconfig, dir) {
  11923. var _a;
  11924. if (((_a = tsconfig.compilerOptions) == null ? void 0 : _a.baseUrl) && !require$$0$4.isAbsolute(tsconfig.compilerOptions.baseUrl)) {
  11925. tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl);
  11926. }
  11927. return tsconfig;
  11928. }
  11929. async function parseReferences(result, cache) {
  11930. if (!result.tsconfig.references) {
  11931. return;
  11932. }
  11933. const referencedFiles = resolveReferencedTSConfigFiles(result);
  11934. const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, cache)));
  11935. await Promise.all(referenced.map((ref) => parseExtends(ref, cache)));
  11936. result.referenced = referenced;
  11937. }
  11938. async function parseExtends(result, cache) {
  11939. if (!result.tsconfig.extends) {
  11940. return;
  11941. }
  11942. const extended = [
  11943. { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }
  11944. ];
  11945. let pos = 0;
  11946. const extendsPath = [];
  11947. let currentBranchDepth = 0;
  11948. while (pos < extended.length) {
  11949. const extending = extended[pos];
  11950. extendsPath.push(extending.tsconfigFile);
  11951. if (extending.tsconfig.extends) {
  11952. currentBranchDepth += 1;
  11953. let resolvedExtends;
  11954. if (!Array.isArray(extending.tsconfig.extends)) {
  11955. resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
  11956. } else {
  11957. resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile));
  11958. }
  11959. const circularExtends = resolvedExtends.find(
  11960. (tsconfigFile) => extendsPath.includes(tsconfigFile)
  11961. );
  11962. if (circularExtends) {
  11963. const circle = extendsPath.concat([circularExtends]).join(" -> ");
  11964. throw new TSConfckParseError(
  11965. `Circular dependency in "extends": ${circle}`,
  11966. "EXTENDS_CIRCULAR",
  11967. result.tsconfigFile
  11968. );
  11969. }
  11970. extended.splice(
  11971. pos + 1,
  11972. 0,
  11973. ...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache)))
  11974. );
  11975. } else {
  11976. extendsPath.splice(-currentBranchDepth);
  11977. currentBranchDepth = 0;
  11978. }
  11979. pos = pos + 1;
  11980. }
  11981. result.extended = extended;
  11982. for (const ext of result.extended.slice(1)) {
  11983. extendTSConfig(result, ext);
  11984. }
  11985. }
  11986. function resolveExtends(extended, from) {
  11987. let error;
  11988. try {
  11989. return createRequire$2(from).resolve(extended);
  11990. } catch (e) {
  11991. error = e;
  11992. }
  11993. if (!require$$0$4.isAbsolute(extended) && !extended.startsWith("./") && !extended.startsWith("../")) {
  11994. try {
  11995. const fallbackExtended = require$$0$4.join(extended, "tsconfig.json");
  11996. return createRequire$2(from).resolve(fallbackExtended);
  11997. } catch (e) {
  11998. error = e;
  11999. }
  12000. }
  12001. throw new TSConfckParseError(
  12002. `failed to resolve "extends":"${extended}" in ${from}`,
  12003. "EXTENDS_RESOLVE",
  12004. from,
  12005. error
  12006. );
  12007. }
  12008. var EXTENDABLE_KEYS = [
  12009. "compilerOptions",
  12010. "files",
  12011. "include",
  12012. "exclude",
  12013. "watchOptions",
  12014. "compileOnSave",
  12015. "typeAcquisition",
  12016. "buildOptions"
  12017. ];
  12018. function extendTSConfig(extending, extended) {
  12019. const extendingConfig = extending.tsconfig;
  12020. const extendedConfig = extended.tsconfig;
  12021. const relativePath = native2posix(
  12022. require$$0$4.relative(require$$0$4.dirname(extending.tsconfigFile), require$$0$4.dirname(extended.tsconfigFile))
  12023. );
  12024. for (const key of Object.keys(extendedConfig).filter((key2) => EXTENDABLE_KEYS.includes(key2))) {
  12025. if (key === "compilerOptions") {
  12026. if (!extendingConfig.compilerOptions) {
  12027. extendingConfig.compilerOptions = {};
  12028. }
  12029. for (const option of Object.keys(extendedConfig.compilerOptions)) {
  12030. if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) {
  12031. continue;
  12032. }
  12033. extendingConfig.compilerOptions[option] = rebaseRelative(
  12034. option,
  12035. extendedConfig.compilerOptions[option],
  12036. relativePath
  12037. );
  12038. }
  12039. } else if (extendingConfig[key] === void 0) {
  12040. if (key === "watchOptions") {
  12041. extendingConfig.watchOptions = {};
  12042. for (const option of Object.keys(extendedConfig.watchOptions)) {
  12043. extendingConfig.watchOptions[option] = rebaseRelative(
  12044. option,
  12045. extendedConfig.watchOptions[option],
  12046. relativePath
  12047. );
  12048. }
  12049. } else {
  12050. extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
  12051. }
  12052. }
  12053. }
  12054. }
  12055. var REBASE_KEYS = [
  12056. // root
  12057. "files",
  12058. "include",
  12059. "exclude",
  12060. // compilerOptions
  12061. "baseUrl",
  12062. "rootDir",
  12063. "rootDirs",
  12064. "typeRoots",
  12065. "outDir",
  12066. "outFile",
  12067. "declarationDir",
  12068. // watchOptions
  12069. "excludeDirectories",
  12070. "excludeFiles"
  12071. ];
  12072. function rebaseRelative(key, value, prependPath) {
  12073. if (!REBASE_KEYS.includes(key)) {
  12074. return value;
  12075. }
  12076. if (Array.isArray(value)) {
  12077. return value.map((x) => rebasePath(x, prependPath));
  12078. } else {
  12079. return rebasePath(value, prependPath);
  12080. }
  12081. }
  12082. function rebasePath(value, prependPath) {
  12083. if (require$$0$4.isAbsolute(value)) {
  12084. return value;
  12085. } else {
  12086. return require$$0$4.posix.normalize(require$$0$4.posix.join(prependPath, value));
  12087. }
  12088. }
  12089. var TSConfckParseError = class extends Error {
  12090. constructor(message, code, tsconfigFile, cause) {
  12091. super(message);
  12092. Object.setPrototypeOf(this, TSConfckParseError.prototype);
  12093. this.name = TSConfckParseError.name;
  12094. this.code = code;
  12095. this.cause = cause;
  12096. this.tsconfigFile = tsconfigFile;
  12097. }
  12098. };
  12099. // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
  12100. const ROOT_FILES = [
  12101. // '.git',
  12102. // https://pnpm.io/workspaces/
  12103. 'pnpm-workspace.yaml',
  12104. // https://rushjs.io/pages/advanced/config_files/
  12105. // 'rush.json',
  12106. // https://nx.dev/latest/react/getting-started/nx-setup
  12107. // 'workspace.json',
  12108. // 'nx.json',
  12109. // https://github.com/lerna/lerna#lernajson
  12110. 'lerna.json',
  12111. ];
  12112. // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
  12113. // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
  12114. function hasWorkspacePackageJSON(root) {
  12115. const path = join$2(root, 'package.json');
  12116. if (!isFileReadable(path)) {
  12117. return false;
  12118. }
  12119. const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {};
  12120. return !!content.workspaces;
  12121. }
  12122. function hasRootFile(root) {
  12123. return ROOT_FILES.some((file) => fs$l.existsSync(join$2(root, file)));
  12124. }
  12125. function hasPackageJSON(root) {
  12126. const path = join$2(root, 'package.json');
  12127. return fs$l.existsSync(path);
  12128. }
  12129. /**
  12130. * Search up for the nearest `package.json`
  12131. */
  12132. function searchForPackageRoot(current, root = current) {
  12133. if (hasPackageJSON(current))
  12134. return current;
  12135. const dir = dirname$2(current);
  12136. // reach the fs root
  12137. if (!dir || dir === current)
  12138. return root;
  12139. return searchForPackageRoot(dir, root);
  12140. }
  12141. /**
  12142. * Search up for the nearest workspace root
  12143. */
  12144. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  12145. if (hasRootFile(current))
  12146. return current;
  12147. if (hasWorkspacePackageJSON(current))
  12148. return current;
  12149. const dir = dirname$2(current);
  12150. // reach the fs root
  12151. if (!dir || dir === current)
  12152. return root;
  12153. return searchForWorkspaceRoot(dir, root);
  12154. }
  12155. const debug$f = createDebugger('vite:esbuild');
  12156. const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{.*?"use strict";)/s;
  12157. const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{.*?"use strict";)/s;
  12158. const validExtensionRE = /\.\w+$/;
  12159. const jsxExtensionsRE = /\.(?:j|t)sx\b/;
  12160. let server;
  12161. async function transformWithEsbuild(code, filename, options, inMap) {
  12162. let loader = options?.loader;
  12163. if (!loader) {
  12164. // if the id ends with a valid ext, use it (e.g. vue blocks)
  12165. // otherwise, cleanup the query before checking the ext
  12166. const ext = path$o
  12167. .extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename))
  12168. .slice(1);
  12169. if (ext === 'cjs' || ext === 'mjs') {
  12170. loader = 'js';
  12171. }
  12172. else if (ext === 'cts' || ext === 'mts') {
  12173. loader = 'ts';
  12174. }
  12175. else {
  12176. loader = ext;
  12177. }
  12178. }
  12179. let tsconfigRaw = options?.tsconfigRaw;
  12180. // if options provide tsconfigRaw in string, it takes highest precedence
  12181. if (typeof tsconfigRaw !== 'string') {
  12182. // these fields would affect the compilation result
  12183. // https://esbuild.github.io/content-types/#tsconfig-json
  12184. const meaningfulFields = [
  12185. 'alwaysStrict',
  12186. 'importsNotUsedAsValues',
  12187. 'jsx',
  12188. 'jsxFactory',
  12189. 'jsxFragmentFactory',
  12190. 'jsxImportSource',
  12191. 'preserveValueImports',
  12192. 'target',
  12193. 'useDefineForClassFields',
  12194. ];
  12195. const compilerOptionsForFile = {};
  12196. if (loader === 'ts' || loader === 'tsx') {
  12197. const loadedTsconfig = await loadTsconfigJsonForFile(filename);
  12198. const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
  12199. for (const field of meaningfulFields) {
  12200. if (field in loadedCompilerOptions) {
  12201. // @ts-expect-error TypeScript can't tell they are of the same type
  12202. compilerOptionsForFile[field] = loadedCompilerOptions[field];
  12203. }
  12204. }
  12205. }
  12206. const compilerOptions = {
  12207. ...compilerOptionsForFile,
  12208. ...tsconfigRaw?.compilerOptions,
  12209. };
  12210. // esbuild derives `useDefineForClassFields` from `target` instead of `tsconfig.compilerOptions.target`
  12211. // https://github.com/evanw/esbuild/issues/2584
  12212. // but we want `useDefineForClassFields` to be derived from `tsconfig.compilerOptions.target`
  12213. if (compilerOptions.useDefineForClassFields === undefined) {
  12214. const lowercaseTarget = compilerOptions.target?.toLowerCase() ?? 'es3';
  12215. if (lowercaseTarget.startsWith('es')) {
  12216. const esVersion = lowercaseTarget.slice(2);
  12217. compilerOptions.useDefineForClassFields =
  12218. esVersion === 'next' || +esVersion >= 2022;
  12219. }
  12220. else {
  12221. compilerOptions.useDefineForClassFields = false;
  12222. }
  12223. }
  12224. // esbuild uses tsconfig fields when both the normal options and tsconfig was set
  12225. // but we want to prioritize the normal options
  12226. if (options) {
  12227. options.jsx && (compilerOptions.jsx = undefined);
  12228. options.jsxFactory && (compilerOptions.jsxFactory = undefined);
  12229. options.jsxFragment && (compilerOptions.jsxFragmentFactory = undefined);
  12230. options.jsxImportSource && (compilerOptions.jsxImportSource = undefined);
  12231. options.target && (compilerOptions.target = undefined);
  12232. }
  12233. tsconfigRaw = {
  12234. ...tsconfigRaw,
  12235. compilerOptions,
  12236. };
  12237. }
  12238. const resolvedOptions = {
  12239. sourcemap: true,
  12240. // ensure source file name contains full query
  12241. sourcefile: filename,
  12242. ...options,
  12243. loader,
  12244. tsconfigRaw,
  12245. };
  12246. // Some projects in the ecosystem are calling this function with an ESBuildOptions
  12247. // object and esbuild throws an error for extra fields
  12248. delete resolvedOptions.include;
  12249. delete resolvedOptions.exclude;
  12250. delete resolvedOptions.jsxInject;
  12251. try {
  12252. const result = await transform$2(code, resolvedOptions);
  12253. let map;
  12254. if (inMap && resolvedOptions.sourcemap) {
  12255. const nextMap = JSON.parse(result.map);
  12256. nextMap.sourcesContent = [];
  12257. map = combineSourcemaps(filename, [
  12258. nextMap,
  12259. inMap,
  12260. ]);
  12261. }
  12262. else {
  12263. map =
  12264. resolvedOptions.sourcemap && resolvedOptions.sourcemap !== 'inline'
  12265. ? JSON.parse(result.map)
  12266. : { mappings: '' };
  12267. }
  12268. return {
  12269. ...result,
  12270. map,
  12271. };
  12272. }
  12273. catch (e) {
  12274. debug$f?.(`esbuild error with options used: `, resolvedOptions);
  12275. // patch error information
  12276. if (e.errors) {
  12277. e.frame = '';
  12278. e.errors.forEach((m) => {
  12279. e.frame += `\n` + prettifyMessage(m, code);
  12280. });
  12281. e.loc = e.errors[0].location;
  12282. }
  12283. throw e;
  12284. }
  12285. }
  12286. function esbuildPlugin(config) {
  12287. const options = config.esbuild;
  12288. const { jsxInject, include, exclude, ...esbuildTransformOptions } = options;
  12289. const filter = createFilter(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
  12290. // Remove optimization options for dev as we only need to transpile them,
  12291. // and for build as the final optimization is in `buildEsbuildPlugin`
  12292. const transformOptions = {
  12293. target: 'esnext',
  12294. charset: 'utf8',
  12295. ...esbuildTransformOptions,
  12296. minify: false,
  12297. minifyIdentifiers: false,
  12298. minifySyntax: false,
  12299. minifyWhitespace: false,
  12300. treeShaking: false,
  12301. // keepNames is not needed when minify is disabled.
  12302. // Also transforming multiple times with keepNames enabled breaks
  12303. // tree-shaking. (#9164)
  12304. keepNames: false,
  12305. };
  12306. initTSConfck(config.root);
  12307. return {
  12308. name: 'vite:esbuild',
  12309. configureServer(_server) {
  12310. server = _server;
  12311. server.watcher
  12312. .on('add', reloadOnTsconfigChange)
  12313. .on('change', reloadOnTsconfigChange)
  12314. .on('unlink', reloadOnTsconfigChange);
  12315. },
  12316. buildEnd() {
  12317. // recycle serve to avoid preventing Node self-exit (#6815)
  12318. server = null;
  12319. },
  12320. async transform(code, id) {
  12321. if (filter(id) || filter(cleanUrl(id))) {
  12322. const result = await transformWithEsbuild(code, id, transformOptions);
  12323. if (result.warnings.length) {
  12324. result.warnings.forEach((m) => {
  12325. this.warn(prettifyMessage(m, code));
  12326. });
  12327. }
  12328. if (jsxInject && jsxExtensionsRE.test(id)) {
  12329. result.code = jsxInject + ';' + result.code;
  12330. }
  12331. return {
  12332. code: result.code,
  12333. map: result.map,
  12334. };
  12335. }
  12336. },
  12337. };
  12338. }
  12339. const rollupToEsbuildFormatMap = {
  12340. es: 'esm',
  12341. cjs: 'cjs',
  12342. // passing `var Lib = (() => {})()` to esbuild with format = "iife"
  12343. // will turn it to `(() => { var Lib = (() => {})() })()`,
  12344. // so we remove the format config to tell esbuild not doing this
  12345. //
  12346. // although esbuild doesn't change format, there is still possibility
  12347. // that `{ treeShaking: true }` removes a top-level no-side-effect variable
  12348. // like: `var Lib = 1`, which becomes `` after esbuild transforming,
  12349. // but thankfully rollup does not do this optimization now
  12350. iife: undefined,
  12351. };
  12352. const buildEsbuildPlugin = (config) => {
  12353. initTSConfck(config.root);
  12354. return {
  12355. name: 'vite:esbuild-transpile',
  12356. async renderChunk(code, chunk, opts) {
  12357. // @ts-expect-error injected by @vitejs/plugin-legacy
  12358. if (opts.__vite_skip_esbuild__) {
  12359. return null;
  12360. }
  12361. const options = resolveEsbuildTranspileOptions(config, opts.format);
  12362. if (!options) {
  12363. return null;
  12364. }
  12365. const res = await transformWithEsbuild(code, chunk.fileName, options);
  12366. if (config.build.lib) {
  12367. // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the
  12368. // names are minified potentially causing collision with other globals.
  12369. // We use a regex to inject the helpers inside the wrappers.
  12370. // We don't need to create a MagicString here because both the helpers and
  12371. // the headers don't modify the sourcemap
  12372. const injectHelpers = opts.format === 'umd'
  12373. ? INJECT_HELPERS_UMD_RE
  12374. : opts.format === 'iife'
  12375. ? INJECT_HELPERS_IIFE_RE
  12376. : undefined;
  12377. if (injectHelpers) {
  12378. res.code = res.code.replace(injectHelpers, (_, helpers, header) => header + helpers);
  12379. }
  12380. }
  12381. return res;
  12382. },
  12383. };
  12384. };
  12385. function resolveEsbuildTranspileOptions(config, format) {
  12386. const target = config.build.target;
  12387. const minify = config.build.minify === 'esbuild';
  12388. if ((!target || target === 'esnext') && !minify) {
  12389. return null;
  12390. }
  12391. // Do not minify whitespace for ES lib output since that would remove
  12392. // pure annotations and break tree-shaking
  12393. // https://github.com/vuejs/core/issues/2860#issuecomment-926882793
  12394. const isEsLibBuild = config.build.lib && format === 'es';
  12395. const esbuildOptions = config.esbuild || {};
  12396. const options = {
  12397. charset: 'utf8',
  12398. ...esbuildOptions,
  12399. target: target || undefined,
  12400. format: rollupToEsbuildFormatMap[format],
  12401. // the final build should always support dynamic import and import.meta.
  12402. // if they need to be polyfilled, plugin-legacy should be used.
  12403. // plugin-legacy detects these two features when checking for modern code.
  12404. supported: {
  12405. 'dynamic-import': true,
  12406. 'import-meta': true,
  12407. ...esbuildOptions.supported,
  12408. },
  12409. };
  12410. // If no minify, disable all minify options
  12411. if (!minify) {
  12412. return {
  12413. ...options,
  12414. minify: false,
  12415. minifyIdentifiers: false,
  12416. minifySyntax: false,
  12417. minifyWhitespace: false,
  12418. treeShaking: false,
  12419. };
  12420. }
  12421. // If user enable fine-grain minify options, minify with their options instead
  12422. if (options.minifyIdentifiers != null ||
  12423. options.minifySyntax != null ||
  12424. options.minifyWhitespace != null) {
  12425. if (isEsLibBuild) {
  12426. // Disable minify whitespace as it breaks tree-shaking
  12427. return {
  12428. ...options,
  12429. minify: false,
  12430. minifyIdentifiers: options.minifyIdentifiers ?? true,
  12431. minifySyntax: options.minifySyntax ?? true,
  12432. minifyWhitespace: false,
  12433. treeShaking: true,
  12434. };
  12435. }
  12436. else {
  12437. return {
  12438. ...options,
  12439. minify: false,
  12440. minifyIdentifiers: options.minifyIdentifiers ?? true,
  12441. minifySyntax: options.minifySyntax ?? true,
  12442. minifyWhitespace: options.minifyWhitespace ?? true,
  12443. treeShaking: true,
  12444. };
  12445. }
  12446. }
  12447. // Else apply default minify options
  12448. if (isEsLibBuild) {
  12449. // Minify all except whitespace as it breaks tree-shaking
  12450. return {
  12451. ...options,
  12452. minify: false,
  12453. minifyIdentifiers: true,
  12454. minifySyntax: true,
  12455. minifyWhitespace: false,
  12456. treeShaking: true,
  12457. };
  12458. }
  12459. else {
  12460. return {
  12461. ...options,
  12462. minify: true,
  12463. treeShaking: true,
  12464. };
  12465. }
  12466. }
  12467. function prettifyMessage(m, code) {
  12468. let res = colors$1.yellow(m.text);
  12469. if (m.location) {
  12470. const lines = code.split(/\r?\n/g);
  12471. const line = Number(m.location.line);
  12472. const column = Number(m.location.column);
  12473. const offset = lines
  12474. .slice(0, line - 1)
  12475. .map((l) => l.length)
  12476. .reduce((total, l) => total + l + 1, 0) + column;
  12477. res += `\n` + generateCodeFrame(code, offset, offset + 1);
  12478. }
  12479. return res + `\n`;
  12480. }
  12481. let tsconfckRoot;
  12482. let tsconfckParseOptions = { resolveWithEmptyIfConfigNotFound: true };
  12483. function initTSConfck(root, force = false) {
  12484. // bail if already cached
  12485. if (!force && root === tsconfckRoot)
  12486. return;
  12487. const workspaceRoot = searchForWorkspaceRoot(root);
  12488. tsconfckRoot = root;
  12489. tsconfckParseOptions = initTSConfckParseOptions(workspaceRoot);
  12490. // cached as the options value itself when promise is resolved
  12491. tsconfckParseOptions.then((options) => {
  12492. if (root === tsconfckRoot) {
  12493. tsconfckParseOptions = options;
  12494. }
  12495. });
  12496. }
  12497. async function initTSConfckParseOptions(workspaceRoot) {
  12498. const start = debug$f ? performance.now() : 0;
  12499. const options = {
  12500. cache: new Map(),
  12501. root: workspaceRoot,
  12502. tsConfigPaths: new Set(await findAll(workspaceRoot, {
  12503. skip: (dir) => dir === 'node_modules' || dir === '.git',
  12504. })),
  12505. resolveWithEmptyIfConfigNotFound: true,
  12506. };
  12507. debug$f?.(timeFrom(start), 'tsconfck init', colors$1.dim(workspaceRoot));
  12508. return options;
  12509. }
  12510. async function loadTsconfigJsonForFile(filename) {
  12511. try {
  12512. const result = await parse$f(filename, await tsconfckParseOptions);
  12513. // tsconfig could be out of root, make sure it is watched on dev
  12514. if (server && result.tsconfigFile !== 'no_tsconfig_file_found') {
  12515. ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root);
  12516. }
  12517. return result.tsconfig;
  12518. }
  12519. catch (e) {
  12520. if (e instanceof TSConfckParseError) {
  12521. // tsconfig could be out of root, make sure it is watched on dev
  12522. if (server && e.tsconfigFile) {
  12523. ensureWatchedFile(server.watcher, e.tsconfigFile, server.config.root);
  12524. }
  12525. }
  12526. throw e;
  12527. }
  12528. }
  12529. async function reloadOnTsconfigChange(changedFile) {
  12530. // server could be closed externally after a file change is detected
  12531. if (!server)
  12532. return;
  12533. // any tsconfig.json that's added in the workspace could be closer to a code file than a previously cached one
  12534. // any json file in the tsconfig cache could have been used to compile ts
  12535. if (path$o.basename(changedFile) === 'tsconfig.json' ||
  12536. (changedFile.endsWith('.json') &&
  12537. (await tsconfckParseOptions)?.cache?.has(changedFile))) {
  12538. server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
  12539. // clear module graph to remove code compiled with outdated config
  12540. server.moduleGraph.invalidateAll();
  12541. // reset tsconfck so that recompile works with up2date configs
  12542. initTSConfck(server.config.root, true);
  12543. // server may not be available if vite config is updated at the same time
  12544. if (server) {
  12545. // force full reload
  12546. server.ws.send({
  12547. type: 'full-reload',
  12548. path: '*',
  12549. });
  12550. }
  12551. }
  12552. }
  12553. var dist$1 = {};
  12554. var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  12555. return (mod && mod.__esModule) ? mod : { "default": mod };
  12556. };
  12557. Object.defineProperty(dist$1, "__esModule", { value: true });
  12558. var Worker_1 = dist$1.Worker = void 0;
  12559. const os_1 = __importDefault(require$$2);
  12560. const worker_threads_1 = require$$1;
  12561. class Worker {
  12562. constructor(fn, options = {}) {
  12563. this.code = genWorkerCode(fn);
  12564. this.max = options.max || Math.max(1, os_1.default.cpus().length - 1);
  12565. this.pool = [];
  12566. this.idlePool = [];
  12567. this.queue = [];
  12568. }
  12569. async run(...args) {
  12570. const worker = await this._getAvailableWorker();
  12571. return new Promise((resolve, reject) => {
  12572. worker.currentResolve = resolve;
  12573. worker.currentReject = reject;
  12574. worker.postMessage(args);
  12575. });
  12576. }
  12577. stop() {
  12578. this.pool.forEach((w) => w.unref());
  12579. this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.')));
  12580. this.pool = [];
  12581. this.idlePool = [];
  12582. this.queue = [];
  12583. }
  12584. async _getAvailableWorker() {
  12585. // has idle one?
  12586. if (this.idlePool.length) {
  12587. return this.idlePool.shift();
  12588. }
  12589. // can spawn more?
  12590. if (this.pool.length < this.max) {
  12591. const worker = new worker_threads_1.Worker(this.code, { eval: true });
  12592. worker.on('message', (res) => {
  12593. worker.currentResolve && worker.currentResolve(res);
  12594. worker.currentResolve = null;
  12595. this._assignDoneWorker(worker);
  12596. });
  12597. worker.on('error', (err) => {
  12598. worker.currentReject && worker.currentReject(err);
  12599. worker.currentReject = null;
  12600. });
  12601. worker.on('exit', (code) => {
  12602. const i = this.pool.indexOf(worker);
  12603. if (i > -1)
  12604. this.pool.splice(i, 1);
  12605. if (code !== 0 && worker.currentReject) {
  12606. worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`));
  12607. worker.currentReject = null;
  12608. }
  12609. });
  12610. this.pool.push(worker);
  12611. return worker;
  12612. }
  12613. // no one is available, we have to wait
  12614. let resolve;
  12615. let reject;
  12616. const onWorkerAvailablePromise = new Promise((r, rj) => {
  12617. resolve = r;
  12618. reject = rj;
  12619. });
  12620. this.queue.push([resolve, reject]);
  12621. return onWorkerAvailablePromise;
  12622. }
  12623. _assignDoneWorker(worker) {
  12624. // someone's waiting already?
  12625. if (this.queue.length) {
  12626. const [resolve] = this.queue.shift();
  12627. resolve(worker);
  12628. return;
  12629. }
  12630. // take a rest.
  12631. this.idlePool.push(worker);
  12632. }
  12633. }
  12634. Worker_1 = dist$1.Worker = Worker;
  12635. function genWorkerCode(fn) {
  12636. return `
  12637. const doWork = ${fn.toString()}
  12638. const { parentPort } = require('worker_threads')
  12639. parentPort.on('message', async (args) => {
  12640. const res = await doWork(...args)
  12641. parentPort.postMessage(res)
  12642. })
  12643. `;
  12644. }
  12645. let terserPath;
  12646. const loadTerserPath = (root) => {
  12647. if (terserPath)
  12648. return terserPath;
  12649. try {
  12650. terserPath = requireResolveFromRootWithFallback(root, 'terser');
  12651. }
  12652. catch (e) {
  12653. if (e.code === 'MODULE_NOT_FOUND') {
  12654. throw new Error('terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.');
  12655. }
  12656. else {
  12657. const message = new Error(`terser failed to load:\n${e.message}`);
  12658. message.stack = e.stack + '\n' + message.stack;
  12659. throw message;
  12660. }
  12661. }
  12662. return terserPath;
  12663. };
  12664. function terserPlugin(config) {
  12665. const makeWorker = () => new Worker_1(async (terserPath, code, options) => {
  12666. // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205
  12667. // eslint-disable-next-line no-restricted-globals -- this function runs inside cjs
  12668. const terser = require(terserPath);
  12669. return terser.minify(code, options);
  12670. });
  12671. let worker;
  12672. return {
  12673. name: 'vite:terser',
  12674. async renderChunk(code, _chunk, outputOptions) {
  12675. // This plugin is included for any non-false value of config.build.minify,
  12676. // so that normal chunks can use the preferred minifier, and legacy chunks
  12677. // can use terser.
  12678. if (config.build.minify !== 'terser' &&
  12679. // @ts-expect-error injected by @vitejs/plugin-legacy
  12680. !outputOptions.__vite_force_terser__) {
  12681. return null;
  12682. }
  12683. // Do not minify ES lib output since that would remove pure annotations
  12684. // and break tree-shaking.
  12685. if (config.build.lib && outputOptions.format === 'es') {
  12686. return null;
  12687. }
  12688. // Lazy load worker.
  12689. worker || (worker = makeWorker());
  12690. const terserPath = loadTerserPath(config.root);
  12691. const res = await worker.run(terserPath, code, {
  12692. safari10: true,
  12693. ...config.build.terserOptions,
  12694. sourceMap: !!outputOptions.sourcemap,
  12695. module: outputOptions.format.startsWith('es'),
  12696. toplevel: outputOptions.format === 'cjs',
  12697. });
  12698. return {
  12699. code: res.code,
  12700. map: res.map,
  12701. };
  12702. },
  12703. closeBundle() {
  12704. worker?.stop();
  12705. },
  12706. };
  12707. }
  12708. var json = JSON;
  12709. var isArray$1 = Array.isArray || function (x) {
  12710. return {}.toString.call(x) === '[object Array]';
  12711. };
  12712. var objectKeys = Object.keys || function (obj) {
  12713. var has = Object.prototype.hasOwnProperty || function () { return true; };
  12714. var keys = [];
  12715. for (var key in obj) {
  12716. if (has.call(obj, key)) { keys.push(key); }
  12717. }
  12718. return keys;
  12719. };
  12720. var jsonStableStringify = function (obj, opts) {
  12721. if (!opts) { opts = {}; }
  12722. if (typeof opts === 'function') { opts = { cmp: opts }; }
  12723. var space = opts.space || '';
  12724. if (typeof space === 'number') { space = Array(space + 1).join(' '); }
  12725. var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
  12726. var replacer = opts.replacer || function (key, value) { return value; };
  12727. var cmp = opts.cmp && (function (f) {
  12728. return function (node) {
  12729. return function (a, b) {
  12730. var aobj = { key: a, value: node[a] };
  12731. var bobj = { key: b, value: node[b] };
  12732. return f(aobj, bobj);
  12733. };
  12734. };
  12735. }(opts.cmp));
  12736. var seen = [];
  12737. return (function stringify(parent, key, node, level) {
  12738. var indent = space ? '\n' + new Array(level + 1).join(space) : '';
  12739. var colonSeparator = space ? ': ' : ':';
  12740. if (node && node.toJSON && typeof node.toJSON === 'function') {
  12741. node = node.toJSON();
  12742. }
  12743. node = replacer.call(parent, key, node);
  12744. if (node === undefined) {
  12745. return;
  12746. }
  12747. if (typeof node !== 'object' || node === null) {
  12748. return json.stringify(node);
  12749. }
  12750. if (isArray$1(node)) {
  12751. var out = [];
  12752. for (var i = 0; i < node.length; i++) {
  12753. var item = stringify(node, i, node[i], level + 1) || json.stringify(null);
  12754. out.push(indent + space + item);
  12755. }
  12756. return '[' + out.join(',') + indent + ']';
  12757. }
  12758. if (seen.indexOf(node) !== -1) {
  12759. if (cycles) { return json.stringify('__cycle__'); }
  12760. throw new TypeError('Converting circular structure to JSON');
  12761. } else { seen.push(node); }
  12762. var keys = objectKeys(node).sort(cmp && cmp(node));
  12763. var out = [];
  12764. for (var i = 0; i < keys.length; i++) {
  12765. var key = keys[i];
  12766. var value = stringify(node, key, node[key], level + 1);
  12767. if (!value) { continue; }
  12768. var keyValue = json.stringify(key)
  12769. + colonSeparator
  12770. + value;
  12771. out.push(indent + space + keyValue);
  12772. }
  12773. seen.splice(seen.indexOf(node), 1);
  12774. return '{' + out.join(',') + indent + '}';
  12775. }({ '': obj }, '', obj, 0));
  12776. };
  12777. var jsonStableStringify$1 = /*@__PURE__*/getDefaultExportFromCjs(jsonStableStringify);
  12778. const mimes$1 = {
  12779. "ez": "application/andrew-inset",
  12780. "aw": "application/applixware",
  12781. "atom": "application/atom+xml",
  12782. "atomcat": "application/atomcat+xml",
  12783. "atomdeleted": "application/atomdeleted+xml",
  12784. "atomsvc": "application/atomsvc+xml",
  12785. "dwd": "application/atsc-dwd+xml",
  12786. "held": "application/atsc-held+xml",
  12787. "rsat": "application/atsc-rsat+xml",
  12788. "bdoc": "application/bdoc",
  12789. "xcs": "application/calendar+xml",
  12790. "ccxml": "application/ccxml+xml",
  12791. "cdfx": "application/cdfx+xml",
  12792. "cdmia": "application/cdmi-capability",
  12793. "cdmic": "application/cdmi-container",
  12794. "cdmid": "application/cdmi-domain",
  12795. "cdmio": "application/cdmi-object",
  12796. "cdmiq": "application/cdmi-queue",
  12797. "cu": "application/cu-seeme",
  12798. "mpd": "application/dash+xml",
  12799. "davmount": "application/davmount+xml",
  12800. "dbk": "application/docbook+xml",
  12801. "dssc": "application/dssc+der",
  12802. "xdssc": "application/dssc+xml",
  12803. "es": "application/ecmascript",
  12804. "ecma": "application/ecmascript",
  12805. "emma": "application/emma+xml",
  12806. "emotionml": "application/emotionml+xml",
  12807. "epub": "application/epub+zip",
  12808. "exi": "application/exi",
  12809. "fdt": "application/fdt+xml",
  12810. "pfr": "application/font-tdpfr",
  12811. "geojson": "application/geo+json",
  12812. "gml": "application/gml+xml",
  12813. "gpx": "application/gpx+xml",
  12814. "gxf": "application/gxf",
  12815. "gz": "application/gzip",
  12816. "hjson": "application/hjson",
  12817. "stk": "application/hyperstudio",
  12818. "ink": "application/inkml+xml",
  12819. "inkml": "application/inkml+xml",
  12820. "ipfix": "application/ipfix",
  12821. "its": "application/its+xml",
  12822. "jar": "application/java-archive",
  12823. "war": "application/java-archive",
  12824. "ear": "application/java-archive",
  12825. "ser": "application/java-serialized-object",
  12826. "class": "application/java-vm",
  12827. "js": "application/javascript",
  12828. "mjs": "application/javascript",
  12829. "json": "application/json",
  12830. "map": "application/json",
  12831. "json5": "application/json5",
  12832. "jsonml": "application/jsonml+json",
  12833. "jsonld": "application/ld+json",
  12834. "lgr": "application/lgr+xml",
  12835. "lostxml": "application/lost+xml",
  12836. "hqx": "application/mac-binhex40",
  12837. "cpt": "application/mac-compactpro",
  12838. "mads": "application/mads+xml",
  12839. "webmanifest": "application/manifest+json",
  12840. "mrc": "application/marc",
  12841. "mrcx": "application/marcxml+xml",
  12842. "ma": "application/mathematica",
  12843. "nb": "application/mathematica",
  12844. "mb": "application/mathematica",
  12845. "mathml": "application/mathml+xml",
  12846. "mbox": "application/mbox",
  12847. "mscml": "application/mediaservercontrol+xml",
  12848. "metalink": "application/metalink+xml",
  12849. "meta4": "application/metalink4+xml",
  12850. "mets": "application/mets+xml",
  12851. "maei": "application/mmt-aei+xml",
  12852. "musd": "application/mmt-usd+xml",
  12853. "mods": "application/mods+xml",
  12854. "m21": "application/mp21",
  12855. "mp21": "application/mp21",
  12856. "mp4s": "application/mp4",
  12857. "m4p": "application/mp4",
  12858. "doc": "application/msword",
  12859. "dot": "application/msword",
  12860. "mxf": "application/mxf",
  12861. "nq": "application/n-quads",
  12862. "nt": "application/n-triples",
  12863. "cjs": "application/node",
  12864. "bin": "application/octet-stream",
  12865. "dms": "application/octet-stream",
  12866. "lrf": "application/octet-stream",
  12867. "mar": "application/octet-stream",
  12868. "so": "application/octet-stream",
  12869. "dist": "application/octet-stream",
  12870. "distz": "application/octet-stream",
  12871. "pkg": "application/octet-stream",
  12872. "bpk": "application/octet-stream",
  12873. "dump": "application/octet-stream",
  12874. "elc": "application/octet-stream",
  12875. "deploy": "application/octet-stream",
  12876. "exe": "application/octet-stream",
  12877. "dll": "application/octet-stream",
  12878. "deb": "application/octet-stream",
  12879. "dmg": "application/octet-stream",
  12880. "iso": "application/octet-stream",
  12881. "img": "application/octet-stream",
  12882. "msi": "application/octet-stream",
  12883. "msp": "application/octet-stream",
  12884. "msm": "application/octet-stream",
  12885. "buffer": "application/octet-stream",
  12886. "oda": "application/oda",
  12887. "opf": "application/oebps-package+xml",
  12888. "ogx": "application/ogg",
  12889. "omdoc": "application/omdoc+xml",
  12890. "onetoc": "application/onenote",
  12891. "onetoc2": "application/onenote",
  12892. "onetmp": "application/onenote",
  12893. "onepkg": "application/onenote",
  12894. "oxps": "application/oxps",
  12895. "relo": "application/p2p-overlay+xml",
  12896. "xer": "application/patch-ops-error+xml",
  12897. "pdf": "application/pdf",
  12898. "pgp": "application/pgp-encrypted",
  12899. "asc": "application/pgp-signature",
  12900. "sig": "application/pgp-signature",
  12901. "prf": "application/pics-rules",
  12902. "p10": "application/pkcs10",
  12903. "p7m": "application/pkcs7-mime",
  12904. "p7c": "application/pkcs7-mime",
  12905. "p7s": "application/pkcs7-signature",
  12906. "p8": "application/pkcs8",
  12907. "ac": "application/pkix-attr-cert",
  12908. "cer": "application/pkix-cert",
  12909. "crl": "application/pkix-crl",
  12910. "pkipath": "application/pkix-pkipath",
  12911. "pki": "application/pkixcmp",
  12912. "pls": "application/pls+xml",
  12913. "ai": "application/postscript",
  12914. "eps": "application/postscript",
  12915. "ps": "application/postscript",
  12916. "provx": "application/provenance+xml",
  12917. "cww": "application/prs.cww",
  12918. "pskcxml": "application/pskc+xml",
  12919. "raml": "application/raml+yaml",
  12920. "rdf": "application/rdf+xml",
  12921. "owl": "application/rdf+xml",
  12922. "rif": "application/reginfo+xml",
  12923. "rnc": "application/relax-ng-compact-syntax",
  12924. "rl": "application/resource-lists+xml",
  12925. "rld": "application/resource-lists-diff+xml",
  12926. "rs": "application/rls-services+xml",
  12927. "rapd": "application/route-apd+xml",
  12928. "sls": "application/route-s-tsid+xml",
  12929. "rusd": "application/route-usd+xml",
  12930. "gbr": "application/rpki-ghostbusters",
  12931. "mft": "application/rpki-manifest",
  12932. "roa": "application/rpki-roa",
  12933. "rsd": "application/rsd+xml",
  12934. "rss": "application/rss+xml",
  12935. "rtf": "application/rtf",
  12936. "sbml": "application/sbml+xml",
  12937. "scq": "application/scvp-cv-request",
  12938. "scs": "application/scvp-cv-response",
  12939. "spq": "application/scvp-vp-request",
  12940. "spp": "application/scvp-vp-response",
  12941. "sdp": "application/sdp",
  12942. "senmlx": "application/senml+xml",
  12943. "sensmlx": "application/sensml+xml",
  12944. "setpay": "application/set-payment-initiation",
  12945. "setreg": "application/set-registration-initiation",
  12946. "shf": "application/shf+xml",
  12947. "siv": "application/sieve",
  12948. "sieve": "application/sieve",
  12949. "smi": "application/smil+xml",
  12950. "smil": "application/smil+xml",
  12951. "rq": "application/sparql-query",
  12952. "srx": "application/sparql-results+xml",
  12953. "gram": "application/srgs",
  12954. "grxml": "application/srgs+xml",
  12955. "sru": "application/sru+xml",
  12956. "ssdl": "application/ssdl+xml",
  12957. "ssml": "application/ssml+xml",
  12958. "swidtag": "application/swid+xml",
  12959. "tei": "application/tei+xml",
  12960. "teicorpus": "application/tei+xml",
  12961. "tfi": "application/thraud+xml",
  12962. "tsd": "application/timestamped-data",
  12963. "toml": "application/toml",
  12964. "trig": "application/trig",
  12965. "ttml": "application/ttml+xml",
  12966. "ubj": "application/ubjson",
  12967. "rsheet": "application/urc-ressheet+xml",
  12968. "td": "application/urc-targetdesc+xml",
  12969. "vxml": "application/voicexml+xml",
  12970. "wasm": "application/wasm",
  12971. "wgt": "application/widget",
  12972. "hlp": "application/winhlp",
  12973. "wsdl": "application/wsdl+xml",
  12974. "wspolicy": "application/wspolicy+xml",
  12975. "xaml": "application/xaml+xml",
  12976. "xav": "application/xcap-att+xml",
  12977. "xca": "application/xcap-caps+xml",
  12978. "xdf": "application/xcap-diff+xml",
  12979. "xel": "application/xcap-el+xml",
  12980. "xns": "application/xcap-ns+xml",
  12981. "xenc": "application/xenc+xml",
  12982. "xhtml": "application/xhtml+xml",
  12983. "xht": "application/xhtml+xml",
  12984. "xlf": "application/xliff+xml",
  12985. "xml": "application/xml",
  12986. "xsl": "application/xml",
  12987. "xsd": "application/xml",
  12988. "rng": "application/xml",
  12989. "dtd": "application/xml-dtd",
  12990. "xop": "application/xop+xml",
  12991. "xpl": "application/xproc+xml",
  12992. "xslt": "application/xml",
  12993. "xspf": "application/xspf+xml",
  12994. "mxml": "application/xv+xml",
  12995. "xhvml": "application/xv+xml",
  12996. "xvml": "application/xv+xml",
  12997. "xvm": "application/xv+xml",
  12998. "yang": "application/yang",
  12999. "yin": "application/yin+xml",
  13000. "zip": "application/zip",
  13001. "3gpp": "video/3gpp",
  13002. "adp": "audio/adpcm",
  13003. "amr": "audio/amr",
  13004. "au": "audio/basic",
  13005. "snd": "audio/basic",
  13006. "mid": "audio/midi",
  13007. "midi": "audio/midi",
  13008. "kar": "audio/midi",
  13009. "rmi": "audio/midi",
  13010. "mxmf": "audio/mobile-xmf",
  13011. "mp3": "audio/mpeg",
  13012. "m4a": "audio/mp4",
  13013. "mp4a": "audio/mp4",
  13014. "mpga": "audio/mpeg",
  13015. "mp2": "audio/mpeg",
  13016. "mp2a": "audio/mpeg",
  13017. "m2a": "audio/mpeg",
  13018. "m3a": "audio/mpeg",
  13019. "oga": "audio/ogg",
  13020. "ogg": "audio/ogg",
  13021. "spx": "audio/ogg",
  13022. "opus": "audio/ogg",
  13023. "s3m": "audio/s3m",
  13024. "sil": "audio/silk",
  13025. "wav": "audio/wav",
  13026. "weba": "audio/webm",
  13027. "xm": "audio/xm",
  13028. "ttc": "font/collection",
  13029. "otf": "font/otf",
  13030. "ttf": "font/ttf",
  13031. "woff": "font/woff",
  13032. "woff2": "font/woff2",
  13033. "exr": "image/aces",
  13034. "apng": "image/apng",
  13035. "avif": "image/avif",
  13036. "bmp": "image/bmp",
  13037. "cgm": "image/cgm",
  13038. "drle": "image/dicom-rle",
  13039. "emf": "image/emf",
  13040. "fits": "image/fits",
  13041. "g3": "image/g3fax",
  13042. "gif": "image/gif",
  13043. "heic": "image/heic",
  13044. "heics": "image/heic-sequence",
  13045. "heif": "image/heif",
  13046. "heifs": "image/heif-sequence",
  13047. "hej2": "image/hej2k",
  13048. "hsj2": "image/hsj2",
  13049. "ief": "image/ief",
  13050. "jls": "image/jls",
  13051. "jp2": "image/jp2",
  13052. "jpg2": "image/jp2",
  13053. "jpeg": "image/jpeg",
  13054. "jpg": "image/jpeg",
  13055. "jpe": "image/jpeg",
  13056. "jph": "image/jph",
  13057. "jhc": "image/jphc",
  13058. "jpm": "image/jpm",
  13059. "jpx": "image/jpx",
  13060. "jpf": "image/jpx",
  13061. "jxr": "image/jxr",
  13062. "jxra": "image/jxra",
  13063. "jxrs": "image/jxrs",
  13064. "jxs": "image/jxs",
  13065. "jxsc": "image/jxsc",
  13066. "jxsi": "image/jxsi",
  13067. "jxss": "image/jxss",
  13068. "ktx": "image/ktx",
  13069. "ktx2": "image/ktx2",
  13070. "png": "image/png",
  13071. "btif": "image/prs.btif",
  13072. "pti": "image/prs.pti",
  13073. "sgi": "image/sgi",
  13074. "svg": "image/svg+xml",
  13075. "svgz": "image/svg+xml",
  13076. "t38": "image/t38",
  13077. "tif": "image/tiff",
  13078. "tiff": "image/tiff",
  13079. "tfx": "image/tiff-fx",
  13080. "webp": "image/webp",
  13081. "wmf": "image/wmf",
  13082. "disposition-notification": "message/disposition-notification",
  13083. "u8msg": "message/global",
  13084. "u8dsn": "message/global-delivery-status",
  13085. "u8mdn": "message/global-disposition-notification",
  13086. "u8hdr": "message/global-headers",
  13087. "eml": "message/rfc822",
  13088. "mime": "message/rfc822",
  13089. "3mf": "model/3mf",
  13090. "gltf": "model/gltf+json",
  13091. "glb": "model/gltf-binary",
  13092. "igs": "model/iges",
  13093. "iges": "model/iges",
  13094. "msh": "model/mesh",
  13095. "mesh": "model/mesh",
  13096. "silo": "model/mesh",
  13097. "mtl": "model/mtl",
  13098. "obj": "model/obj",
  13099. "stpz": "model/step+zip",
  13100. "stpxz": "model/step-xml+zip",
  13101. "stl": "model/stl",
  13102. "wrl": "model/vrml",
  13103. "vrml": "model/vrml",
  13104. "x3db": "model/x3d+fastinfoset",
  13105. "x3dbz": "model/x3d+binary",
  13106. "x3dv": "model/x3d-vrml",
  13107. "x3dvz": "model/x3d+vrml",
  13108. "x3d": "model/x3d+xml",
  13109. "x3dz": "model/x3d+xml",
  13110. "appcache": "text/cache-manifest",
  13111. "manifest": "text/cache-manifest",
  13112. "ics": "text/calendar",
  13113. "ifb": "text/calendar",
  13114. "coffee": "text/coffeescript",
  13115. "litcoffee": "text/coffeescript",
  13116. "css": "text/css",
  13117. "csv": "text/csv",
  13118. "html": "text/html",
  13119. "htm": "text/html",
  13120. "shtml": "text/html",
  13121. "jade": "text/jade",
  13122. "jsx": "text/jsx",
  13123. "less": "text/less",
  13124. "markdown": "text/markdown",
  13125. "md": "text/markdown",
  13126. "mml": "text/mathml",
  13127. "mdx": "text/mdx",
  13128. "n3": "text/n3",
  13129. "txt": "text/plain",
  13130. "text": "text/plain",
  13131. "conf": "text/plain",
  13132. "def": "text/plain",
  13133. "list": "text/plain",
  13134. "log": "text/plain",
  13135. "in": "text/plain",
  13136. "ini": "text/plain",
  13137. "dsc": "text/prs.lines.tag",
  13138. "rtx": "text/richtext",
  13139. "sgml": "text/sgml",
  13140. "sgm": "text/sgml",
  13141. "shex": "text/shex",
  13142. "slim": "text/slim",
  13143. "slm": "text/slim",
  13144. "spdx": "text/spdx",
  13145. "stylus": "text/stylus",
  13146. "styl": "text/stylus",
  13147. "tsv": "text/tab-separated-values",
  13148. "t": "text/troff",
  13149. "tr": "text/troff",
  13150. "roff": "text/troff",
  13151. "man": "text/troff",
  13152. "me": "text/troff",
  13153. "ms": "text/troff",
  13154. "ttl": "text/turtle",
  13155. "uri": "text/uri-list",
  13156. "uris": "text/uri-list",
  13157. "urls": "text/uri-list",
  13158. "vcard": "text/vcard",
  13159. "vtt": "text/vtt",
  13160. "yaml": "text/yaml",
  13161. "yml": "text/yaml",
  13162. "3gp": "video/3gpp",
  13163. "3g2": "video/3gpp2",
  13164. "h261": "video/h261",
  13165. "h263": "video/h263",
  13166. "h264": "video/h264",
  13167. "m4s": "video/iso.segment",
  13168. "jpgv": "video/jpeg",
  13169. "jpgm": "image/jpm",
  13170. "mj2": "video/mj2",
  13171. "mjp2": "video/mj2",
  13172. "ts": "video/mp2t",
  13173. "mp4": "video/mp4",
  13174. "mp4v": "video/mp4",
  13175. "mpg4": "video/mp4",
  13176. "mpeg": "video/mpeg",
  13177. "mpg": "video/mpeg",
  13178. "mpe": "video/mpeg",
  13179. "m1v": "video/mpeg",
  13180. "m2v": "video/mpeg",
  13181. "ogv": "video/ogg",
  13182. "qt": "video/quicktime",
  13183. "mov": "video/quicktime",
  13184. "webm": "video/webm"
  13185. };
  13186. function lookup(extn) {
  13187. let tmp = ('' + extn).trim().toLowerCase();
  13188. let idx = tmp.lastIndexOf('.');
  13189. return mimes$1[!~idx ? tmp : tmp.substring(++idx)];
  13190. }
  13191. class BitSet {
  13192. constructor(arg) {
  13193. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  13194. }
  13195. add(n) {
  13196. this.bits[n >> 5] |= 1 << (n & 31);
  13197. }
  13198. has(n) {
  13199. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  13200. }
  13201. }
  13202. class Chunk {
  13203. constructor(start, end, content) {
  13204. this.start = start;
  13205. this.end = end;
  13206. this.original = content;
  13207. this.intro = '';
  13208. this.outro = '';
  13209. this.content = content;
  13210. this.storeName = false;
  13211. this.edited = false;
  13212. {
  13213. this.previous = null;
  13214. this.next = null;
  13215. }
  13216. }
  13217. appendLeft(content) {
  13218. this.outro += content;
  13219. }
  13220. appendRight(content) {
  13221. this.intro = this.intro + content;
  13222. }
  13223. clone() {
  13224. const chunk = new Chunk(this.start, this.end, this.original);
  13225. chunk.intro = this.intro;
  13226. chunk.outro = this.outro;
  13227. chunk.content = this.content;
  13228. chunk.storeName = this.storeName;
  13229. chunk.edited = this.edited;
  13230. return chunk;
  13231. }
  13232. contains(index) {
  13233. return this.start < index && index < this.end;
  13234. }
  13235. eachNext(fn) {
  13236. let chunk = this;
  13237. while (chunk) {
  13238. fn(chunk);
  13239. chunk = chunk.next;
  13240. }
  13241. }
  13242. eachPrevious(fn) {
  13243. let chunk = this;
  13244. while (chunk) {
  13245. fn(chunk);
  13246. chunk = chunk.previous;
  13247. }
  13248. }
  13249. edit(content, storeName, contentOnly) {
  13250. this.content = content;
  13251. if (!contentOnly) {
  13252. this.intro = '';
  13253. this.outro = '';
  13254. }
  13255. this.storeName = storeName;
  13256. this.edited = true;
  13257. return this;
  13258. }
  13259. prependLeft(content) {
  13260. this.outro = content + this.outro;
  13261. }
  13262. prependRight(content) {
  13263. this.intro = content + this.intro;
  13264. }
  13265. split(index) {
  13266. const sliceIndex = index - this.start;
  13267. const originalBefore = this.original.slice(0, sliceIndex);
  13268. const originalAfter = this.original.slice(sliceIndex);
  13269. this.original = originalBefore;
  13270. const newChunk = new Chunk(index, this.end, originalAfter);
  13271. newChunk.outro = this.outro;
  13272. this.outro = '';
  13273. this.end = index;
  13274. if (this.edited) {
  13275. // TODO is this block necessary?...
  13276. newChunk.edit('', false);
  13277. this.content = '';
  13278. } else {
  13279. this.content = originalBefore;
  13280. }
  13281. newChunk.next = this.next;
  13282. if (newChunk.next) newChunk.next.previous = newChunk;
  13283. newChunk.previous = this;
  13284. this.next = newChunk;
  13285. return newChunk;
  13286. }
  13287. toString() {
  13288. return this.intro + this.content + this.outro;
  13289. }
  13290. trimEnd(rx) {
  13291. this.outro = this.outro.replace(rx, '');
  13292. if (this.outro.length) return true;
  13293. const trimmed = this.content.replace(rx, '');
  13294. if (trimmed.length) {
  13295. if (trimmed !== this.content) {
  13296. this.split(this.start + trimmed.length).edit('', undefined, true);
  13297. }
  13298. return true;
  13299. } else {
  13300. this.edit('', undefined, true);
  13301. this.intro = this.intro.replace(rx, '');
  13302. if (this.intro.length) return true;
  13303. }
  13304. }
  13305. trimStart(rx) {
  13306. this.intro = this.intro.replace(rx, '');
  13307. if (this.intro.length) return true;
  13308. const trimmed = this.content.replace(rx, '');
  13309. if (trimmed.length) {
  13310. if (trimmed !== this.content) {
  13311. this.split(this.end - trimmed.length);
  13312. this.edit('', undefined, true);
  13313. }
  13314. return true;
  13315. } else {
  13316. this.edit('', undefined, true);
  13317. this.outro = this.outro.replace(rx, '');
  13318. if (this.outro.length) return true;
  13319. }
  13320. }
  13321. }
  13322. function getBtoa () {
  13323. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  13324. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  13325. } else if (typeof Buffer === 'function') {
  13326. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  13327. } else {
  13328. return () => {
  13329. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  13330. };
  13331. }
  13332. }
  13333. const btoa$1 = /*#__PURE__*/ getBtoa();
  13334. class SourceMap {
  13335. constructor(properties) {
  13336. this.version = 3;
  13337. this.file = properties.file;
  13338. this.sources = properties.sources;
  13339. this.sourcesContent = properties.sourcesContent;
  13340. this.names = properties.names;
  13341. this.mappings = encode$1(properties.mappings);
  13342. if (typeof properties.x_google_ignoreList !== 'undefined') {
  13343. this.x_google_ignoreList = properties.x_google_ignoreList;
  13344. }
  13345. }
  13346. toString() {
  13347. return JSON.stringify(this);
  13348. }
  13349. toUrl() {
  13350. return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
  13351. }
  13352. }
  13353. function guessIndent(code) {
  13354. const lines = code.split('\n');
  13355. const tabbed = lines.filter((line) => /^\t+/.test(line));
  13356. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  13357. if (tabbed.length === 0 && spaced.length === 0) {
  13358. return null;
  13359. }
  13360. // More lines tabbed than spaced? Assume tabs, and
  13361. // default to tabs in the case of a tie (or nothing
  13362. // to go on)
  13363. if (tabbed.length >= spaced.length) {
  13364. return '\t';
  13365. }
  13366. // Otherwise, we need to guess the multiple
  13367. const min = spaced.reduce((previous, current) => {
  13368. const numSpaces = /^ +/.exec(current)[0].length;
  13369. return Math.min(numSpaces, previous);
  13370. }, Infinity);
  13371. return new Array(min + 1).join(' ');
  13372. }
  13373. function getRelativePath(from, to) {
  13374. const fromParts = from.split(/[/\\]/);
  13375. const toParts = to.split(/[/\\]/);
  13376. fromParts.pop(); // get dirname
  13377. while (fromParts[0] === toParts[0]) {
  13378. fromParts.shift();
  13379. toParts.shift();
  13380. }
  13381. if (fromParts.length) {
  13382. let i = fromParts.length;
  13383. while (i--) fromParts[i] = '..';
  13384. }
  13385. return fromParts.concat(toParts).join('/');
  13386. }
  13387. const toString$2 = Object.prototype.toString;
  13388. function isObject$1(thing) {
  13389. return toString$2.call(thing) === '[object Object]';
  13390. }
  13391. function getLocator(source) {
  13392. const originalLines = source.split('\n');
  13393. const lineOffsets = [];
  13394. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  13395. lineOffsets.push(pos);
  13396. pos += originalLines[i].length + 1;
  13397. }
  13398. return function locate(index) {
  13399. let i = 0;
  13400. let j = lineOffsets.length;
  13401. while (i < j) {
  13402. const m = (i + j) >> 1;
  13403. if (index < lineOffsets[m]) {
  13404. j = m;
  13405. } else {
  13406. i = m + 1;
  13407. }
  13408. }
  13409. const line = i - 1;
  13410. const column = index - lineOffsets[line];
  13411. return { line, column };
  13412. };
  13413. }
  13414. class Mappings {
  13415. constructor(hires) {
  13416. this.hires = hires;
  13417. this.generatedCodeLine = 0;
  13418. this.generatedCodeColumn = 0;
  13419. this.raw = [];
  13420. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  13421. this.pending = null;
  13422. }
  13423. addEdit(sourceIndex, content, loc, nameIndex) {
  13424. if (content.length) {
  13425. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  13426. if (nameIndex >= 0) {
  13427. segment.push(nameIndex);
  13428. }
  13429. this.rawSegments.push(segment);
  13430. } else if (this.pending) {
  13431. this.rawSegments.push(this.pending);
  13432. }
  13433. this.advance(content);
  13434. this.pending = null;
  13435. }
  13436. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  13437. let originalCharIndex = chunk.start;
  13438. let first = true;
  13439. while (originalCharIndex < chunk.end) {
  13440. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  13441. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  13442. }
  13443. if (original[originalCharIndex] === '\n') {
  13444. loc.line += 1;
  13445. loc.column = 0;
  13446. this.generatedCodeLine += 1;
  13447. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  13448. this.generatedCodeColumn = 0;
  13449. first = true;
  13450. } else {
  13451. loc.column += 1;
  13452. this.generatedCodeColumn += 1;
  13453. first = false;
  13454. }
  13455. originalCharIndex += 1;
  13456. }
  13457. this.pending = null;
  13458. }
  13459. advance(str) {
  13460. if (!str) return;
  13461. const lines = str.split('\n');
  13462. if (lines.length > 1) {
  13463. for (let i = 0; i < lines.length - 1; i++) {
  13464. this.generatedCodeLine++;
  13465. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  13466. }
  13467. this.generatedCodeColumn = 0;
  13468. }
  13469. this.generatedCodeColumn += lines[lines.length - 1].length;
  13470. }
  13471. }
  13472. const n$1 = '\n';
  13473. const warned = {
  13474. insertLeft: false,
  13475. insertRight: false,
  13476. storeName: false,
  13477. };
  13478. class MagicString {
  13479. constructor(string, options = {}) {
  13480. const chunk = new Chunk(0, string.length, string);
  13481. Object.defineProperties(this, {
  13482. original: { writable: true, value: string },
  13483. outro: { writable: true, value: '' },
  13484. intro: { writable: true, value: '' },
  13485. firstChunk: { writable: true, value: chunk },
  13486. lastChunk: { writable: true, value: chunk },
  13487. lastSearchedChunk: { writable: true, value: chunk },
  13488. byStart: { writable: true, value: {} },
  13489. byEnd: { writable: true, value: {} },
  13490. filename: { writable: true, value: options.filename },
  13491. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  13492. sourcemapLocations: { writable: true, value: new BitSet() },
  13493. storedNames: { writable: true, value: {} },
  13494. indentStr: { writable: true, value: undefined },
  13495. ignoreList: { writable: true, value: options.ignoreList },
  13496. });
  13497. this.byStart[0] = chunk;
  13498. this.byEnd[string.length] = chunk;
  13499. }
  13500. addSourcemapLocation(char) {
  13501. this.sourcemapLocations.add(char);
  13502. }
  13503. append(content) {
  13504. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  13505. this.outro += content;
  13506. return this;
  13507. }
  13508. appendLeft(index, content) {
  13509. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  13510. this._split(index);
  13511. const chunk = this.byEnd[index];
  13512. if (chunk) {
  13513. chunk.appendLeft(content);
  13514. } else {
  13515. this.intro += content;
  13516. }
  13517. return this;
  13518. }
  13519. appendRight(index, content) {
  13520. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  13521. this._split(index);
  13522. const chunk = this.byStart[index];
  13523. if (chunk) {
  13524. chunk.appendRight(content);
  13525. } else {
  13526. this.outro += content;
  13527. }
  13528. return this;
  13529. }
  13530. clone() {
  13531. const cloned = new MagicString(this.original, { filename: this.filename });
  13532. let originalChunk = this.firstChunk;
  13533. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  13534. while (originalChunk) {
  13535. cloned.byStart[clonedChunk.start] = clonedChunk;
  13536. cloned.byEnd[clonedChunk.end] = clonedChunk;
  13537. const nextOriginalChunk = originalChunk.next;
  13538. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  13539. if (nextClonedChunk) {
  13540. clonedChunk.next = nextClonedChunk;
  13541. nextClonedChunk.previous = clonedChunk;
  13542. clonedChunk = nextClonedChunk;
  13543. }
  13544. originalChunk = nextOriginalChunk;
  13545. }
  13546. cloned.lastChunk = clonedChunk;
  13547. if (this.indentExclusionRanges) {
  13548. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  13549. }
  13550. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  13551. cloned.intro = this.intro;
  13552. cloned.outro = this.outro;
  13553. return cloned;
  13554. }
  13555. generateDecodedMap(options) {
  13556. options = options || {};
  13557. const sourceIndex = 0;
  13558. const names = Object.keys(this.storedNames);
  13559. const mappings = new Mappings(options.hires);
  13560. const locate = getLocator(this.original);
  13561. if (this.intro) {
  13562. mappings.advance(this.intro);
  13563. }
  13564. this.firstChunk.eachNext((chunk) => {
  13565. const loc = locate(chunk.start);
  13566. if (chunk.intro.length) mappings.advance(chunk.intro);
  13567. if (chunk.edited) {
  13568. mappings.addEdit(
  13569. sourceIndex,
  13570. chunk.content,
  13571. loc,
  13572. chunk.storeName ? names.indexOf(chunk.original) : -1
  13573. );
  13574. } else {
  13575. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  13576. }
  13577. if (chunk.outro.length) mappings.advance(chunk.outro);
  13578. });
  13579. return {
  13580. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  13581. sources: [options.source ? getRelativePath(options.file || '', options.source) : (options.file || '')],
  13582. sourcesContent: options.includeContent ? [this.original] : undefined,
  13583. names,
  13584. mappings: mappings.raw,
  13585. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined
  13586. };
  13587. }
  13588. generateMap(options) {
  13589. return new SourceMap(this.generateDecodedMap(options));
  13590. }
  13591. _ensureindentStr() {
  13592. if (this.indentStr === undefined) {
  13593. this.indentStr = guessIndent(this.original);
  13594. }
  13595. }
  13596. _getRawIndentString() {
  13597. this._ensureindentStr();
  13598. return this.indentStr;
  13599. }
  13600. getIndentString() {
  13601. this._ensureindentStr();
  13602. return this.indentStr === null ? '\t' : this.indentStr;
  13603. }
  13604. indent(indentStr, options) {
  13605. const pattern = /^[^\r\n]/gm;
  13606. if (isObject$1(indentStr)) {
  13607. options = indentStr;
  13608. indentStr = undefined;
  13609. }
  13610. if (indentStr === undefined) {
  13611. this._ensureindentStr();
  13612. indentStr = this.indentStr || '\t';
  13613. }
  13614. if (indentStr === '') return this; // noop
  13615. options = options || {};
  13616. // Process exclusion ranges
  13617. const isExcluded = {};
  13618. if (options.exclude) {
  13619. const exclusions =
  13620. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  13621. exclusions.forEach((exclusion) => {
  13622. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  13623. isExcluded[i] = true;
  13624. }
  13625. });
  13626. }
  13627. let shouldIndentNextCharacter = options.indentStart !== false;
  13628. const replacer = (match) => {
  13629. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  13630. shouldIndentNextCharacter = true;
  13631. return match;
  13632. };
  13633. this.intro = this.intro.replace(pattern, replacer);
  13634. let charIndex = 0;
  13635. let chunk = this.firstChunk;
  13636. while (chunk) {
  13637. const end = chunk.end;
  13638. if (chunk.edited) {
  13639. if (!isExcluded[charIndex]) {
  13640. chunk.content = chunk.content.replace(pattern, replacer);
  13641. if (chunk.content.length) {
  13642. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  13643. }
  13644. }
  13645. } else {
  13646. charIndex = chunk.start;
  13647. while (charIndex < end) {
  13648. if (!isExcluded[charIndex]) {
  13649. const char = this.original[charIndex];
  13650. if (char === '\n') {
  13651. shouldIndentNextCharacter = true;
  13652. } else if (char !== '\r' && shouldIndentNextCharacter) {
  13653. shouldIndentNextCharacter = false;
  13654. if (charIndex === chunk.start) {
  13655. chunk.prependRight(indentStr);
  13656. } else {
  13657. this._splitChunk(chunk, charIndex);
  13658. chunk = chunk.next;
  13659. chunk.prependRight(indentStr);
  13660. }
  13661. }
  13662. }
  13663. charIndex += 1;
  13664. }
  13665. }
  13666. charIndex = chunk.end;
  13667. chunk = chunk.next;
  13668. }
  13669. this.outro = this.outro.replace(pattern, replacer);
  13670. return this;
  13671. }
  13672. insert() {
  13673. throw new Error(
  13674. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  13675. );
  13676. }
  13677. insertLeft(index, content) {
  13678. if (!warned.insertLeft) {
  13679. console.warn(
  13680. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  13681. ); // eslint-disable-line no-console
  13682. warned.insertLeft = true;
  13683. }
  13684. return this.appendLeft(index, content);
  13685. }
  13686. insertRight(index, content) {
  13687. if (!warned.insertRight) {
  13688. console.warn(
  13689. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  13690. ); // eslint-disable-line no-console
  13691. warned.insertRight = true;
  13692. }
  13693. return this.prependRight(index, content);
  13694. }
  13695. move(start, end, index) {
  13696. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  13697. this._split(start);
  13698. this._split(end);
  13699. this._split(index);
  13700. const first = this.byStart[start];
  13701. const last = this.byEnd[end];
  13702. const oldLeft = first.previous;
  13703. const oldRight = last.next;
  13704. const newRight = this.byStart[index];
  13705. if (!newRight && last === this.lastChunk) return this;
  13706. const newLeft = newRight ? newRight.previous : this.lastChunk;
  13707. if (oldLeft) oldLeft.next = oldRight;
  13708. if (oldRight) oldRight.previous = oldLeft;
  13709. if (newLeft) newLeft.next = first;
  13710. if (newRight) newRight.previous = last;
  13711. if (!first.previous) this.firstChunk = last.next;
  13712. if (!last.next) {
  13713. this.lastChunk = first.previous;
  13714. this.lastChunk.next = null;
  13715. }
  13716. first.previous = newLeft;
  13717. last.next = newRight || null;
  13718. if (!newLeft) this.firstChunk = first;
  13719. if (!newRight) this.lastChunk = last;
  13720. return this;
  13721. }
  13722. overwrite(start, end, content, options) {
  13723. options = options || {};
  13724. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  13725. }
  13726. update(start, end, content, options) {
  13727. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  13728. while (start < 0) start += this.original.length;
  13729. while (end < 0) end += this.original.length;
  13730. if (end > this.original.length) throw new Error('end is out of bounds');
  13731. if (start === end)
  13732. throw new Error(
  13733. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  13734. );
  13735. this._split(start);
  13736. this._split(end);
  13737. if (options === true) {
  13738. if (!warned.storeName) {
  13739. console.warn(
  13740. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  13741. ); // eslint-disable-line no-console
  13742. warned.storeName = true;
  13743. }
  13744. options = { storeName: true };
  13745. }
  13746. const storeName = options !== undefined ? options.storeName : false;
  13747. const overwrite = options !== undefined ? options.overwrite : false;
  13748. if (storeName) {
  13749. const original = this.original.slice(start, end);
  13750. Object.defineProperty(this.storedNames, original, {
  13751. writable: true,
  13752. value: true,
  13753. enumerable: true,
  13754. });
  13755. }
  13756. const first = this.byStart[start];
  13757. const last = this.byEnd[end];
  13758. if (first) {
  13759. let chunk = first;
  13760. while (chunk !== last) {
  13761. if (chunk.next !== this.byStart[chunk.end]) {
  13762. throw new Error('Cannot overwrite across a split point');
  13763. }
  13764. chunk = chunk.next;
  13765. chunk.edit('', false);
  13766. }
  13767. first.edit(content, storeName, !overwrite);
  13768. } else {
  13769. // must be inserting at the end
  13770. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  13771. // TODO last chunk in the array may not be the last chunk, if it's moved...
  13772. last.next = newChunk;
  13773. newChunk.previous = last;
  13774. }
  13775. return this;
  13776. }
  13777. prepend(content) {
  13778. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  13779. this.intro = content + this.intro;
  13780. return this;
  13781. }
  13782. prependLeft(index, content) {
  13783. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  13784. this._split(index);
  13785. const chunk = this.byEnd[index];
  13786. if (chunk) {
  13787. chunk.prependLeft(content);
  13788. } else {
  13789. this.intro = content + this.intro;
  13790. }
  13791. return this;
  13792. }
  13793. prependRight(index, content) {
  13794. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  13795. this._split(index);
  13796. const chunk = this.byStart[index];
  13797. if (chunk) {
  13798. chunk.prependRight(content);
  13799. } else {
  13800. this.outro = content + this.outro;
  13801. }
  13802. return this;
  13803. }
  13804. remove(start, end) {
  13805. while (start < 0) start += this.original.length;
  13806. while (end < 0) end += this.original.length;
  13807. if (start === end) return this;
  13808. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  13809. if (start > end) throw new Error('end must be greater than start');
  13810. this._split(start);
  13811. this._split(end);
  13812. let chunk = this.byStart[start];
  13813. while (chunk) {
  13814. chunk.intro = '';
  13815. chunk.outro = '';
  13816. chunk.edit('');
  13817. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  13818. }
  13819. return this;
  13820. }
  13821. lastChar() {
  13822. if (this.outro.length) return this.outro[this.outro.length - 1];
  13823. let chunk = this.lastChunk;
  13824. do {
  13825. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  13826. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  13827. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  13828. } while ((chunk = chunk.previous));
  13829. if (this.intro.length) return this.intro[this.intro.length - 1];
  13830. return '';
  13831. }
  13832. lastLine() {
  13833. let lineIndex = this.outro.lastIndexOf(n$1);
  13834. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  13835. let lineStr = this.outro;
  13836. let chunk = this.lastChunk;
  13837. do {
  13838. if (chunk.outro.length > 0) {
  13839. lineIndex = chunk.outro.lastIndexOf(n$1);
  13840. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  13841. lineStr = chunk.outro + lineStr;
  13842. }
  13843. if (chunk.content.length > 0) {
  13844. lineIndex = chunk.content.lastIndexOf(n$1);
  13845. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  13846. lineStr = chunk.content + lineStr;
  13847. }
  13848. if (chunk.intro.length > 0) {
  13849. lineIndex = chunk.intro.lastIndexOf(n$1);
  13850. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  13851. lineStr = chunk.intro + lineStr;
  13852. }
  13853. } while ((chunk = chunk.previous));
  13854. lineIndex = this.intro.lastIndexOf(n$1);
  13855. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  13856. return this.intro + lineStr;
  13857. }
  13858. slice(start = 0, end = this.original.length) {
  13859. while (start < 0) start += this.original.length;
  13860. while (end < 0) end += this.original.length;
  13861. let result = '';
  13862. // find start chunk
  13863. let chunk = this.firstChunk;
  13864. while (chunk && (chunk.start > start || chunk.end <= start)) {
  13865. // found end chunk before start
  13866. if (chunk.start < end && chunk.end >= end) {
  13867. return result;
  13868. }
  13869. chunk = chunk.next;
  13870. }
  13871. if (chunk && chunk.edited && chunk.start !== start)
  13872. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  13873. const startChunk = chunk;
  13874. while (chunk) {
  13875. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  13876. result += chunk.intro;
  13877. }
  13878. const containsEnd = chunk.start < end && chunk.end >= end;
  13879. if (containsEnd && chunk.edited && chunk.end !== end)
  13880. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  13881. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  13882. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  13883. result += chunk.content.slice(sliceStart, sliceEnd);
  13884. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  13885. result += chunk.outro;
  13886. }
  13887. if (containsEnd) {
  13888. break;
  13889. }
  13890. chunk = chunk.next;
  13891. }
  13892. return result;
  13893. }
  13894. // TODO deprecate this? not really very useful
  13895. snip(start, end) {
  13896. const clone = this.clone();
  13897. clone.remove(0, start);
  13898. clone.remove(end, clone.original.length);
  13899. return clone;
  13900. }
  13901. _split(index) {
  13902. if (this.byStart[index] || this.byEnd[index]) return;
  13903. let chunk = this.lastSearchedChunk;
  13904. const searchForward = index > chunk.end;
  13905. while (chunk) {
  13906. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  13907. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  13908. }
  13909. }
  13910. _splitChunk(chunk, index) {
  13911. if (chunk.edited && chunk.content.length) {
  13912. // zero-length edited chunks are a special case (overlapping replacements)
  13913. const loc = getLocator(this.original)(index);
  13914. throw new Error(
  13915. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  13916. );
  13917. }
  13918. const newChunk = chunk.split(index);
  13919. this.byEnd[index] = chunk;
  13920. this.byStart[index] = newChunk;
  13921. this.byEnd[newChunk.end] = newChunk;
  13922. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  13923. this.lastSearchedChunk = chunk;
  13924. return true;
  13925. }
  13926. toString() {
  13927. let str = this.intro;
  13928. let chunk = this.firstChunk;
  13929. while (chunk) {
  13930. str += chunk.toString();
  13931. chunk = chunk.next;
  13932. }
  13933. return str + this.outro;
  13934. }
  13935. isEmpty() {
  13936. let chunk = this.firstChunk;
  13937. do {
  13938. if (
  13939. (chunk.intro.length && chunk.intro.trim()) ||
  13940. (chunk.content.length && chunk.content.trim()) ||
  13941. (chunk.outro.length && chunk.outro.trim())
  13942. )
  13943. return false;
  13944. } while ((chunk = chunk.next));
  13945. return true;
  13946. }
  13947. length() {
  13948. let chunk = this.firstChunk;
  13949. let length = 0;
  13950. do {
  13951. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  13952. } while ((chunk = chunk.next));
  13953. return length;
  13954. }
  13955. trimLines() {
  13956. return this.trim('[\\r\\n]');
  13957. }
  13958. trim(charType) {
  13959. return this.trimStart(charType).trimEnd(charType);
  13960. }
  13961. trimEndAborted(charType) {
  13962. const rx = new RegExp((charType || '\\s') + '+$');
  13963. this.outro = this.outro.replace(rx, '');
  13964. if (this.outro.length) return true;
  13965. let chunk = this.lastChunk;
  13966. do {
  13967. const end = chunk.end;
  13968. const aborted = chunk.trimEnd(rx);
  13969. // if chunk was trimmed, we have a new lastChunk
  13970. if (chunk.end !== end) {
  13971. if (this.lastChunk === chunk) {
  13972. this.lastChunk = chunk.next;
  13973. }
  13974. this.byEnd[chunk.end] = chunk;
  13975. this.byStart[chunk.next.start] = chunk.next;
  13976. this.byEnd[chunk.next.end] = chunk.next;
  13977. }
  13978. if (aborted) return true;
  13979. chunk = chunk.previous;
  13980. } while (chunk);
  13981. return false;
  13982. }
  13983. trimEnd(charType) {
  13984. this.trimEndAborted(charType);
  13985. return this;
  13986. }
  13987. trimStartAborted(charType) {
  13988. const rx = new RegExp('^' + (charType || '\\s') + '+');
  13989. this.intro = this.intro.replace(rx, '');
  13990. if (this.intro.length) return true;
  13991. let chunk = this.firstChunk;
  13992. do {
  13993. const end = chunk.end;
  13994. const aborted = chunk.trimStart(rx);
  13995. if (chunk.end !== end) {
  13996. // special case...
  13997. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  13998. this.byEnd[chunk.end] = chunk;
  13999. this.byStart[chunk.next.start] = chunk.next;
  14000. this.byEnd[chunk.next.end] = chunk.next;
  14001. }
  14002. if (aborted) return true;
  14003. chunk = chunk.next;
  14004. } while (chunk);
  14005. return false;
  14006. }
  14007. trimStart(charType) {
  14008. this.trimStartAborted(charType);
  14009. return this;
  14010. }
  14011. hasChanged() {
  14012. return this.original !== this.toString();
  14013. }
  14014. _replaceRegexp(searchValue, replacement) {
  14015. function getReplacement(match, str) {
  14016. if (typeof replacement === 'string') {
  14017. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  14018. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  14019. if (i === '$') return '$';
  14020. if (i === '&') return match[0];
  14021. const num = +i;
  14022. if (num < match.length) return match[+i];
  14023. return `$${i}`;
  14024. });
  14025. } else {
  14026. return replacement(...match, match.index, str, match.groups);
  14027. }
  14028. }
  14029. function matchAll(re, str) {
  14030. let match;
  14031. const matches = [];
  14032. while ((match = re.exec(str))) {
  14033. matches.push(match);
  14034. }
  14035. return matches;
  14036. }
  14037. if (searchValue.global) {
  14038. const matches = matchAll(searchValue, this.original);
  14039. matches.forEach((match) => {
  14040. if (match.index != null)
  14041. this.overwrite(
  14042. match.index,
  14043. match.index + match[0].length,
  14044. getReplacement(match, this.original)
  14045. );
  14046. });
  14047. } else {
  14048. const match = this.original.match(searchValue);
  14049. if (match && match.index != null)
  14050. this.overwrite(
  14051. match.index,
  14052. match.index + match[0].length,
  14053. getReplacement(match, this.original)
  14054. );
  14055. }
  14056. return this;
  14057. }
  14058. _replaceString(string, replacement) {
  14059. const { original } = this;
  14060. const index = original.indexOf(string);
  14061. if (index !== -1) {
  14062. this.overwrite(index, index + string.length, replacement);
  14063. }
  14064. return this;
  14065. }
  14066. replace(searchValue, replacement) {
  14067. if (typeof searchValue === 'string') {
  14068. return this._replaceString(searchValue, replacement);
  14069. }
  14070. return this._replaceRegexp(searchValue, replacement);
  14071. }
  14072. _replaceAllString(string, replacement) {
  14073. const { original } = this;
  14074. const stringLength = string.length;
  14075. for (
  14076. let index = original.indexOf(string);
  14077. index !== -1;
  14078. index = original.indexOf(string, index + stringLength)
  14079. ) {
  14080. this.overwrite(index, index + stringLength, replacement);
  14081. }
  14082. return this;
  14083. }
  14084. replaceAll(searchValue, replacement) {
  14085. if (typeof searchValue === 'string') {
  14086. return this._replaceAllString(searchValue, replacement);
  14087. }
  14088. if (!searchValue.global) {
  14089. throw new TypeError(
  14090. 'MagicString.prototype.replaceAll called with a non-global RegExp argument'
  14091. );
  14092. }
  14093. return this._replaceRegexp(searchValue, replacement);
  14094. }
  14095. }
  14096. const assetUrlRE = /__VITE_ASSET__([a-z\d]+)__(?:\$_(.*?)__)?/g;
  14097. const rawRE = /(?:\?|&)raw(?:&|$)/;
  14098. const urlRE = /(\?|&)url(?:&|$)/;
  14099. const jsSourceMapRE = /\.[cm]?js\.map$/;
  14100. const unnededFinalQueryCharRE = /[?&]$/;
  14101. const assetCache = new WeakMap();
  14102. const generatedAssets = new WeakMap();
  14103. // add own dictionary entry by directly assigning mrmime
  14104. function registerCustomMime() {
  14105. // https://github.com/lukeed/mrmime/issues/3
  14106. mimes$1['ico'] = 'image/x-icon';
  14107. // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#flac
  14108. mimes$1['flac'] = 'audio/flac';
  14109. // mrmime and mime-db is not released yet: https://github.com/jshttp/mime-db/commit/c9242a9b7d4bb25d7a0c9244adec74aeef08d8a1
  14110. mimes$1['aac'] = 'audio/aac';
  14111. // https://wiki.xiph.org/MIME_Types_and_File_Extensions#.opus_-_audio/ogg
  14112. mimes$1['opus'] = 'audio/ogg';
  14113. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
  14114. mimes$1['eot'] = 'application/vnd.ms-fontobject';
  14115. }
  14116. function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
  14117. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config.isWorker);
  14118. let match;
  14119. let s;
  14120. // Urls added with JS using e.g.
  14121. // imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes
  14122. // Urls added in CSS that is imported in JS end up like
  14123. // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n";
  14124. // In both cases, the wrapping should already be fine
  14125. assetUrlRE.lastIndex = 0;
  14126. while ((match = assetUrlRE.exec(code))) {
  14127. s || (s = new MagicString(code));
  14128. const [full, referenceId, postfix = ''] = match;
  14129. const file = ctx.getFileName(referenceId);
  14130. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  14131. const filename = file + postfix;
  14132. const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
  14133. const replacementString = typeof replacement === 'string'
  14134. ? JSON.stringify(replacement).slice(1, -1)
  14135. : `"+${replacement.runtime}+"`;
  14136. s.update(match.index, match.index + full.length, replacementString);
  14137. }
  14138. // Replace __VITE_PUBLIC_ASSET__5aa0ddc0__ with absolute paths
  14139. const publicAssetUrlMap = publicAssetUrlCache.get(config);
  14140. publicAssetUrlRE.lastIndex = 0;
  14141. while ((match = publicAssetUrlRE.exec(code))) {
  14142. s || (s = new MagicString(code));
  14143. const [full, hash] = match;
  14144. const publicUrl = publicAssetUrlMap.get(hash).slice(1);
  14145. const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime);
  14146. const replacementString = typeof replacement === 'string'
  14147. ? JSON.stringify(replacement).slice(1, -1)
  14148. : `"+${replacement.runtime}+"`;
  14149. s.update(match.index, match.index + full.length, replacementString);
  14150. }
  14151. return s;
  14152. }
  14153. /**
  14154. * Also supports loading plain strings with import text from './foo.txt?raw'
  14155. */
  14156. function assetPlugin(config) {
  14157. registerCustomMime();
  14158. return {
  14159. name: 'vite:asset',
  14160. buildStart() {
  14161. assetCache.set(config, new Map());
  14162. generatedAssets.set(config, new Map());
  14163. },
  14164. resolveId(id) {
  14165. if (!config.assetsInclude(cleanUrl(id))) {
  14166. return;
  14167. }
  14168. // imports to absolute urls pointing to files in /public
  14169. // will fail to resolve in the main resolver. handle them here.
  14170. const publicFile = checkPublicFile(id, config);
  14171. if (publicFile) {
  14172. return id;
  14173. }
  14174. },
  14175. async load(id) {
  14176. if (id[0] === '\0') {
  14177. // Rollup convention, this id should be handled by the
  14178. // plugin that marked it with \0
  14179. return;
  14180. }
  14181. // raw requests, read from disk
  14182. if (rawRE.test(id)) {
  14183. const file = checkPublicFile(id, config) || cleanUrl(id);
  14184. // raw query, read file and return as string
  14185. return `export default ${JSON.stringify(await promises$2.readFile(file, 'utf-8'))}`;
  14186. }
  14187. if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) {
  14188. return;
  14189. }
  14190. id = id.replace(urlRE, '$1').replace(unnededFinalQueryCharRE, '');
  14191. const url = await fileToUrl(id, config, this);
  14192. return `export default ${JSON.stringify(url)}`;
  14193. },
  14194. renderChunk(code, chunk, opts) {
  14195. const s = renderAssetUrlInJS(this, config, chunk, opts, code);
  14196. if (s) {
  14197. return {
  14198. code: s.toString(),
  14199. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null,
  14200. };
  14201. }
  14202. else {
  14203. return null;
  14204. }
  14205. },
  14206. generateBundle(_, bundle) {
  14207. // do not emit assets for SSR build
  14208. if (config.command === 'build' &&
  14209. config.build.ssr &&
  14210. !config.build.ssrEmitAssets) {
  14211. for (const file in bundle) {
  14212. if (bundle[file].type === 'asset' &&
  14213. !file.endsWith('ssr-manifest.json') &&
  14214. !jsSourceMapRE.test(file)) {
  14215. delete bundle[file];
  14216. }
  14217. }
  14218. }
  14219. },
  14220. };
  14221. }
  14222. function checkPublicFile(url, { publicDir }) {
  14223. // note if the file is in /public, the resolver would have returned it
  14224. // as-is so it's not going to be a fully resolved path.
  14225. if (!publicDir || url[0] !== '/') {
  14226. return;
  14227. }
  14228. const publicFile = path$o.join(publicDir, cleanUrl(url));
  14229. if (!publicFile.startsWith(publicDir)) {
  14230. // can happen if URL starts with '../'
  14231. return;
  14232. }
  14233. if (fs$l.existsSync(publicFile)) {
  14234. return publicFile;
  14235. }
  14236. else {
  14237. return;
  14238. }
  14239. }
  14240. async function fileToUrl(id, config, ctx) {
  14241. if (config.command === 'serve') {
  14242. return fileToDevUrl(id, config);
  14243. }
  14244. else {
  14245. return fileToBuiltUrl(id, config, ctx);
  14246. }
  14247. }
  14248. function fileToDevUrl(id, config) {
  14249. let rtn;
  14250. if (checkPublicFile(id, config)) {
  14251. // in public dir, keep the url as-is
  14252. rtn = id;
  14253. }
  14254. else if (id.startsWith(config.root)) {
  14255. // in project root, infer short public path
  14256. rtn = '/' + path$o.posix.relative(config.root, id);
  14257. }
  14258. else {
  14259. // outside of project root, use absolute fs path
  14260. // (this is special handled by the serve static middleware
  14261. rtn = path$o.posix.join(FS_PREFIX, id);
  14262. }
  14263. const base = joinUrlSegments(config.server?.origin ?? '', config.base);
  14264. return joinUrlSegments(base, removeLeadingSlash(rtn));
  14265. }
  14266. function getPublicAssetFilename(hash, config) {
  14267. return publicAssetUrlCache.get(config)?.get(hash);
  14268. }
  14269. const publicAssetUrlCache = new WeakMap();
  14270. const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
  14271. function publicFileToBuiltUrl(url, config) {
  14272. if (config.command !== 'build') {
  14273. // We don't need relative base or renderBuiltUrl support during dev
  14274. return joinUrlSegments(config.base, url);
  14275. }
  14276. const hash = getHash(url);
  14277. let cache = publicAssetUrlCache.get(config);
  14278. if (!cache) {
  14279. cache = new Map();
  14280. publicAssetUrlCache.set(config, cache);
  14281. }
  14282. if (!cache.get(hash)) {
  14283. cache.set(hash, url);
  14284. }
  14285. return `__VITE_PUBLIC_ASSET__${hash}__`;
  14286. }
  14287. const GIT_LFS_PREFIX = Buffer$1.from('version https://git-lfs.github.com');
  14288. function isGitLfsPlaceholder(content) {
  14289. if (content.length < GIT_LFS_PREFIX.length)
  14290. return false;
  14291. // Check whether the content begins with the characteristic string of Git LFS placeholders
  14292. return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0;
  14293. }
  14294. /**
  14295. * Register an asset to be emitted as part of the bundle (if necessary)
  14296. * and returns the resolved public URL
  14297. */
  14298. async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) {
  14299. if (!skipPublicCheck && checkPublicFile(id, config)) {
  14300. return publicFileToBuiltUrl(id, config);
  14301. }
  14302. const cache = assetCache.get(config);
  14303. const cached = cache.get(id);
  14304. if (cached) {
  14305. return cached;
  14306. }
  14307. const file = cleanUrl(id);
  14308. const content = await promises$2.readFile(file);
  14309. let url;
  14310. if (config.build.lib ||
  14311. (!file.endsWith('.svg') &&
  14312. !file.endsWith('.html') &&
  14313. content.length < Number(config.build.assetsInlineLimit) &&
  14314. !isGitLfsPlaceholder(content))) {
  14315. if (config.build.lib && isGitLfsPlaceholder(content)) {
  14316. config.logger.warn(colors$1.yellow(`Inlined file ${id} was not downloaded via Git LFS`));
  14317. }
  14318. const mimeType = lookup(file) ?? 'application/octet-stream';
  14319. // base64 inlined as a string
  14320. url = `data:${mimeType};base64,${content.toString('base64')}`;
  14321. }
  14322. else {
  14323. // emit as asset
  14324. const { search, hash } = parse$i(id);
  14325. const postfix = (search || '') + (hash || '');
  14326. const referenceId = pluginContext.emitFile({
  14327. // Ignore directory structure for asset file names
  14328. name: path$o.basename(file),
  14329. type: 'asset',
  14330. source: content,
  14331. });
  14332. const originalName = normalizePath$3(path$o.relative(config.root, file));
  14333. generatedAssets.get(config).set(referenceId, { originalName });
  14334. url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE
  14335. }
  14336. cache.set(id, url);
  14337. return url;
  14338. }
  14339. async function urlToBuiltUrl(url, importer, config, pluginContext) {
  14340. if (checkPublicFile(url, config)) {
  14341. return publicFileToBuiltUrl(url, config);
  14342. }
  14343. const file = url[0] === '/'
  14344. ? path$o.join(config.root, url)
  14345. : path$o.join(path$o.dirname(importer), url);
  14346. return fileToBuiltUrl(file, config, pluginContext,
  14347. // skip public check since we just did it above
  14348. true);
  14349. }
  14350. function manifestPlugin(config) {
  14351. const manifest = {};
  14352. let outputCount;
  14353. return {
  14354. name: 'vite:manifest',
  14355. buildStart() {
  14356. outputCount = 0;
  14357. },
  14358. generateBundle({ format }, bundle) {
  14359. function getChunkName(chunk) {
  14360. if (chunk.facadeModuleId) {
  14361. let name = normalizePath$3(path$o.relative(config.root, chunk.facadeModuleId));
  14362. if (format === 'system' && !chunk.name.includes('-legacy')) {
  14363. const ext = path$o.extname(name);
  14364. const endPos = ext.length !== 0 ? -ext.length : undefined;
  14365. name = name.slice(0, endPos) + `-legacy` + ext;
  14366. }
  14367. return name.replace(/\0/g, '');
  14368. }
  14369. else {
  14370. return `_` + path$o.basename(chunk.fileName);
  14371. }
  14372. }
  14373. function getInternalImports(imports) {
  14374. const filteredImports = [];
  14375. for (const file of imports) {
  14376. if (bundle[file] === undefined) {
  14377. continue;
  14378. }
  14379. filteredImports.push(getChunkName(bundle[file]));
  14380. }
  14381. return filteredImports;
  14382. }
  14383. function createChunk(chunk) {
  14384. const manifestChunk = {
  14385. file: chunk.fileName,
  14386. };
  14387. if (chunk.facadeModuleId) {
  14388. manifestChunk.src = getChunkName(chunk);
  14389. }
  14390. if (chunk.isEntry) {
  14391. manifestChunk.isEntry = true;
  14392. }
  14393. if (chunk.isDynamicEntry) {
  14394. manifestChunk.isDynamicEntry = true;
  14395. }
  14396. if (chunk.imports.length) {
  14397. const internalImports = getInternalImports(chunk.imports);
  14398. if (internalImports.length > 0) {
  14399. manifestChunk.imports = internalImports;
  14400. }
  14401. }
  14402. if (chunk.dynamicImports.length) {
  14403. const internalImports = getInternalImports(chunk.dynamicImports);
  14404. if (internalImports.length > 0) {
  14405. manifestChunk.dynamicImports = internalImports;
  14406. }
  14407. }
  14408. if (chunk.viteMetadata?.importedCss.size) {
  14409. manifestChunk.css = [...chunk.viteMetadata.importedCss];
  14410. }
  14411. if (chunk.viteMetadata?.importedAssets.size) {
  14412. manifestChunk.assets = [...chunk.viteMetadata.importedAssets];
  14413. }
  14414. return manifestChunk;
  14415. }
  14416. function createAsset(asset, src, isEntry) {
  14417. const manifestChunk = {
  14418. file: asset.fileName,
  14419. src,
  14420. };
  14421. if (isEntry)
  14422. manifestChunk.isEntry = true;
  14423. return manifestChunk;
  14424. }
  14425. const fileNameToAssetMeta = new Map();
  14426. const assets = generatedAssets.get(config);
  14427. assets.forEach((asset, referenceId) => {
  14428. const fileName = this.getFileName(referenceId);
  14429. fileNameToAssetMeta.set(fileName, asset);
  14430. });
  14431. const fileNameToAsset = new Map();
  14432. for (const file in bundle) {
  14433. const chunk = bundle[file];
  14434. if (chunk.type === 'chunk') {
  14435. manifest[getChunkName(chunk)] = createChunk(chunk);
  14436. }
  14437. else if (chunk.type === 'asset' && typeof chunk.name === 'string') {
  14438. // Add every unique asset to the manifest, keyed by its original name
  14439. const assetMeta = fileNameToAssetMeta.get(chunk.fileName);
  14440. const src = assetMeta?.originalName ?? chunk.name;
  14441. const asset = createAsset(chunk, src, assetMeta?.isEntry);
  14442. manifest[src] = asset;
  14443. fileNameToAsset.set(chunk.fileName, asset);
  14444. }
  14445. }
  14446. // Add deduplicated assets to the manifest
  14447. assets.forEach(({ originalName }, referenceId) => {
  14448. if (!manifest[originalName]) {
  14449. const fileName = this.getFileName(referenceId);
  14450. const asset = fileNameToAsset.get(fileName);
  14451. if (asset) {
  14452. manifest[originalName] = asset;
  14453. }
  14454. }
  14455. });
  14456. outputCount++;
  14457. const output = config.build.rollupOptions?.output;
  14458. const outputLength = Array.isArray(output) ? output.length : 1;
  14459. if (outputCount >= outputLength) {
  14460. this.emitFile({
  14461. fileName: typeof config.build.manifest === 'string'
  14462. ? config.build.manifest
  14463. : 'manifest.json',
  14464. type: 'asset',
  14465. source: jsonStableStringify$1(manifest, { space: 2 }),
  14466. });
  14467. }
  14468. },
  14469. };
  14470. }
  14471. // This is based on @rollup/plugin-data-uri
  14472. const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
  14473. const base64RE = /base64/i;
  14474. const dataUriPrefix = `\0/@data-uri/`;
  14475. /**
  14476. * Build only, since importing from a data URI works natively.
  14477. */
  14478. function dataURIPlugin() {
  14479. let resolved;
  14480. return {
  14481. name: 'vite:data-uri',
  14482. buildStart() {
  14483. resolved = new Map();
  14484. },
  14485. resolveId(id) {
  14486. if (!dataUriRE.test(id)) {
  14487. return;
  14488. }
  14489. const uri = new URL$3(id);
  14490. if (uri.protocol !== 'data:') {
  14491. return;
  14492. }
  14493. const match = uri.pathname.match(dataUriRE);
  14494. if (!match) {
  14495. return;
  14496. }
  14497. const [, mime, format, data] = match;
  14498. if (mime !== 'text/javascript') {
  14499. throw new Error(`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`);
  14500. }
  14501. // decode data
  14502. const base64 = format && base64RE.test(format.substring(1));
  14503. const content = base64
  14504. ? Buffer.from(data, 'base64').toString('utf-8')
  14505. : data;
  14506. resolved.set(id, content);
  14507. return dataUriPrefix + id;
  14508. },
  14509. load(id) {
  14510. if (id.startsWith(dataUriPrefix)) {
  14511. return resolved.get(id.slice(dataUriPrefix.length));
  14512. }
  14513. },
  14514. };
  14515. }
  14516. /* es-module-lexer 1.2.1 */
  14517. const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init.then((()=>parse$e(E)));const I=E.length+1,o=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;o>0&&C.memory.grow(Math.ceil(o/65536));const D=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,D,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const K=[],k=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),o=C.se();let D;C.ip()&&(D=J(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),K.push({n:D,s:A,e:Q,ss:I,se:o,d:g,a:B});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),o=I[0],D=B<0?void 0:E.slice(B,g),K=D?D[0]:"";k.push({s:A,e:Q,ls:B,le:g,n:'"'===o||"'"===o?J(I):I,ln:'"'===K||"'"===K?J(D):D});}function J(A){try{return (0, eval)(A)}catch(A){}}return [K,k,!!C.f()]}function Q(A,Q){const B=A.length;let C=0;for(;C<B;){const B=A.charCodeAt(C);Q[C++]=(255&B)<<8|B>>>8;}}function B(A,Q){const B=A.length;let C=0;for(;C<B;)Q[C]=A.charCodeAt(C++);}let C;const init=WebAssembly.compile((E="AGFzbQEAAAABKghgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gAn9/AAMvLgABAQICAgICAgICAgICAgICAgIAAwMDBAQAAAADAAAAAAMDAAUGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUGw8gALfwBBsPIACwdwEwZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAmFpAAgCaWQACQJpcAAKAmVzAAsCZWUADANlbHMADQNlbGUADgJyaQAPAnJlABABZgARBXBhcnNlABILX19oZWFwX2Jhc2UDAQqHPC5oAQF/QQAgADYC9AlBACgC0AkiASAAQQF0aiIAQQA7AQBBACAAQQJqIgA2AvgJQQAgADYC/AlBAEEANgLUCUEAQQA2AuQJQQBBADYC3AlBAEEANgLYCUEAQQA2AuwJQQBBADYC4AkgAQufAQEDf0EAKALkCSEEQQBBACgC/AkiBTYC5AlBACAENgLoCUEAIAVBIGo2AvwJIARBHGpB1AkgBBsgBTYCAEEAKALICSEEQQAoAsQJIQYgBSABNgIAIAUgADYCCCAFIAIgAkECakEAIAYgA0YbIAQgA0YbNgIMIAUgAzYCFCAFQQA2AhAgBSACNgIEIAVBADYCHCAFQQAoAsQJIANGOgAYC1YBAX9BACgC7AkiBEEQakHYCSAEG0EAKAL8CSIENgIAQQAgBDYC7AlBACAEQRRqNgL8CSAEQQA2AhAgBCADNgIMIAQgAjYCCCAEIAE2AgQgBCAANgIACwgAQQAoAoAKCxUAQQAoAtwJKAIAQQAoAtAJa0EBdQseAQF/QQAoAtwJKAIEIgBBACgC0AlrQQF1QX8gABsLFQBBACgC3AkoAghBACgC0AlrQQF1Cx4BAX9BACgC3AkoAgwiAEEAKALQCWtBAXVBfyAAGwseAQF/QQAoAtwJKAIQIgBBACgC0AlrQQF1QX8gABsLOwEBfwJAQQAoAtwJKAIUIgBBACgCxAlHDQBBfw8LAkAgAEEAKALICUcNAEF+DwsgAEEAKALQCWtBAXULCwBBACgC3AktABgLFQBBACgC4AkoAgBBACgC0AlrQQF1CxUAQQAoAuAJKAIEQQAoAtAJa0EBdQseAQF/QQAoAuAJKAIIIgBBACgC0AlrQQF1QX8gABsLHgEBf0EAKALgCSgCDCIAQQAoAtAJa0EBdUF/IAAbCyUBAX9BAEEAKALcCSIAQRxqQdQJIAAbKAIAIgA2AtwJIABBAEcLJQEBf0EAQQAoAuAJIgBBEGpB2AkgABsoAgAiADYC4AkgAEEARwsIAEEALQCECgvmDAEGfyMAQYDQAGsiACQAQQBBAToAhApBAEEAKALMCTYCjApBAEEAKALQCUF+aiIBNgKgCkEAIAFBACgC9AlBAXRqIgI2AqQKQQBBADsBhgpBAEEAOwGICkEAQQA6AJAKQQBBADYCgApBAEEAOgDwCUEAIABBgBBqNgKUCkEAIAA2ApgKQQBBADoAnAoCQAJAAkACQANAQQAgAUECaiIDNgKgCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BiAoNASADEBNFDQEgAUEEakGCCEEKEC0NARAUQQAtAIQKDQFBAEEAKAKgCiIBNgKMCgwHCyADEBNFDQAgAUEEakGMCEEKEC0NABAVC0EAQQAoAqAKNgKMCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAWDAELQQEQFwtBACgCpAohAkEAKAKgCiEBDAALC0EAIQIgAyEBQQAtAPAJDQIMAQtBACABNgKgCkEAQQA6AIQKCwNAQQAgAUECaiIDNgKgCgJAAkACQAJAAkACQAJAAkACQCABQQAoAqQKTw0AIAMvAQAiAkF3akEFSQ0IAkACQAJAAkACQAJAAkACQAJAAkAgAkFgag4KEhEGEREREQUBAgALAkACQAJAAkAgAkGgf2oOCgsUFAMUARQUFAIACyACQYV/ag4DBRMGCQtBAC8BiAoNEiADEBNFDRIgAUEEakGCCEEKEC0NEhAUDBILIAMQE0UNESABQQRqQYwIQQoQLQ0REBUMEQsgAxATRQ0QIAEpAARC7ICEg7COwDlSDRAgAS8BDCIDQXdqIgFBF0sNDkEBIAF0QZ+AgARxRQ0ODA8LQQBBAC8BiAoiAUEBajsBiApBACgClAogAUEDdGoiAUEBNgIAIAFBACgCjAo2AgQMDwtBAC8BiAoiAkUNC0EAIAJBf2oiBDsBiApBAC8BhgoiAkUNDiACQQJ0QQAoApgKakF8aigCACIFKAIUQQAoApQKIARB//8DcUEDdGooAgRHDQ4CQCAFKAIEDQAgBSADNgIEC0EAIAJBf2o7AYYKIAUgAUEEajYCDAwOCwJAQQAoAowKIgEvAQBBKUcNAEEAKALkCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAugJIgM2AuQJAkAgA0UNACADQQA2AhwMAQtBAEEANgLUCQtBAEEALwGICiIDQQFqOwGICkEAKAKUCiADQQN0aiIDQQZBAkEALQCcChs2AgAgAyABNgIEQQBBADoAnAoMDQtBAC8BiAoiAUUNCUEAIAFBf2oiATsBiApBACgClAogAUH//wNxQQN0aigCAEEERg0EDAwLQScQGAwLC0EiEBgMCgsgAkEvRw0JAkACQCABLwEEIgFBKkYNACABQS9HDQEQFgwMC0EBEBcMCwsCQAJAQQAoAowKIgEvAQAiAxAZRQ0AAkACQCADQVVqDgQACAEDCAsgAUF+ai8BAEErRg0GDAcLIAFBfmovAQBBLUYNBQwGCwJAIANB/QBGDQAgA0EpRw0FQQAoApQKQQAvAYgKQQN0aigCBBAaRQ0FDAYLQQAoApQKQQAvAYgKQQN0aiICKAIEEBsNBSACKAIAQQZGDQUMBAsgAUF+ai8BAEFQakH//wNxQQpJDQMMBAtBACgClApBAC8BiAoiAUEDdCIDakEAKAKMCjYCBEEAIAFBAWo7AYgKQQAoApQKIANqQQM2AgALEBwMBwtBAC0A8AlBAC8BhgpBAC8BiApyckUhAgwJCyABEB0NACADRQ0AIANBL0ZBAC0AkApBAEdxDQAgAUF+aiEBQQAoAtAJIQICQANAIAFBAmoiBCACTQ0BQQAgATYCjAogAS8BACEDIAFBfmoiBCEBIAMQHkUNAAsgBEECaiEEC0EBIQUgA0H//wNxEB9FDQEgBEF+aiEBAkADQCABQQJqIgMgAk0NAUEAIAE2AowKIAEvAQAhAyABQX5qIgQhASADEB8NAAsgBEECaiEDCyADECBFDQEQIUEAQQA6AJAKDAULECFBACEFC0EAIAU6AJAKDAMLECJBACECDAULIANBoAFHDQELQQBBAToAnAoLQQBBACgCoAo2AowKC0EAKAKgCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC0AkgAEcNAEEBDwsgAEF+ahAjC80JAQV/QQBBACgCoAoiAEEMaiIBNgKgCkEAKALsCSECQQEQJyEDAkACQAJAAkACQAJAAkACQAJAAkBBACgCoAoiBCABRw0AIAMQJkUNAQsCQAJAAkACQCADQSpGDQAgA0H7AEcNAUEAIARBAmo2AqAKQQEQJyEEQQAoAqAKIQEDQAJAAkAgBEH//wNxIgNBIkYNACADQSdGDQAgAxAqGkEAKAKgCiEDDAELIAMQGEEAQQAoAqAKQQJqIgM2AqAKC0EBECcaAkAgASADECsiBEEsRw0AQQBBACgCoApBAmo2AqAKQQEQJyEEC0EAKAKgCiEDIARB/QBGDQMgAyABRg0NIAMhASADQQAoAqQKTQ0ADA0LC0EAIARBAmo2AqAKQQEQJxpBACgCoAoiAyADECsaDAILQQBBADoAhAoCQAJAAkACQAJAAkAgA0Gff2oODAIIBAEIAwgICAgIBQALIANB9gBGDQQMBwtBACAEQQ5qIgM2AqAKAkACQAJAQQEQJ0Gff2oOBgAQAhAQARALQQAoAqAKIgEpAAJC84Dkg+CNwDFSDQ8gAS8BChAfRQ0PQQAgAUEKajYCoApBABAnGgtBACgCoAoiAUECakGiCEEOEC0NDiABLwEQIgBBd2oiAkEXSw0LQQEgAnRBn4CABHFFDQsMDAtBACgCoAoiASkAAkLsgISDsI7AOVINDSABLwEKIgBBd2oiAkEXTQ0HDAgLQQAgBEEKajYCoApBABAnGkEAKAKgCiEEC0EAIARBEGo2AqAKAkBBARAnIgRBKkcNAEEAQQAoAqAKQQJqNgKgCkEBECchBAtBACgCoAohAyAEECoaIANBACgCoAoiBCADIAQQAkEAQQAoAqAKQX5qNgKgCg8LAkAgBCkAAkLsgISDsI7AOVINACAELwEKEB5FDQBBACAEQQpqNgKgCkEBECchBEEAKAKgCiEDIAQQKhogA0EAKAKgCiIEIAMgBBACQQBBACgCoApBfmo2AqAKDwtBACAEQQRqIgQ2AqAKC0EAIARBBGoiAzYCoApBAEEAOgCECgJAA0BBACADQQJqNgKgCkEBECchBEEAKAKgCiEDIAQQKkEgckH7AEYNAUEAKAKgCiIEIANGDQQgAyAEIAMgBBACQQEQJ0EsRw0BQQAoAqAKIQMMAAsLQQBBACgCoApBfmo2AqAKDwtBACADQQJqNgKgCgtBARAnIQRBACgCoAohAwJAIARB5gBHDQAgA0ECakGcCEEGEC0NAEEAIANBCGo2AqAKIABBARAnECkgAkEQakHYCSACGyEDA0AgAygCACIDRQ0CIANCADcCCCADQRBqIQMMAAsLQQAgA0F+ajYCoAoLDwtBASACdEGfgIAEcQ0BCyAAQaABRg0AIABB+wBHDQQLQQAgAUEKajYCoApBARAnIgFB+wBGDQMMAgsCQCAAQVhqDgMBAwEACyAAQaABRw0CC0EAIAFBEGo2AqAKAkBBARAnIgFBKkcNAEEAQQAoAqAKQQJqNgKgCkEBECchAQsgAUEoRg0BC0EAKAKgCiECIAEQKhpBACgCoAoiASACTQ0AIAQgAyACIAEQAkEAQQAoAqAKQX5qNgKgCg8LIAQgA0EAQQAQAkEAIARBDGo2AqAKDwsQIgvUBgEEf0EAQQAoAqAKIgBBDGoiATYCoAoCQAJAAkACQAJAAkACQAJAAkACQEEBECciAkFZag4IBAIBBAEBAQMACyACQSJGDQMgAkH7AEYNBAtBACgCoAogAUcNAkEAIABBCmo2AqAKDwtBACgClApBAC8BiAoiAkEDdGoiAUEAKAKgCjYCBEEAIAJBAWo7AYgKIAFBBTYCAEEAKAKMCi8BAEEuRg0DQQBBACgCoAoiAUECajYCoApBARAnIQIgAEEAKAKgCkEAIAEQAUEAQQAvAYYKIgFBAWo7AYYKQQAoApgKIAFBAnRqQQAoAuQJNgIAAkAgAkEiRg0AIAJBJ0YNAEEAQQAoAqAKQX5qNgKgCg8LIAIQGEEAQQAoAqAKQQJqIgI2AqAKAkACQAJAQQEQJ0FXag4EAQICAAILQQBBACgCoApBAmo2AqAKQQEQJxpBACgC5AkiASACNgIEIAFBAToAGCABQQAoAqAKIgI2AhBBACACQX5qNgKgCg8LQQAoAuQJIgEgAjYCBCABQQE6ABhBAEEALwGICkF/ajsBiAogAUEAKAKgCkECajYCDEEAQQAvAYYKQX9qOwGGCg8LQQBBACgCoApBfmo2AqAKDwtBAEEAKAKgCkECajYCoApBARAnQe0ARw0CQQAoAqAKIgJBAmpBlghBBhAtDQICQEEAKAKMCiIBECgNACABLwEAQS5GDQMLIAAgACACQQhqQQAoAsgJEAEPC0EALwGICg0CQQAoAqAKIQJBACgCpAohAwNAIAIgA08NBQJAAkAgAi8BACIBQSdGDQAgAUEiRw0BCyAAIAEQKQ8LQQAgAkECaiICNgKgCgwACwtBACgCoAohAkEALwGICg0CAkADQAJAAkACQCACQQAoAqQKTw0AQQEQJyICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKgCkECajYCoAoLQQEQJyEBQQAoAqAKIQICQCABQeYARw0AIAJBAmpBnAhBBhAtDQgLQQAgAkEIajYCoApBARAnIgJBIkYNAyACQSdGDQMMBwsgAhAYC0EAQQAoAqAKQQJqIgI2AqAKDAALCyAAIAIQKQsPC0EAQQAoAqAKQX5qNgKgCg8LQQAgAkF+ajYCoAoPCxAiC0cBA39BACgCoApBAmohAEEAKAKkCiEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2ag4EAQAAAQALC0EAIAI2AqAKC5gBAQN/QQBBACgCoAoiAUECajYCoAogAUEGaiEBQQAoAqQKIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoOBAIEBAIECyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2AqAKDAELIAFBfmohAQtBACABNgKgCg8LIAFBAmohAQwACwuIAQEEf0EAKAKgCiEBQQAoAqQKIQICQAJAA0AgASIDQQJqIQEgAyACTw0BIAEvAQAiBCAARg0CAkAgBEHcAEYNACAEQXZqDgQCAQECAQsgA0EEaiEBIAMvAQRBDUcNACADQQZqIAEgAy8BBkEKRhshAQwACwtBACABNgKgChAiDwtBACABNgKgCgtsAQF/AkACQCAAQV9qIgFBBUsNAEEBIAF0QTFxDQELIABBRmpB//8DcUEGSQ0AIABBKUcgAEFYakH//wNxQQdJcQ0AAkAgAEGlf2oOBAEAAAEACyAAQf0ARyAAQYV/akH//wNxQQRJcQ8LQQELLgEBf0EBIQECQCAAQZYJQQUQJA0AIABBoAlBAxAkDQAgAEGmCUECECQhAQsgAQuDAQECf0EBIQECQAJAAkACQAJAAkAgAC8BACICQUVqDgQFBAQBAAsCQCACQZt/ag4EAwQEAgALIAJBKUYNBCACQfkARw0DIABBfmpBsglBBhAkDwsgAEF+ai8BAEE9Rg8LIABBfmpBqglBBBAkDwsgAEF+akG+CUEDECQPC0EAIQELIAEL3gEBBH9BACgCoAohAEEAKAKkCiEBAkACQAJAA0AgACICQQJqIQAgAiABTw0BAkACQAJAIAAvAQAiA0Gkf2oOBQIDAwMBAAsgA0EkRw0CIAIvAQRB+wBHDQJBACACQQRqIgA2AqAKQQBBAC8BiAoiAkEBajsBiApBACgClAogAkEDdGoiAkEENgIAIAIgADYCBA8LQQAgADYCoApBAEEALwGICkF/aiIAOwGICkEAKAKUCiAAQf//A3FBA3RqKAIAQQNHDQMMBAsgAkEEaiEADAALC0EAIAA2AqAKCxAiCwu0AwECf0EAIQECQAJAAkACQAJAAkACQAJAAkACQCAALwEAQZx/ag4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEF+ai8BAEGXf2oOBAAKCgEKCyAAQXxqQboIQQIQJA8LIABBfGpBvghBAxAkDwsCQAJAAkAgAEF+ai8BAEGNf2oOAwABAgoLAkAgAEF8ai8BACICQeEARg0AIAJB7ABHDQogAEF6akHlABAlDwsgAEF6akHjABAlDwsgAEF8akHECEEEECQPCyAAQXxqQcwIQQYQJA8LIABBfmovAQBB7wBHDQYgAEF8ai8BAEHlAEcNBgJAIABBemovAQAiAkHwAEYNACACQeMARw0HIABBeGpB2AhBBhAkDwsgAEF4akHkCEECECQPCyAAQX5qQegIQQQQJA8LQQEhASAAQX5qIgBB6QAQJQ0EIABB8AhBBRAkDwsgAEF+akHkABAlDwsgAEF+akH6CEEHECQPCyAAQX5qQYgJQQQQJA8LAkAgAEF+ai8BACICQe8ARg0AIAJB5QBHDQEgAEF8akHuABAlDwsgAEF8akGQCUEDECQhAQsgAQs0AQF/QQEhAQJAIABBd2pB//8DcUEFSQ0AIABBgAFyQaABRg0AIABBLkcgABAmcSEBCyABCzABAX8CQAJAIABBd2oiAUEXSw0AQQEgAXRBjYCABHENAQsgAEGgAUYNAEEADwtBAQtOAQJ/QQAhAQJAAkAgAC8BACICQeUARg0AIAJB6wBHDQEgAEF+akHoCEEEECQPCyAAQX5qLwEAQfUARw0AIABBfGpBzAhBBhAkIQELIAELcAECfwJAAkADQEEAQQAoAqAKIgBBAmoiATYCoAogAEEAKAKkCk8NAQJAAkACQCABLwEAIgFBpX9qDgIBAgALAkAgAUF2ag4EBAMDBAALIAFBL0cNAgwECxAsGgwBC0EAIABBBGo2AqAKDAALCxAiCws1AQF/QQBBAToA8AlBACgCoAohAEEAQQAoAqQKQQJqNgKgCkEAIABBACgC0AlrQQF1NgKACgtDAQJ/QQEhAQJAIAAvAQAiAkF3akH//wNxQQVJDQAgAkGAAXJBoAFGDQBBACEBIAIQJkUNACACQS5HIAAQKHIPCyABC0YBA39BACEDAkAgACACQQF0IgJrIgRBAmoiAEEAKALQCSIFSQ0AIAAgASACEC0NAAJAIAAgBUcNAEEBDwsgBBAjIQMLIAMLPQECf0EAIQICQEEAKALQCSIDIABLDQAgAC8BACABRw0AAkAgAyAARw0AQQEPCyAAQX5qLwEAEB4hAgsgAgtoAQJ/QQEhAQJAAkAgAEFfaiICQQVLDQBBASACdEExcQ0BCyAAQfj/A3FBKEYNACAAQUZqQf//A3FBBkkNAAJAIABBpX9qIgJBA0sNACACQQFHDQELIABBhX9qQf//A3FBBEkhAQsgAQucAQEDf0EAKAKgCiEBAkADQAJAAkAgAS8BACICQS9HDQACQCABLwECIgFBKkYNACABQS9HDQQQFgwCCyAAEBcMAQsCQAJAIABFDQAgAkF3aiIBQRdLDQFBASABdEGfgIAEcUUNAQwCCyACEB9FDQMMAQsgAkGgAUcNAgtBAEEAKAKgCiIDQQJqIgE2AqAKIANBACgCpApJDQALCyACCzEBAX9BACEBAkAgAC8BAEEuRw0AIABBfmovAQBBLkcNACAAQXxqLwEAQS5GIQELIAELiQQBAX8CQCABQSJGDQAgAUEnRg0AECIPC0EAKAKgCiECIAEQGCAAIAJBAmpBACgCoApBACgCxAkQAUEAQQAoAqAKQQJqNgKgCgJAAkACQAJAQQAQJyIBQeEARg0AIAFB9wBGDQFBACgCoAohAQwCC0EAKAKgCiIBQQJqQbAIQQoQLQ0BQQYhAAwCC0EAKAKgCiIBLwECQekARw0AIAEvAQRB9ABHDQBBBCEAIAEvAQZB6ABGDQELQQAgAUF+ajYCoAoPC0EAIAEgAEEBdGo2AqAKAkBBARAnQfsARg0AQQAgATYCoAoPC0EAKAKgCiICIQADQEEAIABBAmo2AqAKAkACQAJAQQEQJyIAQSJGDQAgAEEnRw0BQScQGEEAQQAoAqAKQQJqNgKgCkEBECchAAwCC0EiEBhBAEEAKAKgCkECajYCoApBARAnIQAMAQsgABAqIQALAkAgAEE6Rg0AQQAgATYCoAoPC0EAQQAoAqAKQQJqNgKgCgJAQQEQJyIAQSJGDQAgAEEnRg0AQQAgATYCoAoPCyAAEBhBAEEAKAKgCkECajYCoAoCQAJAQQEQJyIAQSxGDQAgAEH9AEYNAUEAIAE2AqAKDwtBAEEAKAKgCkECajYCoApBARAnQf0ARg0AQQAoAqAKIQAMAQsLQQAoAuQJIgEgAjYCECABQQAoAqAKQQJqNgIMC20BAn8CQAJAA0ACQCAAQf//A3EiAUF3aiICQRdLDQBBASACdEGfgIAEcQ0CCyABQaABRg0BIAAhAiABECYNAkEAIQJBAEEAKAKgCiIAQQJqNgKgCiAALwECIgANAAwCCwsgACECCyACQf//A3ELqwEBBH8CQAJAQQAoAqAKIgIvAQAiA0HhAEYNACABIQQgACEFDAELQQAgAkEEajYCoApBARAnIQJBACgCoAohBQJAAkAgAkEiRg0AIAJBJ0YNACACECoaQQAoAqAKIQQMAQsgAhAYQQBBACgCoApBAmoiBDYCoAoLQQEQJyEDQQAoAqAKIQILAkAgAiAFRg0AIAUgBEEAIAAgACABRiICG0EAIAEgAhsQAgsgAwtyAQR/QQAoAqAKIQBBACgCpAohAQJAAkADQCAAQQJqIQIgACABTw0BAkACQCACLwEAIgNBpH9qDgIBBAALIAIhACADQXZqDgQCAQECAQsgAEEEaiEADAALC0EAIAI2AqAKECJBAA8LQQAgAjYCoApB3QALSQEDf0EAIQMCQCACRQ0AAkADQCAALQAAIgQgAS0AACIFRw0BIAFBAWohASAAQQFqIQAgAkF/aiICDQAMAgsLIAQgBWshAwsgAwsL4gECAEGACAvEAQAAeABwAG8AcgB0AG0AcABvAHIAdABlAHQAYQByAG8AbQB1AG4AYwB0AGkAbwBuAHMAcwBlAHIAdAB2AG8AeQBpAGUAZABlAGwAZQBjAG8AbgB0AGkAbgBpAG4AcwB0AGEAbgB0AHkAYgByAGUAYQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcwAAQcQJCxABAAAAAgAAAAAEAAAwOQAA","undefined"!=typeof Buffer?Buffer.from(E,"base64"):Uint8Array.from(atob(E),(A=>A.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E;
  14518. var convertSourceMap$1 = {};
  14519. (function (exports) {
  14520. Object.defineProperty(exports, 'commentRegex', {
  14521. get: function getCommentRegex () {
  14522. // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
  14523. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
  14524. }
  14525. });
  14526. Object.defineProperty(exports, 'mapFileCommentRegex', {
  14527. get: function getMapFileCommentRegex () {
  14528. // Matches sourceMappingURL in either // or /* comment styles.
  14529. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
  14530. }
  14531. });
  14532. var decodeBase64;
  14533. if (typeof Buffer !== 'undefined') {
  14534. if (typeof Buffer.from === 'function') {
  14535. decodeBase64 = decodeBase64WithBufferFrom;
  14536. } else {
  14537. decodeBase64 = decodeBase64WithNewBuffer;
  14538. }
  14539. } else {
  14540. decodeBase64 = decodeBase64WithAtob;
  14541. }
  14542. function decodeBase64WithBufferFrom(base64) {
  14543. return Buffer.from(base64, 'base64').toString();
  14544. }
  14545. function decodeBase64WithNewBuffer(base64) {
  14546. if (typeof value === 'number') {
  14547. throw new TypeError('The value to decode must not be of type number.');
  14548. }
  14549. return new Buffer(base64, 'base64').toString();
  14550. }
  14551. function decodeBase64WithAtob(base64) {
  14552. return decodeURIComponent(escape(atob(base64)));
  14553. }
  14554. function stripComment(sm) {
  14555. return sm.split(',').pop();
  14556. }
  14557. function readFromFileMap(sm, read) {
  14558. var r = exports.mapFileCommentRegex.exec(sm);
  14559. // for some odd reason //# .. captures in 1 and /* .. */ in 2
  14560. var filename = r[1] || r[2];
  14561. try {
  14562. var sm = read(filename);
  14563. if (sm != null && typeof sm.catch === 'function') {
  14564. return sm.catch(throwError);
  14565. } else {
  14566. return sm;
  14567. }
  14568. } catch (e) {
  14569. throwError(e);
  14570. }
  14571. function throwError(e) {
  14572. throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack);
  14573. }
  14574. }
  14575. function Converter (sm, opts) {
  14576. opts = opts || {};
  14577. if (opts.hasComment) {
  14578. sm = stripComment(sm);
  14579. }
  14580. if (opts.encoding === 'base64') {
  14581. sm = decodeBase64(sm);
  14582. } else if (opts.encoding === 'uri') {
  14583. sm = decodeURIComponent(sm);
  14584. }
  14585. if (opts.isJSON || opts.encoding) {
  14586. sm = JSON.parse(sm);
  14587. }
  14588. this.sourcemap = sm;
  14589. }
  14590. Converter.prototype.toJSON = function (space) {
  14591. return JSON.stringify(this.sourcemap, null, space);
  14592. };
  14593. if (typeof Buffer !== 'undefined') {
  14594. if (typeof Buffer.from === 'function') {
  14595. Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
  14596. } else {
  14597. Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
  14598. }
  14599. } else {
  14600. Converter.prototype.toBase64 = encodeBase64WithBtoa;
  14601. }
  14602. function encodeBase64WithBufferFrom() {
  14603. var json = this.toJSON();
  14604. return Buffer.from(json, 'utf8').toString('base64');
  14605. }
  14606. function encodeBase64WithNewBuffer() {
  14607. var json = this.toJSON();
  14608. if (typeof json === 'number') {
  14609. throw new TypeError('The json to encode must not be of type number.');
  14610. }
  14611. return new Buffer(json, 'utf8').toString('base64');
  14612. }
  14613. function encodeBase64WithBtoa() {
  14614. var json = this.toJSON();
  14615. return btoa(unescape(encodeURIComponent(json)));
  14616. }
  14617. Converter.prototype.toURI = function () {
  14618. var json = this.toJSON();
  14619. return encodeURIComponent(json);
  14620. };
  14621. Converter.prototype.toComment = function (options) {
  14622. var encoding, content, data;
  14623. if (options != null && options.encoding === 'uri') {
  14624. encoding = '';
  14625. content = this.toURI();
  14626. } else {
  14627. encoding = ';base64';
  14628. content = this.toBase64();
  14629. }
  14630. data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content;
  14631. return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  14632. };
  14633. // returns copy instead of original
  14634. Converter.prototype.toObject = function () {
  14635. return JSON.parse(this.toJSON());
  14636. };
  14637. Converter.prototype.addProperty = function (key, value) {
  14638. if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
  14639. return this.setProperty(key, value);
  14640. };
  14641. Converter.prototype.setProperty = function (key, value) {
  14642. this.sourcemap[key] = value;
  14643. return this;
  14644. };
  14645. Converter.prototype.getProperty = function (key) {
  14646. return this.sourcemap[key];
  14647. };
  14648. exports.fromObject = function (obj) {
  14649. return new Converter(obj);
  14650. };
  14651. exports.fromJSON = function (json) {
  14652. return new Converter(json, { isJSON: true });
  14653. };
  14654. exports.fromURI = function (uri) {
  14655. return new Converter(uri, { encoding: 'uri' });
  14656. };
  14657. exports.fromBase64 = function (base64) {
  14658. return new Converter(base64, { encoding: 'base64' });
  14659. };
  14660. exports.fromComment = function (comment) {
  14661. var m, encoding;
  14662. comment = comment
  14663. .replace(/^\/\*/g, '//')
  14664. .replace(/\*\/$/g, '');
  14665. m = exports.commentRegex.exec(comment);
  14666. encoding = m && m[4] || 'uri';
  14667. return new Converter(comment, { encoding: encoding, hasComment: true });
  14668. };
  14669. function makeConverter(sm) {
  14670. return new Converter(sm, { isJSON: true });
  14671. }
  14672. exports.fromMapFileComment = function (comment, read) {
  14673. if (typeof read === 'string') {
  14674. throw new Error(
  14675. 'String directory paths are no longer supported with `fromMapFileComment`\n' +
  14676. 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
  14677. )
  14678. }
  14679. var sm = readFromFileMap(comment, read);
  14680. if (sm != null && typeof sm.then === 'function') {
  14681. return sm.then(makeConverter);
  14682. } else {
  14683. return makeConverter(sm);
  14684. }
  14685. };
  14686. // Finds last sourcemap comment in file or returns null if none was found
  14687. exports.fromSource = function (content) {
  14688. var m = content.match(exports.commentRegex);
  14689. return m ? exports.fromComment(m.pop()) : null;
  14690. };
  14691. // Finds last sourcemap comment in file or returns null if none was found
  14692. exports.fromMapFileSource = function (content, read) {
  14693. if (typeof read === 'string') {
  14694. throw new Error(
  14695. 'String directory paths are no longer supported with `fromMapFileSource`\n' +
  14696. 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
  14697. )
  14698. }
  14699. var m = content.match(exports.mapFileCommentRegex);
  14700. return m ? exports.fromMapFileComment(m.pop(), read) : null;
  14701. };
  14702. exports.removeComments = function (src) {
  14703. return src.replace(exports.commentRegex, '');
  14704. };
  14705. exports.removeMapFileComments = function (src) {
  14706. return src.replace(exports.mapFileCommentRegex, '');
  14707. };
  14708. exports.generateMapFileComment = function (file, options) {
  14709. var data = 'sourceMappingURL=' + file;
  14710. return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  14711. };
  14712. } (convertSourceMap$1));
  14713. var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1);
  14714. const debug$e = createDebugger('vite:sourcemap', {
  14715. onlyWhenFocused: true,
  14716. });
  14717. // Virtual modules should be prefixed with a null byte to avoid a
  14718. // false positive "missing source" warning. We also check for certain
  14719. // prefixes used for special handling in esbuildDepPlugin.
  14720. const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
  14721. async function injectSourcesContent(map, file, logger) {
  14722. let sourceRoot;
  14723. try {
  14724. // The source root is undefined for virtual modules and permission errors.
  14725. sourceRoot = await promises$2.realpath(path$o.resolve(path$o.dirname(file), map.sourceRoot || ''));
  14726. }
  14727. catch { }
  14728. const missingSources = [];
  14729. map.sourcesContent = await Promise.all(map.sources.map((sourcePath) => {
  14730. if (sourcePath && !virtualSourceRE.test(sourcePath)) {
  14731. sourcePath = decodeURI(sourcePath);
  14732. if (sourceRoot) {
  14733. sourcePath = path$o.resolve(sourceRoot, sourcePath);
  14734. }
  14735. return promises$2.readFile(sourcePath, 'utf-8').catch(() => {
  14736. missingSources.push(sourcePath);
  14737. return null;
  14738. });
  14739. }
  14740. return null;
  14741. }));
  14742. // Use this command…
  14743. // DEBUG="vite:sourcemap" vite build
  14744. // …to log the missing sources.
  14745. if (missingSources.length) {
  14746. logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
  14747. debug$e?.(`Missing sources:\n ` + missingSources.join(`\n `));
  14748. }
  14749. }
  14750. function genSourceMapUrl(map) {
  14751. if (typeof map !== 'string') {
  14752. map = JSON.stringify(map);
  14753. }
  14754. return `data:application/json;base64,${Buffer.from(map).toString('base64')}`;
  14755. }
  14756. function getCodeWithSourcemap(type, code, map) {
  14757. if (debug$e) {
  14758. code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
  14759. }
  14760. if (type === 'js') {
  14761. code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  14762. }
  14763. else if (type === 'css') {
  14764. code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
  14765. }
  14766. return code;
  14767. }
  14768. function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) {
  14769. let { x_google_ignoreList } = map;
  14770. if (x_google_ignoreList === undefined) {
  14771. x_google_ignoreList = [];
  14772. }
  14773. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  14774. const sourcePath = map.sources[sourcesIndex];
  14775. if (!sourcePath)
  14776. continue;
  14777. const ignoreList = sourcemapIgnoreList(path$o.isAbsolute(sourcePath)
  14778. ? sourcePath
  14779. : path$o.resolve(path$o.dirname(sourcemapPath), sourcePath), sourcemapPath);
  14780. if (logger && typeof ignoreList !== 'boolean') {
  14781. logger.warn('sourcemapIgnoreList function must return a boolean.');
  14782. }
  14783. if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) {
  14784. x_google_ignoreList.push(sourcesIndex);
  14785. }
  14786. }
  14787. if (x_google_ignoreList.length > 0) {
  14788. if (!map.x_google_ignoreList)
  14789. map.x_google_ignoreList = x_google_ignoreList;
  14790. }
  14791. }
  14792. function e(e,n,r){throw new Error(r?`No known conditions for "${n}" specifier in "${e}" package`:`Missing "${n}" specifier in "${e}" package`)}function n(n,i,o,f){let s,u,l=r(n,o),c=function(e){let n=new Set(["default",...e.conditions||[]]);return e.unsafe||n.add(e.require?"require":"import"),e.unsafe||n.add(e.browser?"browser":"node"),n}(f||{}),a=i[l];if(void 0===a){let e,n,r,t;for(t in i)n&&t.length<n.length||("/"===t[t.length-1]&&l.startsWith(t)?(u=l.substring(t.length),n=t):t.length>1&&(r=t.indexOf("*",1),~r&&(e=RegExp("^"+t.substring(0,r)+"(.*)"+t.substring(1+r)).exec(l),e&&e[1]&&(u=e[1],n=t))));a=i[n];}return a||e(n,l),s=t(a,c),s||e(n,l,1),u&&function(e,n){let r,t=0,i=e.length,o=/[*]/g,f=/[/]$/;for(;t<i;t++)e[t]=o.test(r=e[t])?r.replace(o,n):f.test(r)?r+n:r;}(s,u),s}function r(e,n,r){if(e===n||"."===n)return ".";let t=e+"/",i=t.length,o=n.slice(0,i)===t,f=o?n.slice(i):n;return "#"===f[0]?f:o||!r?"./"===f.slice(0,2)?f:"./"+f:f}function t(e,n,r){if(e){if("string"==typeof e)return r&&r.add(e),[e];let i,o;if(Array.isArray(e)){for(o=r||new Set,i=0;i<e.length;i++)t(e[i],n,o);if(!r&&o.size)return [...o]}else for(i in e)if(n.has(i))return t(e[i],n,r)}}function o(e,r,t){let i,o=e.exports;if(o){if("string"==typeof o)o={".":o};else for(i in o){"."!==i[0]&&(o={".":o});break}return n(e.name,o,r||".",t)}}function f(e,r,t){if(e.imports)return n(e.name,e.imports,r,t)}
  14793. // This file was generated. Do not modify manually!
  14794. var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  14795. // This file was generated. Do not modify manually!
  14796. var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
  14797. // This file was generated. Do not modify manually!
  14798. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  14799. // This file was generated. Do not modify manually!
  14800. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  14801. // These are a run-length and offset encoded representation of the
  14802. // Reserved word lists for various dialects of the language
  14803. var reservedWords = {
  14804. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  14805. 5: "class enum extends super const export import",
  14806. 6: "enum",
  14807. strict: "implements interface let package private protected public static yield",
  14808. strictBind: "eval arguments"
  14809. };
  14810. // And the keywords
  14811. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  14812. var keywords$1 = {
  14813. 5: ecma5AndLessKeywords,
  14814. "5module": ecma5AndLessKeywords + " export import",
  14815. 6: ecma5AndLessKeywords + " const class extends export import super"
  14816. };
  14817. var keywordRelationalOperator = /^in(stanceof)?$/;
  14818. // ## Character categories
  14819. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  14820. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  14821. // This has a complexity linear to the value of the code. The
  14822. // assumption is that looking up astral identifier characters is
  14823. // rare.
  14824. function isInAstralSet(code, set) {
  14825. var pos = 0x10000;
  14826. for (var i = 0; i < set.length; i += 2) {
  14827. pos += set[i];
  14828. if (pos > code) { return false }
  14829. pos += set[i + 1];
  14830. if (pos >= code) { return true }
  14831. }
  14832. return false
  14833. }
  14834. // Test whether a given character code starts an identifier.
  14835. function isIdentifierStart(code, astral) {
  14836. if (code < 65) { return code === 36 }
  14837. if (code < 91) { return true }
  14838. if (code < 97) { return code === 95 }
  14839. if (code < 123) { return true }
  14840. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  14841. if (astral === false) { return false }
  14842. return isInAstralSet(code, astralIdentifierStartCodes)
  14843. }
  14844. // Test whether a given character is part of an identifier.
  14845. function isIdentifierChar(code, astral) {
  14846. if (code < 48) { return code === 36 }
  14847. if (code < 58) { return true }
  14848. if (code < 65) { return false }
  14849. if (code < 91) { return true }
  14850. if (code < 97) { return code === 95 }
  14851. if (code < 123) { return true }
  14852. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  14853. if (astral === false) { return false }
  14854. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  14855. }
  14856. // ## Token types
  14857. // The assignment of fine-grained, information-carrying type objects
  14858. // allows the tokenizer to store the information it has about a
  14859. // token in a way that is very cheap for the parser to look up.
  14860. // All token type variables start with an underscore, to make them
  14861. // easy to recognize.
  14862. // The `beforeExpr` property is used to disambiguate between regular
  14863. // expressions and divisions. It is set on all token types that can
  14864. // be followed by an expression (thus, a slash after them would be a
  14865. // regular expression).
  14866. //
  14867. // The `startsExpr` property is used to check if the token ends a
  14868. // `yield` expression. It is set on all token types that either can
  14869. // directly start an expression (like a quotation mark) or can
  14870. // continue an expression (like the body of a string).
  14871. //
  14872. // `isLoop` marks a keyword as starting a loop, which is important
  14873. // to know when parsing a label, in order to allow or disallow
  14874. // continue jumps to that label.
  14875. var TokenType = function TokenType(label, conf) {
  14876. if ( conf === void 0 ) conf = {};
  14877. this.label = label;
  14878. this.keyword = conf.keyword;
  14879. this.beforeExpr = !!conf.beforeExpr;
  14880. this.startsExpr = !!conf.startsExpr;
  14881. this.isLoop = !!conf.isLoop;
  14882. this.isAssign = !!conf.isAssign;
  14883. this.prefix = !!conf.prefix;
  14884. this.postfix = !!conf.postfix;
  14885. this.binop = conf.binop || null;
  14886. this.updateContext = null;
  14887. };
  14888. function binop(name, prec) {
  14889. return new TokenType(name, {beforeExpr: true, binop: prec})
  14890. }
  14891. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  14892. // Map keyword names to token types.
  14893. var keywords$2 = {};
  14894. // Succinct definitions of keyword token types
  14895. function kw(name, options) {
  14896. if ( options === void 0 ) options = {};
  14897. options.keyword = name;
  14898. return keywords$2[name] = new TokenType(name, options)
  14899. }
  14900. var types$1 = {
  14901. num: new TokenType("num", startsExpr),
  14902. regexp: new TokenType("regexp", startsExpr),
  14903. string: new TokenType("string", startsExpr),
  14904. name: new TokenType("name", startsExpr),
  14905. privateId: new TokenType("privateId", startsExpr),
  14906. eof: new TokenType("eof"),
  14907. // Punctuation token types.
  14908. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  14909. bracketR: new TokenType("]"),
  14910. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  14911. braceR: new TokenType("}"),
  14912. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  14913. parenR: new TokenType(")"),
  14914. comma: new TokenType(",", beforeExpr),
  14915. semi: new TokenType(";", beforeExpr),
  14916. colon: new TokenType(":", beforeExpr),
  14917. dot: new TokenType("."),
  14918. question: new TokenType("?", beforeExpr),
  14919. questionDot: new TokenType("?."),
  14920. arrow: new TokenType("=>", beforeExpr),
  14921. template: new TokenType("template"),
  14922. invalidTemplate: new TokenType("invalidTemplate"),
  14923. ellipsis: new TokenType("...", beforeExpr),
  14924. backQuote: new TokenType("`", startsExpr),
  14925. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  14926. // Operators. These carry several kinds of properties to help the
  14927. // parser use them properly (the presence of these properties is
  14928. // what categorizes them as operators).
  14929. //
  14930. // `binop`, when present, specifies that this operator is a binary
  14931. // operator, and will refer to its precedence.
  14932. //
  14933. // `prefix` and `postfix` mark the operator as a prefix or postfix
  14934. // unary operator.
  14935. //
  14936. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  14937. // binary operators with a very low precedence, that should result
  14938. // in AssignmentExpression nodes.
  14939. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  14940. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  14941. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  14942. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  14943. logicalOR: binop("||", 1),
  14944. logicalAND: binop("&&", 2),
  14945. bitwiseOR: binop("|", 3),
  14946. bitwiseXOR: binop("^", 4),
  14947. bitwiseAND: binop("&", 5),
  14948. equality: binop("==/!=/===/!==", 6),
  14949. relational: binop("</>/<=/>=", 7),
  14950. bitShift: binop("<</>>/>>>", 8),
  14951. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  14952. modulo: binop("%", 10),
  14953. star: binop("*", 10),
  14954. slash: binop("/", 10),
  14955. starstar: new TokenType("**", {beforeExpr: true}),
  14956. coalesce: binop("??", 1),
  14957. // Keyword token types.
  14958. _break: kw("break"),
  14959. _case: kw("case", beforeExpr),
  14960. _catch: kw("catch"),
  14961. _continue: kw("continue"),
  14962. _debugger: kw("debugger"),
  14963. _default: kw("default", beforeExpr),
  14964. _do: kw("do", {isLoop: true, beforeExpr: true}),
  14965. _else: kw("else", beforeExpr),
  14966. _finally: kw("finally"),
  14967. _for: kw("for", {isLoop: true}),
  14968. _function: kw("function", startsExpr),
  14969. _if: kw("if"),
  14970. _return: kw("return", beforeExpr),
  14971. _switch: kw("switch"),
  14972. _throw: kw("throw", beforeExpr),
  14973. _try: kw("try"),
  14974. _var: kw("var"),
  14975. _const: kw("const"),
  14976. _while: kw("while", {isLoop: true}),
  14977. _with: kw("with"),
  14978. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  14979. _this: kw("this", startsExpr),
  14980. _super: kw("super", startsExpr),
  14981. _class: kw("class", startsExpr),
  14982. _extends: kw("extends", beforeExpr),
  14983. _export: kw("export"),
  14984. _import: kw("import", startsExpr),
  14985. _null: kw("null", startsExpr),
  14986. _true: kw("true", startsExpr),
  14987. _false: kw("false", startsExpr),
  14988. _in: kw("in", {beforeExpr: true, binop: 7}),
  14989. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  14990. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  14991. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  14992. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  14993. };
  14994. // Matches a whole line break (where CRLF is considered a single
  14995. // line break). Used to count lines.
  14996. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  14997. var lineBreakG = new RegExp(lineBreak.source, "g");
  14998. function isNewLine(code) {
  14999. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  15000. }
  15001. function nextLineBreak(code, from, end) {
  15002. if ( end === void 0 ) end = code.length;
  15003. for (var i = from; i < end; i++) {
  15004. var next = code.charCodeAt(i);
  15005. if (isNewLine(next))
  15006. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  15007. }
  15008. return -1
  15009. }
  15010. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  15011. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  15012. var ref = Object.prototype;
  15013. var hasOwnProperty$1 = ref.hasOwnProperty;
  15014. var toString$1 = ref.toString;
  15015. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  15016. hasOwnProperty$1.call(obj, propName)
  15017. ); });
  15018. var isArray = Array.isArray || (function (obj) { return (
  15019. toString$1.call(obj) === "[object Array]"
  15020. ); });
  15021. function wordsRegexp(words) {
  15022. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  15023. }
  15024. function codePointToString(code) {
  15025. // UTF-16 Decoding
  15026. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  15027. code -= 0x10000;
  15028. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  15029. }
  15030. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  15031. // These are used when `options.locations` is on, for the
  15032. // `startLoc` and `endLoc` properties.
  15033. var Position = function Position(line, col) {
  15034. this.line = line;
  15035. this.column = col;
  15036. };
  15037. Position.prototype.offset = function offset (n) {
  15038. return new Position(this.line, this.column + n)
  15039. };
  15040. var SourceLocation = function SourceLocation(p, start, end) {
  15041. this.start = start;
  15042. this.end = end;
  15043. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  15044. };
  15045. // The `getLineInfo` function is mostly useful when the
  15046. // `locations` option is off (for performance reasons) and you
  15047. // want to find the line/column position for a given character
  15048. // offset. `input` should be the code string that the offset refers
  15049. // into.
  15050. function getLineInfo(input, offset) {
  15051. for (var line = 1, cur = 0;;) {
  15052. var nextBreak = nextLineBreak(input, cur, offset);
  15053. if (nextBreak < 0) { return new Position(line, offset - cur) }
  15054. ++line;
  15055. cur = nextBreak;
  15056. }
  15057. }
  15058. // A second argument must be given to configure the parser process.
  15059. // These options are recognized (only `ecmaVersion` is required):
  15060. var defaultOptions = {
  15061. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  15062. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  15063. // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  15064. // (the latest version the library supports). This influences
  15065. // support for strict mode, the set of reserved words, and support
  15066. // for new syntax features.
  15067. ecmaVersion: null,
  15068. // `sourceType` indicates the mode the code should be parsed in.
  15069. // Can be either `"script"` or `"module"`. This influences global
  15070. // strict mode and parsing of `import` and `export` declarations.
  15071. sourceType: "script",
  15072. // `onInsertedSemicolon` can be a callback that will be called
  15073. // when a semicolon is automatically inserted. It will be passed
  15074. // the position of the comma as an offset, and if `locations` is
  15075. // enabled, it is given the location as a `{line, column}` object
  15076. // as second argument.
  15077. onInsertedSemicolon: null,
  15078. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  15079. // trailing commas.
  15080. onTrailingComma: null,
  15081. // By default, reserved words are only enforced if ecmaVersion >= 5.
  15082. // Set `allowReserved` to a boolean value to explicitly turn this on
  15083. // an off. When this option has the value "never", reserved words
  15084. // and keywords can also not be used as property names.
  15085. allowReserved: null,
  15086. // When enabled, a return at the top level is not considered an
  15087. // error.
  15088. allowReturnOutsideFunction: false,
  15089. // When enabled, import/export statements are not constrained to
  15090. // appearing at the top of the program, and an import.meta expression
  15091. // in a script isn't considered an error.
  15092. allowImportExportEverywhere: false,
  15093. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  15094. // When enabled, await identifiers are allowed to appear at the top-level scope,
  15095. // but they are still not allowed in non-async functions.
  15096. allowAwaitOutsideFunction: null,
  15097. // When enabled, super identifiers are not constrained to
  15098. // appearing in methods and do not raise an error when they appear elsewhere.
  15099. allowSuperOutsideMethod: null,
  15100. // When enabled, hashbang directive in the beginning of file is
  15101. // allowed and treated as a line comment. Enabled by default when
  15102. // `ecmaVersion` >= 2023.
  15103. allowHashBang: false,
  15104. // When `locations` is on, `loc` properties holding objects with
  15105. // `start` and `end` properties in `{line, column}` form (with
  15106. // line being 1-based and column 0-based) will be attached to the
  15107. // nodes.
  15108. locations: false,
  15109. // A function can be passed as `onToken` option, which will
  15110. // cause Acorn to call that function with object in the same
  15111. // format as tokens returned from `tokenizer().getToken()`. Note
  15112. // that you are not allowed to call the parser from the
  15113. // callback—that will corrupt its internal state.
  15114. onToken: null,
  15115. // A function can be passed as `onComment` option, which will
  15116. // cause Acorn to call that function with `(block, text, start,
  15117. // end)` parameters whenever a comment is skipped. `block` is a
  15118. // boolean indicating whether this is a block (`/* */`) comment,
  15119. // `text` is the content of the comment, and `start` and `end` are
  15120. // character offsets that denote the start and end of the comment.
  15121. // When the `locations` option is on, two more parameters are
  15122. // passed, the full `{line, column}` locations of the start and
  15123. // end of the comments. Note that you are not allowed to call the
  15124. // parser from the callback—that will corrupt its internal state.
  15125. onComment: null,
  15126. // Nodes have their start and end characters offsets recorded in
  15127. // `start` and `end` properties (directly on the node, rather than
  15128. // the `loc` object, which holds line/column data. To also add a
  15129. // [semi-standardized][range] `range` property holding a `[start,
  15130. // end]` array with the same numbers, set the `ranges` option to
  15131. // `true`.
  15132. //
  15133. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  15134. ranges: false,
  15135. // It is possible to parse multiple files into a single AST by
  15136. // passing the tree produced by parsing the first file as
  15137. // `program` option in subsequent parses. This will add the
  15138. // toplevel forms of the parsed file to the `Program` (top) node
  15139. // of an existing parse tree.
  15140. program: null,
  15141. // When `locations` is on, you can pass this to record the source
  15142. // file in every node's `loc` object.
  15143. sourceFile: null,
  15144. // This value, if given, is stored in every node, whether
  15145. // `locations` is on or off.
  15146. directSourceFile: null,
  15147. // When enabled, parenthesized expressions are represented by
  15148. // (non-standard) ParenthesizedExpression nodes
  15149. preserveParens: false
  15150. };
  15151. // Interpret and default an options object
  15152. var warnedAboutEcmaVersion = false;
  15153. function getOptions(opts) {
  15154. var options = {};
  15155. for (var opt in defaultOptions)
  15156. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  15157. if (options.ecmaVersion === "latest") {
  15158. options.ecmaVersion = 1e8;
  15159. } else if (options.ecmaVersion == null) {
  15160. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  15161. warnedAboutEcmaVersion = true;
  15162. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  15163. }
  15164. options.ecmaVersion = 11;
  15165. } else if (options.ecmaVersion >= 2015) {
  15166. options.ecmaVersion -= 2009;
  15167. }
  15168. if (options.allowReserved == null)
  15169. { options.allowReserved = options.ecmaVersion < 5; }
  15170. if (!opts || opts.allowHashBang == null)
  15171. { options.allowHashBang = options.ecmaVersion >= 14; }
  15172. if (isArray(options.onToken)) {
  15173. var tokens = options.onToken;
  15174. options.onToken = function (token) { return tokens.push(token); };
  15175. }
  15176. if (isArray(options.onComment))
  15177. { options.onComment = pushComment(options, options.onComment); }
  15178. return options
  15179. }
  15180. function pushComment(options, array) {
  15181. return function(block, text, start, end, startLoc, endLoc) {
  15182. var comment = {
  15183. type: block ? "Block" : "Line",
  15184. value: text,
  15185. start: start,
  15186. end: end
  15187. };
  15188. if (options.locations)
  15189. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  15190. if (options.ranges)
  15191. { comment.range = [start, end]; }
  15192. array.push(comment);
  15193. }
  15194. }
  15195. // Each scope gets a bitset that may contain these flags
  15196. var
  15197. SCOPE_TOP = 1,
  15198. SCOPE_FUNCTION = 2,
  15199. SCOPE_ASYNC = 4,
  15200. SCOPE_GENERATOR = 8,
  15201. SCOPE_ARROW = 16,
  15202. SCOPE_SIMPLE_CATCH = 32,
  15203. SCOPE_SUPER = 64,
  15204. SCOPE_DIRECT_SUPER = 128,
  15205. SCOPE_CLASS_STATIC_BLOCK = 256,
  15206. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  15207. function functionFlags(async, generator) {
  15208. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  15209. }
  15210. // Used in checkLVal* and declareName to determine the type of a binding
  15211. var
  15212. BIND_NONE = 0, // Not a binding
  15213. BIND_VAR = 1, // Var-style binding
  15214. BIND_LEXICAL = 2, // Let- or const-style binding
  15215. BIND_FUNCTION = 3, // Function declaration
  15216. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  15217. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  15218. var Parser$1 = function Parser(options, input, startPos) {
  15219. this.options = options = getOptions(options);
  15220. this.sourceFile = options.sourceFile;
  15221. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  15222. var reserved = "";
  15223. if (options.allowReserved !== true) {
  15224. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  15225. if (options.sourceType === "module") { reserved += " await"; }
  15226. }
  15227. this.reservedWords = wordsRegexp(reserved);
  15228. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  15229. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  15230. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  15231. this.input = String(input);
  15232. // Used to signal to callers of `readWord1` whether the word
  15233. // contained any escape sequences. This is needed because words with
  15234. // escape sequences must not be interpreted as keywords.
  15235. this.containsEsc = false;
  15236. // Set up token state
  15237. // The current position of the tokenizer in the input.
  15238. if (startPos) {
  15239. this.pos = startPos;
  15240. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  15241. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  15242. } else {
  15243. this.pos = this.lineStart = 0;
  15244. this.curLine = 1;
  15245. }
  15246. // Properties of the current token:
  15247. // Its type
  15248. this.type = types$1.eof;
  15249. // For tokens that include more information than their type, the value
  15250. this.value = null;
  15251. // Its start and end offset
  15252. this.start = this.end = this.pos;
  15253. // And, if locations are used, the {line, column} object
  15254. // corresponding to those offsets
  15255. this.startLoc = this.endLoc = this.curPosition();
  15256. // Position information for the previous token
  15257. this.lastTokEndLoc = this.lastTokStartLoc = null;
  15258. this.lastTokStart = this.lastTokEnd = this.pos;
  15259. // The context stack is used to superficially track syntactic
  15260. // context to predict whether a regular expression is allowed in a
  15261. // given position.
  15262. this.context = this.initialContext();
  15263. this.exprAllowed = true;
  15264. // Figure out if it's a module code.
  15265. this.inModule = options.sourceType === "module";
  15266. this.strict = this.inModule || this.strictDirective(this.pos);
  15267. // Used to signify the start of a potential arrow function
  15268. this.potentialArrowAt = -1;
  15269. this.potentialArrowInForAwait = false;
  15270. // Positions to delayed-check that yield/await does not exist in default parameters.
  15271. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  15272. // Labels in scope.
  15273. this.labels = [];
  15274. // Thus-far undefined exports.
  15275. this.undefinedExports = Object.create(null);
  15276. // If enabled, skip leading hashbang line.
  15277. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  15278. { this.skipLineComment(2); }
  15279. // Scope tracking for duplicate variable names (see scope.js)
  15280. this.scopeStack = [];
  15281. this.enterScope(SCOPE_TOP);
  15282. // For RegExp validation
  15283. this.regexpState = null;
  15284. // The stack of private names.
  15285. // Each element has two properties: 'declared' and 'used'.
  15286. // When it exited from the outermost class definition, all used private names must be declared.
  15287. this.privateNameStack = [];
  15288. };
  15289. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
  15290. Parser$1.prototype.parse = function parse () {
  15291. var node = this.options.program || this.startNode();
  15292. this.nextToken();
  15293. return this.parseTopLevel(node)
  15294. };
  15295. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  15296. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  15297. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  15298. prototypeAccessors.canAwait.get = function () {
  15299. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  15300. var scope = this.scopeStack[i];
  15301. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  15302. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  15303. }
  15304. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  15305. };
  15306. prototypeAccessors.allowSuper.get = function () {
  15307. var ref = this.currentThisScope();
  15308. var flags = ref.flags;
  15309. var inClassFieldInit = ref.inClassFieldInit;
  15310. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  15311. };
  15312. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  15313. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  15314. prototypeAccessors.allowNewDotTarget.get = function () {
  15315. var ref = this.currentThisScope();
  15316. var flags = ref.flags;
  15317. var inClassFieldInit = ref.inClassFieldInit;
  15318. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  15319. };
  15320. prototypeAccessors.inClassStaticBlock.get = function () {
  15321. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  15322. };
  15323. Parser$1.extend = function extend () {
  15324. var plugins = [], len = arguments.length;
  15325. while ( len-- ) plugins[ len ] = arguments[ len ];
  15326. var cls = this;
  15327. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  15328. return cls
  15329. };
  15330. Parser$1.parse = function parse (input, options) {
  15331. return new this(options, input).parse()
  15332. };
  15333. Parser$1.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  15334. var parser = new this(options, input, pos);
  15335. parser.nextToken();
  15336. return parser.parseExpression()
  15337. };
  15338. Parser$1.tokenizer = function tokenizer (input, options) {
  15339. return new this(options, input)
  15340. };
  15341. Object.defineProperties( Parser$1.prototype, prototypeAccessors );
  15342. var pp$9 = Parser$1.prototype;
  15343. // ## Parser utilities
  15344. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  15345. pp$9.strictDirective = function(start) {
  15346. if (this.options.ecmaVersion < 5) { return false }
  15347. for (;;) {
  15348. // Try to find string literal.
  15349. skipWhiteSpace.lastIndex = start;
  15350. start += skipWhiteSpace.exec(this.input)[0].length;
  15351. var match = literal.exec(this.input.slice(start));
  15352. if (!match) { return false }
  15353. if ((match[1] || match[2]) === "use strict") {
  15354. skipWhiteSpace.lastIndex = start + match[0].length;
  15355. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  15356. var next = this.input.charAt(end);
  15357. return next === ";" || next === "}" ||
  15358. (lineBreak.test(spaceAfter[0]) &&
  15359. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  15360. }
  15361. start += match[0].length;
  15362. // Skip semicolon, if any.
  15363. skipWhiteSpace.lastIndex = start;
  15364. start += skipWhiteSpace.exec(this.input)[0].length;
  15365. if (this.input[start] === ";")
  15366. { start++; }
  15367. }
  15368. };
  15369. // Predicate that tests whether the next token is of the given
  15370. // type, and if yes, consumes it as a side effect.
  15371. pp$9.eat = function(type) {
  15372. if (this.type === type) {
  15373. this.next();
  15374. return true
  15375. } else {
  15376. return false
  15377. }
  15378. };
  15379. // Tests whether parsed token is a contextual keyword.
  15380. pp$9.isContextual = function(name) {
  15381. return this.type === types$1.name && this.value === name && !this.containsEsc
  15382. };
  15383. // Consumes contextual keyword if possible.
  15384. pp$9.eatContextual = function(name) {
  15385. if (!this.isContextual(name)) { return false }
  15386. this.next();
  15387. return true
  15388. };
  15389. // Asserts that following token is given contextual keyword.
  15390. pp$9.expectContextual = function(name) {
  15391. if (!this.eatContextual(name)) { this.unexpected(); }
  15392. };
  15393. // Test whether a semicolon can be inserted at the current position.
  15394. pp$9.canInsertSemicolon = function() {
  15395. return this.type === types$1.eof ||
  15396. this.type === types$1.braceR ||
  15397. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  15398. };
  15399. pp$9.insertSemicolon = function() {
  15400. if (this.canInsertSemicolon()) {
  15401. if (this.options.onInsertedSemicolon)
  15402. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  15403. return true
  15404. }
  15405. };
  15406. // Consume a semicolon, or, failing that, see if we are allowed to
  15407. // pretend that there is a semicolon at this position.
  15408. pp$9.semicolon = function() {
  15409. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  15410. };
  15411. pp$9.afterTrailingComma = function(tokType, notNext) {
  15412. if (this.type === tokType) {
  15413. if (this.options.onTrailingComma)
  15414. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  15415. if (!notNext)
  15416. { this.next(); }
  15417. return true
  15418. }
  15419. };
  15420. // Expect a token of a given type. If found, consume it, otherwise,
  15421. // raise an unexpected token error.
  15422. pp$9.expect = function(type) {
  15423. this.eat(type) || this.unexpected();
  15424. };
  15425. // Raise an unexpected token error.
  15426. pp$9.unexpected = function(pos) {
  15427. this.raise(pos != null ? pos : this.start, "Unexpected token");
  15428. };
  15429. var DestructuringErrors = function DestructuringErrors() {
  15430. this.shorthandAssign =
  15431. this.trailingComma =
  15432. this.parenthesizedAssign =
  15433. this.parenthesizedBind =
  15434. this.doubleProto =
  15435. -1;
  15436. };
  15437. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  15438. if (!refDestructuringErrors) { return }
  15439. if (refDestructuringErrors.trailingComma > -1)
  15440. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  15441. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  15442. if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
  15443. };
  15444. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  15445. if (!refDestructuringErrors) { return false }
  15446. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  15447. var doubleProto = refDestructuringErrors.doubleProto;
  15448. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  15449. if (shorthandAssign >= 0)
  15450. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  15451. if (doubleProto >= 0)
  15452. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  15453. };
  15454. pp$9.checkYieldAwaitInDefaultParams = function() {
  15455. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  15456. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  15457. if (this.awaitPos)
  15458. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  15459. };
  15460. pp$9.isSimpleAssignTarget = function(expr) {
  15461. if (expr.type === "ParenthesizedExpression")
  15462. { return this.isSimpleAssignTarget(expr.expression) }
  15463. return expr.type === "Identifier" || expr.type === "MemberExpression"
  15464. };
  15465. var pp$8 = Parser$1.prototype;
  15466. // ### Statement parsing
  15467. // Parse a program. Initializes the parser, reads any number of
  15468. // statements, and wraps them in a Program node. Optionally takes a
  15469. // `program` argument. If present, the statements will be appended
  15470. // to its body instead of creating a new node.
  15471. pp$8.parseTopLevel = function(node) {
  15472. var exports = Object.create(null);
  15473. if (!node.body) { node.body = []; }
  15474. while (this.type !== types$1.eof) {
  15475. var stmt = this.parseStatement(null, true, exports);
  15476. node.body.push(stmt);
  15477. }
  15478. if (this.inModule)
  15479. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  15480. {
  15481. var name = list[i];
  15482. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  15483. } }
  15484. this.adaptDirectivePrologue(node.body);
  15485. this.next();
  15486. node.sourceType = this.options.sourceType;
  15487. return this.finishNode(node, "Program")
  15488. };
  15489. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  15490. pp$8.isLet = function(context) {
  15491. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  15492. skipWhiteSpace.lastIndex = this.pos;
  15493. var skip = skipWhiteSpace.exec(this.input);
  15494. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  15495. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  15496. // Statement) is allowed here. If context is not empty then only a Statement
  15497. // is allowed. However, `let [` is an explicit negative lookahead for
  15498. // ExpressionStatement, so special-case it first.
  15499. if (nextCh === 91 || nextCh === 92) { return true } // '[', '/'
  15500. if (context) { return false }
  15501. if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
  15502. if (isIdentifierStart(nextCh, true)) {
  15503. var pos = next + 1;
  15504. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  15505. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  15506. var ident = this.input.slice(next, pos);
  15507. if (!keywordRelationalOperator.test(ident)) { return true }
  15508. }
  15509. return false
  15510. };
  15511. // check 'async [no LineTerminator here] function'
  15512. // - 'async /*foo*/ function' is OK.
  15513. // - 'async /*\n*/ function' is invalid.
  15514. pp$8.isAsyncFunction = function() {
  15515. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  15516. { return false }
  15517. skipWhiteSpace.lastIndex = this.pos;
  15518. var skip = skipWhiteSpace.exec(this.input);
  15519. var next = this.pos + skip[0].length, after;
  15520. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  15521. this.input.slice(next, next + 8) === "function" &&
  15522. (next + 8 === this.input.length ||
  15523. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  15524. };
  15525. // Parse a single statement.
  15526. //
  15527. // If expecting a statement and finding a slash operator, parse a
  15528. // regular expression literal. This is to handle cases like
  15529. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  15530. // does not help.
  15531. pp$8.parseStatement = function(context, topLevel, exports) {
  15532. var starttype = this.type, node = this.startNode(), kind;
  15533. if (this.isLet(context)) {
  15534. starttype = types$1._var;
  15535. kind = "let";
  15536. }
  15537. // Most types of statements are recognized by the keyword they
  15538. // start with. Many are trivial to parse, some require a bit of
  15539. // complexity.
  15540. switch (starttype) {
  15541. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  15542. case types$1._debugger: return this.parseDebuggerStatement(node)
  15543. case types$1._do: return this.parseDoStatement(node)
  15544. case types$1._for: return this.parseForStatement(node)
  15545. case types$1._function:
  15546. // Function as sole body of either an if statement or a labeled statement
  15547. // works, but not when it is part of a labeled statement that is the sole
  15548. // body of an if statement.
  15549. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  15550. return this.parseFunctionStatement(node, false, !context)
  15551. case types$1._class:
  15552. if (context) { this.unexpected(); }
  15553. return this.parseClass(node, true)
  15554. case types$1._if: return this.parseIfStatement(node)
  15555. case types$1._return: return this.parseReturnStatement(node)
  15556. case types$1._switch: return this.parseSwitchStatement(node)
  15557. case types$1._throw: return this.parseThrowStatement(node)
  15558. case types$1._try: return this.parseTryStatement(node)
  15559. case types$1._const: case types$1._var:
  15560. kind = kind || this.value;
  15561. if (context && kind !== "var") { this.unexpected(); }
  15562. return this.parseVarStatement(node, kind)
  15563. case types$1._while: return this.parseWhileStatement(node)
  15564. case types$1._with: return this.parseWithStatement(node)
  15565. case types$1.braceL: return this.parseBlock(true, node)
  15566. case types$1.semi: return this.parseEmptyStatement(node)
  15567. case types$1._export:
  15568. case types$1._import:
  15569. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  15570. skipWhiteSpace.lastIndex = this.pos;
  15571. var skip = skipWhiteSpace.exec(this.input);
  15572. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  15573. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  15574. { return this.parseExpressionStatement(node, this.parseExpression()) }
  15575. }
  15576. if (!this.options.allowImportExportEverywhere) {
  15577. if (!topLevel)
  15578. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  15579. if (!this.inModule)
  15580. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  15581. }
  15582. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  15583. // If the statement does not start with a statement keyword or a
  15584. // brace, it's an ExpressionStatement or LabeledStatement. We
  15585. // simply start parsing an expression, and afterwards, if the
  15586. // next token is a colon and the expression was a simple
  15587. // Identifier node, we switch to interpreting it as a label.
  15588. default:
  15589. if (this.isAsyncFunction()) {
  15590. if (context) { this.unexpected(); }
  15591. this.next();
  15592. return this.parseFunctionStatement(node, true, !context)
  15593. }
  15594. var maybeName = this.value, expr = this.parseExpression();
  15595. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  15596. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  15597. else { return this.parseExpressionStatement(node, expr) }
  15598. }
  15599. };
  15600. pp$8.parseBreakContinueStatement = function(node, keyword) {
  15601. var isBreak = keyword === "break";
  15602. this.next();
  15603. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  15604. else if (this.type !== types$1.name) { this.unexpected(); }
  15605. else {
  15606. node.label = this.parseIdent();
  15607. this.semicolon();
  15608. }
  15609. // Verify that there is an actual destination to break or
  15610. // continue to.
  15611. var i = 0;
  15612. for (; i < this.labels.length; ++i) {
  15613. var lab = this.labels[i];
  15614. if (node.label == null || lab.name === node.label.name) {
  15615. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  15616. if (node.label && isBreak) { break }
  15617. }
  15618. }
  15619. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  15620. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  15621. };
  15622. pp$8.parseDebuggerStatement = function(node) {
  15623. this.next();
  15624. this.semicolon();
  15625. return this.finishNode(node, "DebuggerStatement")
  15626. };
  15627. pp$8.parseDoStatement = function(node) {
  15628. this.next();
  15629. this.labels.push(loopLabel);
  15630. node.body = this.parseStatement("do");
  15631. this.labels.pop();
  15632. this.expect(types$1._while);
  15633. node.test = this.parseParenExpression();
  15634. if (this.options.ecmaVersion >= 6)
  15635. { this.eat(types$1.semi); }
  15636. else
  15637. { this.semicolon(); }
  15638. return this.finishNode(node, "DoWhileStatement")
  15639. };
  15640. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  15641. // loop is non-trivial. Basically, we have to parse the init `var`
  15642. // statement or expression, disallowing the `in` operator (see
  15643. // the second parameter to `parseExpression`), and then check
  15644. // whether the next token is `in` or `of`. When there is no init
  15645. // part (semicolon immediately after the opening parenthesis), it
  15646. // is a regular `for` loop.
  15647. pp$8.parseForStatement = function(node) {
  15648. this.next();
  15649. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  15650. this.labels.push(loopLabel);
  15651. this.enterScope(0);
  15652. this.expect(types$1.parenL);
  15653. if (this.type === types$1.semi) {
  15654. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15655. return this.parseFor(node, null)
  15656. }
  15657. var isLet = this.isLet();
  15658. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  15659. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  15660. this.next();
  15661. this.parseVar(init$1, true, kind);
  15662. this.finishNode(init$1, "VariableDeclaration");
  15663. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  15664. if (this.options.ecmaVersion >= 9) {
  15665. if (this.type === types$1._in) {
  15666. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15667. } else { node.await = awaitAt > -1; }
  15668. }
  15669. return this.parseForIn(node, init$1)
  15670. }
  15671. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15672. return this.parseFor(node, init$1)
  15673. }
  15674. var startsWithLet = this.isContextual("let"), isForOf = false;
  15675. var refDestructuringErrors = new DestructuringErrors;
  15676. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  15677. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  15678. if (this.options.ecmaVersion >= 9) {
  15679. if (this.type === types$1._in) {
  15680. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15681. } else { node.await = awaitAt > -1; }
  15682. }
  15683. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  15684. this.toAssignable(init, false, refDestructuringErrors);
  15685. this.checkLValPattern(init);
  15686. return this.parseForIn(node, init)
  15687. } else {
  15688. this.checkExpressionErrors(refDestructuringErrors, true);
  15689. }
  15690. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15691. return this.parseFor(node, init)
  15692. };
  15693. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  15694. this.next();
  15695. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  15696. };
  15697. pp$8.parseIfStatement = function(node) {
  15698. this.next();
  15699. node.test = this.parseParenExpression();
  15700. // allow function declarations in branches, but only in non-strict mode
  15701. node.consequent = this.parseStatement("if");
  15702. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  15703. return this.finishNode(node, "IfStatement")
  15704. };
  15705. pp$8.parseReturnStatement = function(node) {
  15706. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  15707. { this.raise(this.start, "'return' outside of function"); }
  15708. this.next();
  15709. // In `return` (and `break`/`continue`), the keywords with
  15710. // optional arguments, we eagerly look for a semicolon or the
  15711. // possibility to insert one.
  15712. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  15713. else { node.argument = this.parseExpression(); this.semicolon(); }
  15714. return this.finishNode(node, "ReturnStatement")
  15715. };
  15716. pp$8.parseSwitchStatement = function(node) {
  15717. this.next();
  15718. node.discriminant = this.parseParenExpression();
  15719. node.cases = [];
  15720. this.expect(types$1.braceL);
  15721. this.labels.push(switchLabel);
  15722. this.enterScope(0);
  15723. // Statements under must be grouped (by label) in SwitchCase
  15724. // nodes. `cur` is used to keep the node that we are currently
  15725. // adding statements to.
  15726. var cur;
  15727. for (var sawDefault = false; this.type !== types$1.braceR;) {
  15728. if (this.type === types$1._case || this.type === types$1._default) {
  15729. var isCase = this.type === types$1._case;
  15730. if (cur) { this.finishNode(cur, "SwitchCase"); }
  15731. node.cases.push(cur = this.startNode());
  15732. cur.consequent = [];
  15733. this.next();
  15734. if (isCase) {
  15735. cur.test = this.parseExpression();
  15736. } else {
  15737. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  15738. sawDefault = true;
  15739. cur.test = null;
  15740. }
  15741. this.expect(types$1.colon);
  15742. } else {
  15743. if (!cur) { this.unexpected(); }
  15744. cur.consequent.push(this.parseStatement(null));
  15745. }
  15746. }
  15747. this.exitScope();
  15748. if (cur) { this.finishNode(cur, "SwitchCase"); }
  15749. this.next(); // Closing brace
  15750. this.labels.pop();
  15751. return this.finishNode(node, "SwitchStatement")
  15752. };
  15753. pp$8.parseThrowStatement = function(node) {
  15754. this.next();
  15755. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  15756. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  15757. node.argument = this.parseExpression();
  15758. this.semicolon();
  15759. return this.finishNode(node, "ThrowStatement")
  15760. };
  15761. // Reused empty array added for node fields that are always empty.
  15762. var empty$1 = [];
  15763. pp$8.parseTryStatement = function(node) {
  15764. this.next();
  15765. node.block = this.parseBlock();
  15766. node.handler = null;
  15767. if (this.type === types$1._catch) {
  15768. var clause = this.startNode();
  15769. this.next();
  15770. if (this.eat(types$1.parenL)) {
  15771. clause.param = this.parseBindingAtom();
  15772. var simple = clause.param.type === "Identifier";
  15773. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  15774. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  15775. this.expect(types$1.parenR);
  15776. } else {
  15777. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  15778. clause.param = null;
  15779. this.enterScope(0);
  15780. }
  15781. clause.body = this.parseBlock(false);
  15782. this.exitScope();
  15783. node.handler = this.finishNode(clause, "CatchClause");
  15784. }
  15785. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  15786. if (!node.handler && !node.finalizer)
  15787. { this.raise(node.start, "Missing catch or finally clause"); }
  15788. return this.finishNode(node, "TryStatement")
  15789. };
  15790. pp$8.parseVarStatement = function(node, kind) {
  15791. this.next();
  15792. this.parseVar(node, false, kind);
  15793. this.semicolon();
  15794. return this.finishNode(node, "VariableDeclaration")
  15795. };
  15796. pp$8.parseWhileStatement = function(node) {
  15797. this.next();
  15798. node.test = this.parseParenExpression();
  15799. this.labels.push(loopLabel);
  15800. node.body = this.parseStatement("while");
  15801. this.labels.pop();
  15802. return this.finishNode(node, "WhileStatement")
  15803. };
  15804. pp$8.parseWithStatement = function(node) {
  15805. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  15806. this.next();
  15807. node.object = this.parseParenExpression();
  15808. node.body = this.parseStatement("with");
  15809. return this.finishNode(node, "WithStatement")
  15810. };
  15811. pp$8.parseEmptyStatement = function(node) {
  15812. this.next();
  15813. return this.finishNode(node, "EmptyStatement")
  15814. };
  15815. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  15816. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  15817. {
  15818. var label = list[i$1];
  15819. if (label.name === maybeName)
  15820. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  15821. } }
  15822. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  15823. for (var i = this.labels.length - 1; i >= 0; i--) {
  15824. var label$1 = this.labels[i];
  15825. if (label$1.statementStart === node.start) {
  15826. // Update information about previous labels on this node
  15827. label$1.statementStart = this.start;
  15828. label$1.kind = kind;
  15829. } else { break }
  15830. }
  15831. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  15832. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  15833. this.labels.pop();
  15834. node.label = expr;
  15835. return this.finishNode(node, "LabeledStatement")
  15836. };
  15837. pp$8.parseExpressionStatement = function(node, expr) {
  15838. node.expression = expr;
  15839. this.semicolon();
  15840. return this.finishNode(node, "ExpressionStatement")
  15841. };
  15842. // Parse a semicolon-enclosed block of statements, handling `"use
  15843. // strict"` declarations when `allowStrict` is true (used for
  15844. // function bodies).
  15845. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  15846. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  15847. if ( node === void 0 ) node = this.startNode();
  15848. node.body = [];
  15849. this.expect(types$1.braceL);
  15850. if (createNewLexicalScope) { this.enterScope(0); }
  15851. while (this.type !== types$1.braceR) {
  15852. var stmt = this.parseStatement(null);
  15853. node.body.push(stmt);
  15854. }
  15855. if (exitStrict) { this.strict = false; }
  15856. this.next();
  15857. if (createNewLexicalScope) { this.exitScope(); }
  15858. return this.finishNode(node, "BlockStatement")
  15859. };
  15860. // Parse a regular `for` loop. The disambiguation code in
  15861. // `parseStatement` will already have parsed the init statement or
  15862. // expression.
  15863. pp$8.parseFor = function(node, init) {
  15864. node.init = init;
  15865. this.expect(types$1.semi);
  15866. node.test = this.type === types$1.semi ? null : this.parseExpression();
  15867. this.expect(types$1.semi);
  15868. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  15869. this.expect(types$1.parenR);
  15870. node.body = this.parseStatement("for");
  15871. this.exitScope();
  15872. this.labels.pop();
  15873. return this.finishNode(node, "ForStatement")
  15874. };
  15875. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  15876. // same from parser's perspective.
  15877. pp$8.parseForIn = function(node, init) {
  15878. var isForIn = this.type === types$1._in;
  15879. this.next();
  15880. if (
  15881. init.type === "VariableDeclaration" &&
  15882. init.declarations[0].init != null &&
  15883. (
  15884. !isForIn ||
  15885. this.options.ecmaVersion < 8 ||
  15886. this.strict ||
  15887. init.kind !== "var" ||
  15888. init.declarations[0].id.type !== "Identifier"
  15889. )
  15890. ) {
  15891. this.raise(
  15892. init.start,
  15893. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  15894. );
  15895. }
  15896. node.left = init;
  15897. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  15898. this.expect(types$1.parenR);
  15899. node.body = this.parseStatement("for");
  15900. this.exitScope();
  15901. this.labels.pop();
  15902. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  15903. };
  15904. // Parse a list of variable declarations.
  15905. pp$8.parseVar = function(node, isFor, kind) {
  15906. node.declarations = [];
  15907. node.kind = kind;
  15908. for (;;) {
  15909. var decl = this.startNode();
  15910. this.parseVarId(decl, kind);
  15911. if (this.eat(types$1.eq)) {
  15912. decl.init = this.parseMaybeAssign(isFor);
  15913. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  15914. this.unexpected();
  15915. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  15916. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  15917. } else {
  15918. decl.init = null;
  15919. }
  15920. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  15921. if (!this.eat(types$1.comma)) { break }
  15922. }
  15923. return node
  15924. };
  15925. pp$8.parseVarId = function(decl, kind) {
  15926. decl.id = this.parseBindingAtom();
  15927. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  15928. };
  15929. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  15930. // Parse a function declaration or literal (depending on the
  15931. // `statement & FUNC_STATEMENT`).
  15932. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  15933. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  15934. this.initFunction(node);
  15935. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  15936. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  15937. { this.unexpected(); }
  15938. node.generator = this.eat(types$1.star);
  15939. }
  15940. if (this.options.ecmaVersion >= 8)
  15941. { node.async = !!isAsync; }
  15942. if (statement & FUNC_STATEMENT) {
  15943. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
  15944. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  15945. // If it is a regular function declaration in sloppy mode, then it is
  15946. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  15947. // mode depends on properties of the current scope (see
  15948. // treatFunctionsAsVar).
  15949. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  15950. }
  15951. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  15952. this.yieldPos = 0;
  15953. this.awaitPos = 0;
  15954. this.awaitIdentPos = 0;
  15955. this.enterScope(functionFlags(node.async, node.generator));
  15956. if (!(statement & FUNC_STATEMENT))
  15957. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  15958. this.parseFunctionParams(node);
  15959. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  15960. this.yieldPos = oldYieldPos;
  15961. this.awaitPos = oldAwaitPos;
  15962. this.awaitIdentPos = oldAwaitIdentPos;
  15963. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  15964. };
  15965. pp$8.parseFunctionParams = function(node) {
  15966. this.expect(types$1.parenL);
  15967. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  15968. this.checkYieldAwaitInDefaultParams();
  15969. };
  15970. // Parse a class declaration or literal (depending on the
  15971. // `isStatement` parameter).
  15972. pp$8.parseClass = function(node, isStatement) {
  15973. this.next();
  15974. // ecma-262 14.6 Class Definitions
  15975. // A class definition is always strict mode code.
  15976. var oldStrict = this.strict;
  15977. this.strict = true;
  15978. this.parseClassId(node, isStatement);
  15979. this.parseClassSuper(node);
  15980. var privateNameMap = this.enterClassBody();
  15981. var classBody = this.startNode();
  15982. var hadConstructor = false;
  15983. classBody.body = [];
  15984. this.expect(types$1.braceL);
  15985. while (this.type !== types$1.braceR) {
  15986. var element = this.parseClassElement(node.superClass !== null);
  15987. if (element) {
  15988. classBody.body.push(element);
  15989. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  15990. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  15991. hadConstructor = true;
  15992. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  15993. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  15994. }
  15995. }
  15996. }
  15997. this.strict = oldStrict;
  15998. this.next();
  15999. node.body = this.finishNode(classBody, "ClassBody");
  16000. this.exitClassBody();
  16001. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  16002. };
  16003. pp$8.parseClassElement = function(constructorAllowsSuper) {
  16004. if (this.eat(types$1.semi)) { return null }
  16005. var ecmaVersion = this.options.ecmaVersion;
  16006. var node = this.startNode();
  16007. var keyName = "";
  16008. var isGenerator = false;
  16009. var isAsync = false;
  16010. var kind = "method";
  16011. var isStatic = false;
  16012. if (this.eatContextual("static")) {
  16013. // Parse static init block
  16014. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  16015. this.parseClassStaticBlock(node);
  16016. return node
  16017. }
  16018. if (this.isClassElementNameStart() || this.type === types$1.star) {
  16019. isStatic = true;
  16020. } else {
  16021. keyName = "static";
  16022. }
  16023. }
  16024. node.static = isStatic;
  16025. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  16026. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  16027. isAsync = true;
  16028. } else {
  16029. keyName = "async";
  16030. }
  16031. }
  16032. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  16033. isGenerator = true;
  16034. }
  16035. if (!keyName && !isAsync && !isGenerator) {
  16036. var lastValue = this.value;
  16037. if (this.eatContextual("get") || this.eatContextual("set")) {
  16038. if (this.isClassElementNameStart()) {
  16039. kind = lastValue;
  16040. } else {
  16041. keyName = lastValue;
  16042. }
  16043. }
  16044. }
  16045. // Parse element name
  16046. if (keyName) {
  16047. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  16048. // The last token is any of those. Make it the element name.
  16049. node.computed = false;
  16050. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  16051. node.key.name = keyName;
  16052. this.finishNode(node.key, "Identifier");
  16053. } else {
  16054. this.parseClassElementName(node);
  16055. }
  16056. // Parse element value
  16057. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  16058. var isConstructor = !node.static && checkKeyName(node, "constructor");
  16059. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  16060. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  16061. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  16062. node.kind = isConstructor ? "constructor" : kind;
  16063. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  16064. } else {
  16065. this.parseClassField(node);
  16066. }
  16067. return node
  16068. };
  16069. pp$8.isClassElementNameStart = function() {
  16070. return (
  16071. this.type === types$1.name ||
  16072. this.type === types$1.privateId ||
  16073. this.type === types$1.num ||
  16074. this.type === types$1.string ||
  16075. this.type === types$1.bracketL ||
  16076. this.type.keyword
  16077. )
  16078. };
  16079. pp$8.parseClassElementName = function(element) {
  16080. if (this.type === types$1.privateId) {
  16081. if (this.value === "constructor") {
  16082. this.raise(this.start, "Classes can't have an element named '#constructor'");
  16083. }
  16084. element.computed = false;
  16085. element.key = this.parsePrivateIdent();
  16086. } else {
  16087. this.parsePropertyName(element);
  16088. }
  16089. };
  16090. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  16091. // Check key and flags
  16092. var key = method.key;
  16093. if (method.kind === "constructor") {
  16094. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  16095. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  16096. } else if (method.static && checkKeyName(method, "prototype")) {
  16097. this.raise(key.start, "Classes may not have a static property named prototype");
  16098. }
  16099. // Parse value
  16100. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  16101. // Check value
  16102. if (method.kind === "get" && value.params.length !== 0)
  16103. { this.raiseRecoverable(value.start, "getter should have no params"); }
  16104. if (method.kind === "set" && value.params.length !== 1)
  16105. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  16106. if (method.kind === "set" && value.params[0].type === "RestElement")
  16107. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  16108. return this.finishNode(method, "MethodDefinition")
  16109. };
  16110. pp$8.parseClassField = function(field) {
  16111. if (checkKeyName(field, "constructor")) {
  16112. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  16113. } else if (field.static && checkKeyName(field, "prototype")) {
  16114. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  16115. }
  16116. if (this.eat(types$1.eq)) {
  16117. // To raise SyntaxError if 'arguments' exists in the initializer.
  16118. var scope = this.currentThisScope();
  16119. var inClassFieldInit = scope.inClassFieldInit;
  16120. scope.inClassFieldInit = true;
  16121. field.value = this.parseMaybeAssign();
  16122. scope.inClassFieldInit = inClassFieldInit;
  16123. } else {
  16124. field.value = null;
  16125. }
  16126. this.semicolon();
  16127. return this.finishNode(field, "PropertyDefinition")
  16128. };
  16129. pp$8.parseClassStaticBlock = function(node) {
  16130. node.body = [];
  16131. var oldLabels = this.labels;
  16132. this.labels = [];
  16133. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  16134. while (this.type !== types$1.braceR) {
  16135. var stmt = this.parseStatement(null);
  16136. node.body.push(stmt);
  16137. }
  16138. this.next();
  16139. this.exitScope();
  16140. this.labels = oldLabels;
  16141. return this.finishNode(node, "StaticBlock")
  16142. };
  16143. pp$8.parseClassId = function(node, isStatement) {
  16144. if (this.type === types$1.name) {
  16145. node.id = this.parseIdent();
  16146. if (isStatement)
  16147. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  16148. } else {
  16149. if (isStatement === true)
  16150. { this.unexpected(); }
  16151. node.id = null;
  16152. }
  16153. };
  16154. pp$8.parseClassSuper = function(node) {
  16155. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
  16156. };
  16157. pp$8.enterClassBody = function() {
  16158. var element = {declared: Object.create(null), used: []};
  16159. this.privateNameStack.push(element);
  16160. return element.declared
  16161. };
  16162. pp$8.exitClassBody = function() {
  16163. var ref = this.privateNameStack.pop();
  16164. var declared = ref.declared;
  16165. var used = ref.used;
  16166. var len = this.privateNameStack.length;
  16167. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  16168. for (var i = 0; i < used.length; ++i) {
  16169. var id = used[i];
  16170. if (!hasOwn(declared, id.name)) {
  16171. if (parent) {
  16172. parent.used.push(id);
  16173. } else {
  16174. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  16175. }
  16176. }
  16177. }
  16178. };
  16179. function isPrivateNameConflicted(privateNameMap, element) {
  16180. var name = element.key.name;
  16181. var curr = privateNameMap[name];
  16182. var next = "true";
  16183. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  16184. next = (element.static ? "s" : "i") + element.kind;
  16185. }
  16186. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  16187. if (
  16188. curr === "iget" && next === "iset" ||
  16189. curr === "iset" && next === "iget" ||
  16190. curr === "sget" && next === "sset" ||
  16191. curr === "sset" && next === "sget"
  16192. ) {
  16193. privateNameMap[name] = "true";
  16194. return false
  16195. } else if (!curr) {
  16196. privateNameMap[name] = next;
  16197. return false
  16198. } else {
  16199. return true
  16200. }
  16201. }
  16202. function checkKeyName(node, name) {
  16203. var computed = node.computed;
  16204. var key = node.key;
  16205. return !computed && (
  16206. key.type === "Identifier" && key.name === name ||
  16207. key.type === "Literal" && key.value === name
  16208. )
  16209. }
  16210. // Parses module export declaration.
  16211. pp$8.parseExport = function(node, exports) {
  16212. this.next();
  16213. // export * from '...'
  16214. if (this.eat(types$1.star)) {
  16215. if (this.options.ecmaVersion >= 11) {
  16216. if (this.eatContextual("as")) {
  16217. node.exported = this.parseModuleExportName();
  16218. this.checkExport(exports, node.exported, this.lastTokStart);
  16219. } else {
  16220. node.exported = null;
  16221. }
  16222. }
  16223. this.expectContextual("from");
  16224. if (this.type !== types$1.string) { this.unexpected(); }
  16225. node.source = this.parseExprAtom();
  16226. this.semicolon();
  16227. return this.finishNode(node, "ExportAllDeclaration")
  16228. }
  16229. if (this.eat(types$1._default)) { // export default ...
  16230. this.checkExport(exports, "default", this.lastTokStart);
  16231. var isAsync;
  16232. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  16233. var fNode = this.startNode();
  16234. this.next();
  16235. if (isAsync) { this.next(); }
  16236. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  16237. } else if (this.type === types$1._class) {
  16238. var cNode = this.startNode();
  16239. node.declaration = this.parseClass(cNode, "nullableID");
  16240. } else {
  16241. node.declaration = this.parseMaybeAssign();
  16242. this.semicolon();
  16243. }
  16244. return this.finishNode(node, "ExportDefaultDeclaration")
  16245. }
  16246. // export var|const|let|function|class ...
  16247. if (this.shouldParseExportStatement()) {
  16248. node.declaration = this.parseStatement(null);
  16249. if (node.declaration.type === "VariableDeclaration")
  16250. { this.checkVariableExport(exports, node.declaration.declarations); }
  16251. else
  16252. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  16253. node.specifiers = [];
  16254. node.source = null;
  16255. } else { // export { x, y as z } [from '...']
  16256. node.declaration = null;
  16257. node.specifiers = this.parseExportSpecifiers(exports);
  16258. if (this.eatContextual("from")) {
  16259. if (this.type !== types$1.string) { this.unexpected(); }
  16260. node.source = this.parseExprAtom();
  16261. } else {
  16262. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  16263. // check for keywords used as local names
  16264. var spec = list[i];
  16265. this.checkUnreserved(spec.local);
  16266. // check if export is defined
  16267. this.checkLocalExport(spec.local);
  16268. if (spec.local.type === "Literal") {
  16269. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  16270. }
  16271. }
  16272. node.source = null;
  16273. }
  16274. this.semicolon();
  16275. }
  16276. return this.finishNode(node, "ExportNamedDeclaration")
  16277. };
  16278. pp$8.checkExport = function(exports, name, pos) {
  16279. if (!exports) { return }
  16280. if (typeof name !== "string")
  16281. { name = name.type === "Identifier" ? name.name : name.value; }
  16282. if (hasOwn(exports, name))
  16283. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  16284. exports[name] = true;
  16285. };
  16286. pp$8.checkPatternExport = function(exports, pat) {
  16287. var type = pat.type;
  16288. if (type === "Identifier")
  16289. { this.checkExport(exports, pat, pat.start); }
  16290. else if (type === "ObjectPattern")
  16291. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  16292. {
  16293. var prop = list[i];
  16294. this.checkPatternExport(exports, prop);
  16295. } }
  16296. else if (type === "ArrayPattern")
  16297. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  16298. var elt = list$1[i$1];
  16299. if (elt) { this.checkPatternExport(exports, elt); }
  16300. } }
  16301. else if (type === "Property")
  16302. { this.checkPatternExport(exports, pat.value); }
  16303. else if (type === "AssignmentPattern")
  16304. { this.checkPatternExport(exports, pat.left); }
  16305. else if (type === "RestElement")
  16306. { this.checkPatternExport(exports, pat.argument); }
  16307. else if (type === "ParenthesizedExpression")
  16308. { this.checkPatternExport(exports, pat.expression); }
  16309. };
  16310. pp$8.checkVariableExport = function(exports, decls) {
  16311. if (!exports) { return }
  16312. for (var i = 0, list = decls; i < list.length; i += 1)
  16313. {
  16314. var decl = list[i];
  16315. this.checkPatternExport(exports, decl.id);
  16316. }
  16317. };
  16318. pp$8.shouldParseExportStatement = function() {
  16319. return this.type.keyword === "var" ||
  16320. this.type.keyword === "const" ||
  16321. this.type.keyword === "class" ||
  16322. this.type.keyword === "function" ||
  16323. this.isLet() ||
  16324. this.isAsyncFunction()
  16325. };
  16326. // Parses a comma-separated list of module exports.
  16327. pp$8.parseExportSpecifiers = function(exports) {
  16328. var nodes = [], first = true;
  16329. // export { x, y as z } [from '...']
  16330. this.expect(types$1.braceL);
  16331. while (!this.eat(types$1.braceR)) {
  16332. if (!first) {
  16333. this.expect(types$1.comma);
  16334. if (this.afterTrailingComma(types$1.braceR)) { break }
  16335. } else { first = false; }
  16336. var node = this.startNode();
  16337. node.local = this.parseModuleExportName();
  16338. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  16339. this.checkExport(
  16340. exports,
  16341. node.exported,
  16342. node.exported.start
  16343. );
  16344. nodes.push(this.finishNode(node, "ExportSpecifier"));
  16345. }
  16346. return nodes
  16347. };
  16348. // Parses import declaration.
  16349. pp$8.parseImport = function(node) {
  16350. this.next();
  16351. // import '...'
  16352. if (this.type === types$1.string) {
  16353. node.specifiers = empty$1;
  16354. node.source = this.parseExprAtom();
  16355. } else {
  16356. node.specifiers = this.parseImportSpecifiers();
  16357. this.expectContextual("from");
  16358. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  16359. }
  16360. this.semicolon();
  16361. return this.finishNode(node, "ImportDeclaration")
  16362. };
  16363. // Parses a comma-separated list of module imports.
  16364. pp$8.parseImportSpecifiers = function() {
  16365. var nodes = [], first = true;
  16366. if (this.type === types$1.name) {
  16367. // import defaultObj, { x, y as z } from '...'
  16368. var node = this.startNode();
  16369. node.local = this.parseIdent();
  16370. this.checkLValSimple(node.local, BIND_LEXICAL);
  16371. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  16372. if (!this.eat(types$1.comma)) { return nodes }
  16373. }
  16374. if (this.type === types$1.star) {
  16375. var node$1 = this.startNode();
  16376. this.next();
  16377. this.expectContextual("as");
  16378. node$1.local = this.parseIdent();
  16379. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  16380. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  16381. return nodes
  16382. }
  16383. this.expect(types$1.braceL);
  16384. while (!this.eat(types$1.braceR)) {
  16385. if (!first) {
  16386. this.expect(types$1.comma);
  16387. if (this.afterTrailingComma(types$1.braceR)) { break }
  16388. } else { first = false; }
  16389. var node$2 = this.startNode();
  16390. node$2.imported = this.parseModuleExportName();
  16391. if (this.eatContextual("as")) {
  16392. node$2.local = this.parseIdent();
  16393. } else {
  16394. this.checkUnreserved(node$2.imported);
  16395. node$2.local = node$2.imported;
  16396. }
  16397. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  16398. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  16399. }
  16400. return nodes
  16401. };
  16402. pp$8.parseModuleExportName = function() {
  16403. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  16404. var stringLiteral = this.parseLiteral(this.value);
  16405. if (loneSurrogate.test(stringLiteral.value)) {
  16406. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  16407. }
  16408. return stringLiteral
  16409. }
  16410. return this.parseIdent(true)
  16411. };
  16412. // Set `ExpressionStatement#directive` property for directive prologues.
  16413. pp$8.adaptDirectivePrologue = function(statements) {
  16414. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  16415. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  16416. }
  16417. };
  16418. pp$8.isDirectiveCandidate = function(statement) {
  16419. return (
  16420. this.options.ecmaVersion >= 5 &&
  16421. statement.type === "ExpressionStatement" &&
  16422. statement.expression.type === "Literal" &&
  16423. typeof statement.expression.value === "string" &&
  16424. // Reject parenthesized strings.
  16425. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  16426. )
  16427. };
  16428. var pp$7 = Parser$1.prototype;
  16429. // Convert existing expression atom to assignable pattern
  16430. // if possible.
  16431. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  16432. if (this.options.ecmaVersion >= 6 && node) {
  16433. switch (node.type) {
  16434. case "Identifier":
  16435. if (this.inAsync && node.name === "await")
  16436. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  16437. break
  16438. case "ObjectPattern":
  16439. case "ArrayPattern":
  16440. case "AssignmentPattern":
  16441. case "RestElement":
  16442. break
  16443. case "ObjectExpression":
  16444. node.type = "ObjectPattern";
  16445. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16446. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  16447. var prop = list[i];
  16448. this.toAssignable(prop, isBinding);
  16449. // Early error:
  16450. // AssignmentRestProperty[Yield, Await] :
  16451. // `...` DestructuringAssignmentTarget[Yield, Await]
  16452. //
  16453. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  16454. if (
  16455. prop.type === "RestElement" &&
  16456. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  16457. ) {
  16458. this.raise(prop.argument.start, "Unexpected token");
  16459. }
  16460. }
  16461. break
  16462. case "Property":
  16463. // AssignmentProperty has type === "Property"
  16464. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  16465. this.toAssignable(node.value, isBinding);
  16466. break
  16467. case "ArrayExpression":
  16468. node.type = "ArrayPattern";
  16469. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16470. this.toAssignableList(node.elements, isBinding);
  16471. break
  16472. case "SpreadElement":
  16473. node.type = "RestElement";
  16474. this.toAssignable(node.argument, isBinding);
  16475. if (node.argument.type === "AssignmentPattern")
  16476. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  16477. break
  16478. case "AssignmentExpression":
  16479. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  16480. node.type = "AssignmentPattern";
  16481. delete node.operator;
  16482. this.toAssignable(node.left, isBinding);
  16483. break
  16484. case "ParenthesizedExpression":
  16485. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  16486. break
  16487. case "ChainExpression":
  16488. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  16489. break
  16490. case "MemberExpression":
  16491. if (!isBinding) { break }
  16492. default:
  16493. this.raise(node.start, "Assigning to rvalue");
  16494. }
  16495. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16496. return node
  16497. };
  16498. // Convert list of expression atoms to binding list.
  16499. pp$7.toAssignableList = function(exprList, isBinding) {
  16500. var end = exprList.length;
  16501. for (var i = 0; i < end; i++) {
  16502. var elt = exprList[i];
  16503. if (elt) { this.toAssignable(elt, isBinding); }
  16504. }
  16505. if (end) {
  16506. var last = exprList[end - 1];
  16507. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  16508. { this.unexpected(last.argument.start); }
  16509. }
  16510. return exprList
  16511. };
  16512. // Parses spread element.
  16513. pp$7.parseSpread = function(refDestructuringErrors) {
  16514. var node = this.startNode();
  16515. this.next();
  16516. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  16517. return this.finishNode(node, "SpreadElement")
  16518. };
  16519. pp$7.parseRestBinding = function() {
  16520. var node = this.startNode();
  16521. this.next();
  16522. // RestElement inside of a function parameter must be an identifier
  16523. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  16524. { this.unexpected(); }
  16525. node.argument = this.parseBindingAtom();
  16526. return this.finishNode(node, "RestElement")
  16527. };
  16528. // Parses lvalue (assignable) atom.
  16529. pp$7.parseBindingAtom = function() {
  16530. if (this.options.ecmaVersion >= 6) {
  16531. switch (this.type) {
  16532. case types$1.bracketL:
  16533. var node = this.startNode();
  16534. this.next();
  16535. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  16536. return this.finishNode(node, "ArrayPattern")
  16537. case types$1.braceL:
  16538. return this.parseObj(true)
  16539. }
  16540. }
  16541. return this.parseIdent()
  16542. };
  16543. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  16544. var elts = [], first = true;
  16545. while (!this.eat(close)) {
  16546. if (first) { first = false; }
  16547. else { this.expect(types$1.comma); }
  16548. if (allowEmpty && this.type === types$1.comma) {
  16549. elts.push(null);
  16550. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  16551. break
  16552. } else if (this.type === types$1.ellipsis) {
  16553. var rest = this.parseRestBinding();
  16554. this.parseBindingListItem(rest);
  16555. elts.push(rest);
  16556. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  16557. this.expect(close);
  16558. break
  16559. } else {
  16560. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  16561. this.parseBindingListItem(elem);
  16562. elts.push(elem);
  16563. }
  16564. }
  16565. return elts
  16566. };
  16567. pp$7.parseBindingListItem = function(param) {
  16568. return param
  16569. };
  16570. // Parses assignment pattern around given atom if possible.
  16571. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  16572. left = left || this.parseBindingAtom();
  16573. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  16574. var node = this.startNodeAt(startPos, startLoc);
  16575. node.left = left;
  16576. node.right = this.parseMaybeAssign();
  16577. return this.finishNode(node, "AssignmentPattern")
  16578. };
  16579. // The following three functions all verify that a node is an lvalue —
  16580. // something that can be bound, or assigned to. In order to do so, they perform
  16581. // a variety of checks:
  16582. //
  16583. // - Check that none of the bound/assigned-to identifiers are reserved words.
  16584. // - Record name declarations for bindings in the appropriate scope.
  16585. // - Check duplicate argument names, if checkClashes is set.
  16586. //
  16587. // If a complex binding pattern is encountered (e.g., object and array
  16588. // destructuring), the entire pattern is recursively checked.
  16589. //
  16590. // There are three versions of checkLVal*() appropriate for different
  16591. // circumstances:
  16592. //
  16593. // - checkLValSimple() shall be used if the syntactic construct supports
  16594. // nothing other than identifiers and member expressions. Parenthesized
  16595. // expressions are also correctly handled. This is generally appropriate for
  16596. // constructs for which the spec says
  16597. //
  16598. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  16599. // > simple.
  16600. //
  16601. // It is also appropriate for checking if an identifier is valid and not
  16602. // defined elsewhere, like import declarations or function/class identifiers.
  16603. //
  16604. // Examples where this is used include:
  16605. // a += …;
  16606. // import a from '…';
  16607. // where a is the node to be checked.
  16608. //
  16609. // - checkLValPattern() shall be used if the syntactic construct supports
  16610. // anything checkLValSimple() supports, as well as object and array
  16611. // destructuring patterns. This is generally appropriate for constructs for
  16612. // which the spec says
  16613. //
  16614. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  16615. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  16616. // > simple.
  16617. //
  16618. // Examples where this is used include:
  16619. // (a = …);
  16620. // const a = …;
  16621. // try { … } catch (a) { … }
  16622. // where a is the node to be checked.
  16623. //
  16624. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  16625. // anything checkLValPattern() supports, as well as default assignment
  16626. // patterns, rest elements, and other constructs that may appear within an
  16627. // object or array destructuring pattern.
  16628. //
  16629. // As a special case, function parameters also use checkLValInnerPattern(),
  16630. // as they also support defaults and rest constructs.
  16631. //
  16632. // These functions deliberately support both assignment and binding constructs,
  16633. // as the logic for both is exceedingly similar. If the node is the target of
  16634. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  16635. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  16636. // BIND_LEXICAL.
  16637. //
  16638. // If the function is called with a non-BIND_NONE bindingType, then
  16639. // additionally a checkClashes object may be specified to allow checking for
  16640. // duplicate argument names. checkClashes is ignored if the provided construct
  16641. // is an assignment (i.e., bindingType is BIND_NONE).
  16642. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  16643. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  16644. var isBind = bindingType !== BIND_NONE;
  16645. switch (expr.type) {
  16646. case "Identifier":
  16647. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  16648. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  16649. if (isBind) {
  16650. if (bindingType === BIND_LEXICAL && expr.name === "let")
  16651. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  16652. if (checkClashes) {
  16653. if (hasOwn(checkClashes, expr.name))
  16654. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  16655. checkClashes[expr.name] = true;
  16656. }
  16657. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  16658. }
  16659. break
  16660. case "ChainExpression":
  16661. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  16662. break
  16663. case "MemberExpression":
  16664. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  16665. break
  16666. case "ParenthesizedExpression":
  16667. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  16668. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  16669. default:
  16670. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  16671. }
  16672. };
  16673. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  16674. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  16675. switch (expr.type) {
  16676. case "ObjectPattern":
  16677. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  16678. var prop = list[i];
  16679. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  16680. }
  16681. break
  16682. case "ArrayPattern":
  16683. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  16684. var elem = list$1[i$1];
  16685. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  16686. }
  16687. break
  16688. default:
  16689. this.checkLValSimple(expr, bindingType, checkClashes);
  16690. }
  16691. };
  16692. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  16693. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  16694. switch (expr.type) {
  16695. case "Property":
  16696. // AssignmentProperty has type === "Property"
  16697. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  16698. break
  16699. case "AssignmentPattern":
  16700. this.checkLValPattern(expr.left, bindingType, checkClashes);
  16701. break
  16702. case "RestElement":
  16703. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  16704. break
  16705. default:
  16706. this.checkLValPattern(expr, bindingType, checkClashes);
  16707. }
  16708. };
  16709. // The algorithm used to determine whether a regexp can appear at a
  16710. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  16711. this.token = token;
  16712. this.isExpr = !!isExpr;
  16713. this.preserveSpace = !!preserveSpace;
  16714. this.override = override;
  16715. this.generator = !!generator;
  16716. };
  16717. var types$2 = {
  16718. b_stat: new TokContext("{", false),
  16719. b_expr: new TokContext("{", true),
  16720. b_tmpl: new TokContext("${", false),
  16721. p_stat: new TokContext("(", false),
  16722. p_expr: new TokContext("(", true),
  16723. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  16724. f_stat: new TokContext("function", false),
  16725. f_expr: new TokContext("function", true),
  16726. f_expr_gen: new TokContext("function", true, false, null, true),
  16727. f_gen: new TokContext("function", false, false, null, true)
  16728. };
  16729. var pp$6 = Parser$1.prototype;
  16730. pp$6.initialContext = function() {
  16731. return [types$2.b_stat]
  16732. };
  16733. pp$6.curContext = function() {
  16734. return this.context[this.context.length - 1]
  16735. };
  16736. pp$6.braceIsBlock = function(prevType) {
  16737. var parent = this.curContext();
  16738. if (parent === types$2.f_expr || parent === types$2.f_stat)
  16739. { return true }
  16740. if (prevType === types$1.colon && (parent === types$2.b_stat || parent === types$2.b_expr))
  16741. { return !parent.isExpr }
  16742. // The check for `tt.name && exprAllowed` detects whether we are
  16743. // after a `yield` or `of` construct. See the `updateContext` for
  16744. // `tt.name`.
  16745. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  16746. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  16747. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  16748. { return true }
  16749. if (prevType === types$1.braceL)
  16750. { return parent === types$2.b_stat }
  16751. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  16752. { return false }
  16753. return !this.exprAllowed
  16754. };
  16755. pp$6.inGeneratorContext = function() {
  16756. for (var i = this.context.length - 1; i >= 1; i--) {
  16757. var context = this.context[i];
  16758. if (context.token === "function")
  16759. { return context.generator }
  16760. }
  16761. return false
  16762. };
  16763. pp$6.updateContext = function(prevType) {
  16764. var update, type = this.type;
  16765. if (type.keyword && prevType === types$1.dot)
  16766. { this.exprAllowed = false; }
  16767. else if (update = type.updateContext)
  16768. { update.call(this, prevType); }
  16769. else
  16770. { this.exprAllowed = type.beforeExpr; }
  16771. };
  16772. // Used to handle egde cases when token context could not be inferred correctly during tokenization phase
  16773. pp$6.overrideContext = function(tokenCtx) {
  16774. if (this.curContext() !== tokenCtx) {
  16775. this.context[this.context.length - 1] = tokenCtx;
  16776. }
  16777. };
  16778. // Token-specific context update code
  16779. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  16780. if (this.context.length === 1) {
  16781. this.exprAllowed = true;
  16782. return
  16783. }
  16784. var out = this.context.pop();
  16785. if (out === types$2.b_stat && this.curContext().token === "function") {
  16786. out = this.context.pop();
  16787. }
  16788. this.exprAllowed = !out.isExpr;
  16789. };
  16790. types$1.braceL.updateContext = function(prevType) {
  16791. this.context.push(this.braceIsBlock(prevType) ? types$2.b_stat : types$2.b_expr);
  16792. this.exprAllowed = true;
  16793. };
  16794. types$1.dollarBraceL.updateContext = function() {
  16795. this.context.push(types$2.b_tmpl);
  16796. this.exprAllowed = true;
  16797. };
  16798. types$1.parenL.updateContext = function(prevType) {
  16799. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  16800. this.context.push(statementParens ? types$2.p_stat : types$2.p_expr);
  16801. this.exprAllowed = true;
  16802. };
  16803. types$1.incDec.updateContext = function() {
  16804. // tokExprAllowed stays unchanged
  16805. };
  16806. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  16807. if (prevType.beforeExpr && prevType !== types$1._else &&
  16808. !(prevType === types$1.semi && this.curContext() !== types$2.p_stat) &&
  16809. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  16810. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types$2.b_stat))
  16811. { this.context.push(types$2.f_expr); }
  16812. else
  16813. { this.context.push(types$2.f_stat); }
  16814. this.exprAllowed = false;
  16815. };
  16816. types$1.backQuote.updateContext = function() {
  16817. if (this.curContext() === types$2.q_tmpl)
  16818. { this.context.pop(); }
  16819. else
  16820. { this.context.push(types$2.q_tmpl); }
  16821. this.exprAllowed = false;
  16822. };
  16823. types$1.star.updateContext = function(prevType) {
  16824. if (prevType === types$1._function) {
  16825. var index = this.context.length - 1;
  16826. if (this.context[index] === types$2.f_expr)
  16827. { this.context[index] = types$2.f_expr_gen; }
  16828. else
  16829. { this.context[index] = types$2.f_gen; }
  16830. }
  16831. this.exprAllowed = true;
  16832. };
  16833. types$1.name.updateContext = function(prevType) {
  16834. var allowed = false;
  16835. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  16836. if (this.value === "of" && !this.exprAllowed ||
  16837. this.value === "yield" && this.inGeneratorContext())
  16838. { allowed = true; }
  16839. }
  16840. this.exprAllowed = allowed;
  16841. };
  16842. // A recursive descent parser operates by defining functions for all
  16843. var pp$5 = Parser$1.prototype;
  16844. // Check if property name clashes with already added.
  16845. // Object/class getters and setters are not allowed to clash —
  16846. // either with each other or with an init property — and in
  16847. // strict mode, init properties are also not allowed to be repeated.
  16848. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  16849. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  16850. { return }
  16851. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  16852. { return }
  16853. var key = prop.key;
  16854. var name;
  16855. switch (key.type) {
  16856. case "Identifier": name = key.name; break
  16857. case "Literal": name = String(key.value); break
  16858. default: return
  16859. }
  16860. var kind = prop.kind;
  16861. if (this.options.ecmaVersion >= 6) {
  16862. if (name === "__proto__" && kind === "init") {
  16863. if (propHash.proto) {
  16864. if (refDestructuringErrors) {
  16865. if (refDestructuringErrors.doubleProto < 0) {
  16866. refDestructuringErrors.doubleProto = key.start;
  16867. }
  16868. } else {
  16869. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  16870. }
  16871. }
  16872. propHash.proto = true;
  16873. }
  16874. return
  16875. }
  16876. name = "$" + name;
  16877. var other = propHash[name];
  16878. if (other) {
  16879. var redefinition;
  16880. if (kind === "init") {
  16881. redefinition = this.strict && other.init || other.get || other.set;
  16882. } else {
  16883. redefinition = other.init || other[kind];
  16884. }
  16885. if (redefinition)
  16886. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  16887. } else {
  16888. other = propHash[name] = {
  16889. init: false,
  16890. get: false,
  16891. set: false
  16892. };
  16893. }
  16894. other[kind] = true;
  16895. };
  16896. // ### Expression parsing
  16897. // These nest, from the most general expression type at the top to
  16898. // 'atomic', nondivisible expression types at the bottom. Most of
  16899. // the functions will simply let the function(s) below them parse,
  16900. // and, *if* the syntactic construct they handle is present, wrap
  16901. // the AST node that the inner parser gave them in another node.
  16902. // Parse a full expression. The optional arguments are used to
  16903. // forbid the `in` operator (in for loops initalization expressions)
  16904. // and provide reference for storing '=' operator inside shorthand
  16905. // property assignment in contexts where both object expression
  16906. // and object pattern might appear (so it's possible to raise
  16907. // delayed syntax error at correct position).
  16908. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  16909. var startPos = this.start, startLoc = this.startLoc;
  16910. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  16911. if (this.type === types$1.comma) {
  16912. var node = this.startNodeAt(startPos, startLoc);
  16913. node.expressions = [expr];
  16914. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  16915. return this.finishNode(node, "SequenceExpression")
  16916. }
  16917. return expr
  16918. };
  16919. // Parse an assignment expression. This includes applications of
  16920. // operators like `+=`.
  16921. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  16922. if (this.isContextual("yield")) {
  16923. if (this.inGenerator) { return this.parseYield(forInit) }
  16924. // The tokenizer will assume an expression is allowed after
  16925. // `yield`, but this isn't that kind of yield
  16926. else { this.exprAllowed = false; }
  16927. }
  16928. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  16929. if (refDestructuringErrors) {
  16930. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  16931. oldTrailingComma = refDestructuringErrors.trailingComma;
  16932. oldDoubleProto = refDestructuringErrors.doubleProto;
  16933. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  16934. } else {
  16935. refDestructuringErrors = new DestructuringErrors;
  16936. ownDestructuringErrors = true;
  16937. }
  16938. var startPos = this.start, startLoc = this.startLoc;
  16939. if (this.type === types$1.parenL || this.type === types$1.name) {
  16940. this.potentialArrowAt = this.start;
  16941. this.potentialArrowInForAwait = forInit === "await";
  16942. }
  16943. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  16944. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  16945. if (this.type.isAssign) {
  16946. var node = this.startNodeAt(startPos, startLoc);
  16947. node.operator = this.value;
  16948. if (this.type === types$1.eq)
  16949. { left = this.toAssignable(left, false, refDestructuringErrors); }
  16950. if (!ownDestructuringErrors) {
  16951. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  16952. }
  16953. if (refDestructuringErrors.shorthandAssign >= left.start)
  16954. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  16955. if (this.type === types$1.eq)
  16956. { this.checkLValPattern(left); }
  16957. else
  16958. { this.checkLValSimple(left); }
  16959. node.left = left;
  16960. this.next();
  16961. node.right = this.parseMaybeAssign(forInit);
  16962. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  16963. return this.finishNode(node, "AssignmentExpression")
  16964. } else {
  16965. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  16966. }
  16967. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  16968. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  16969. return left
  16970. };
  16971. // Parse a ternary conditional (`?:`) operator.
  16972. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  16973. var startPos = this.start, startLoc = this.startLoc;
  16974. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  16975. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  16976. if (this.eat(types$1.question)) {
  16977. var node = this.startNodeAt(startPos, startLoc);
  16978. node.test = expr;
  16979. node.consequent = this.parseMaybeAssign();
  16980. this.expect(types$1.colon);
  16981. node.alternate = this.parseMaybeAssign(forInit);
  16982. return this.finishNode(node, "ConditionalExpression")
  16983. }
  16984. return expr
  16985. };
  16986. // Start the precedence parser.
  16987. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  16988. var startPos = this.start, startLoc = this.startLoc;
  16989. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  16990. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  16991. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  16992. };
  16993. // Parse binary operators with the operator precedence parsing
  16994. // algorithm. `left` is the left-hand side of the operator.
  16995. // `minPrec` provides context that allows the function to stop and
  16996. // defer further parser to one of its callers when it encounters an
  16997. // operator that has a lower precedence than the set it is parsing.
  16998. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  16999. var prec = this.type.binop;
  17000. if (prec != null && (!forInit || this.type !== types$1._in)) {
  17001. if (prec > minPrec) {
  17002. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  17003. var coalesce = this.type === types$1.coalesce;
  17004. if (coalesce) {
  17005. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  17006. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  17007. prec = types$1.logicalAND.binop;
  17008. }
  17009. var op = this.value;
  17010. this.next();
  17011. var startPos = this.start, startLoc = this.startLoc;
  17012. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  17013. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  17014. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  17015. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  17016. }
  17017. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  17018. }
  17019. }
  17020. return left
  17021. };
  17022. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  17023. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  17024. var node = this.startNodeAt(startPos, startLoc);
  17025. node.left = left;
  17026. node.operator = op;
  17027. node.right = right;
  17028. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  17029. };
  17030. // Parse unary operators, both prefix and postfix.
  17031. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  17032. var startPos = this.start, startLoc = this.startLoc, expr;
  17033. if (this.isContextual("await") && this.canAwait) {
  17034. expr = this.parseAwait(forInit);
  17035. sawUnary = true;
  17036. } else if (this.type.prefix) {
  17037. var node = this.startNode(), update = this.type === types$1.incDec;
  17038. node.operator = this.value;
  17039. node.prefix = true;
  17040. this.next();
  17041. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  17042. this.checkExpressionErrors(refDestructuringErrors, true);
  17043. if (update) { this.checkLValSimple(node.argument); }
  17044. else if (this.strict && node.operator === "delete" &&
  17045. node.argument.type === "Identifier")
  17046. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  17047. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  17048. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  17049. else { sawUnary = true; }
  17050. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  17051. } else if (!sawUnary && this.type === types$1.privateId) {
  17052. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  17053. expr = this.parsePrivateIdent();
  17054. // only could be private fields in 'in', such as #x in obj
  17055. if (this.type !== types$1._in) { this.unexpected(); }
  17056. } else {
  17057. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  17058. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17059. while (this.type.postfix && !this.canInsertSemicolon()) {
  17060. var node$1 = this.startNodeAt(startPos, startLoc);
  17061. node$1.operator = this.value;
  17062. node$1.prefix = false;
  17063. node$1.argument = expr;
  17064. this.checkLValSimple(expr);
  17065. this.next();
  17066. expr = this.finishNode(node$1, "UpdateExpression");
  17067. }
  17068. }
  17069. if (!incDec && this.eat(types$1.starstar)) {
  17070. if (sawUnary)
  17071. { this.unexpected(this.lastTokStart); }
  17072. else
  17073. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  17074. } else {
  17075. return expr
  17076. }
  17077. };
  17078. function isPrivateFieldAccess(node) {
  17079. return (
  17080. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  17081. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  17082. )
  17083. }
  17084. // Parse call, dot, and `[]`-subscript expressions.
  17085. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  17086. var startPos = this.start, startLoc = this.startLoc;
  17087. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  17088. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  17089. { return expr }
  17090. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  17091. if (refDestructuringErrors && result.type === "MemberExpression") {
  17092. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  17093. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  17094. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  17095. }
  17096. return result
  17097. };
  17098. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  17099. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  17100. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  17101. this.potentialArrowAt === base.start;
  17102. var optionalChained = false;
  17103. while (true) {
  17104. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  17105. if (element.optional) { optionalChained = true; }
  17106. if (element === base || element.type === "ArrowFunctionExpression") {
  17107. if (optionalChained) {
  17108. var chainNode = this.startNodeAt(startPos, startLoc);
  17109. chainNode.expression = element;
  17110. element = this.finishNode(chainNode, "ChainExpression");
  17111. }
  17112. return element
  17113. }
  17114. base = element;
  17115. }
  17116. };
  17117. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  17118. var optionalSupported = this.options.ecmaVersion >= 11;
  17119. var optional = optionalSupported && this.eat(types$1.questionDot);
  17120. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  17121. var computed = this.eat(types$1.bracketL);
  17122. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  17123. var node = this.startNodeAt(startPos, startLoc);
  17124. node.object = base;
  17125. if (computed) {
  17126. node.property = this.parseExpression();
  17127. this.expect(types$1.bracketR);
  17128. } else if (this.type === types$1.privateId && base.type !== "Super") {
  17129. node.property = this.parsePrivateIdent();
  17130. } else {
  17131. node.property = this.parseIdent(this.options.allowReserved !== "never");
  17132. }
  17133. node.computed = !!computed;
  17134. if (optionalSupported) {
  17135. node.optional = optional;
  17136. }
  17137. base = this.finishNode(node, "MemberExpression");
  17138. } else if (!noCalls && this.eat(types$1.parenL)) {
  17139. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17140. this.yieldPos = 0;
  17141. this.awaitPos = 0;
  17142. this.awaitIdentPos = 0;
  17143. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  17144. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17145. this.checkPatternErrors(refDestructuringErrors, false);
  17146. this.checkYieldAwaitInDefaultParams();
  17147. if (this.awaitIdentPos > 0)
  17148. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  17149. this.yieldPos = oldYieldPos;
  17150. this.awaitPos = oldAwaitPos;
  17151. this.awaitIdentPos = oldAwaitIdentPos;
  17152. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  17153. }
  17154. this.checkExpressionErrors(refDestructuringErrors, true);
  17155. this.yieldPos = oldYieldPos || this.yieldPos;
  17156. this.awaitPos = oldAwaitPos || this.awaitPos;
  17157. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  17158. var node$1 = this.startNodeAt(startPos, startLoc);
  17159. node$1.callee = base;
  17160. node$1.arguments = exprList;
  17161. if (optionalSupported) {
  17162. node$1.optional = optional;
  17163. }
  17164. base = this.finishNode(node$1, "CallExpression");
  17165. } else if (this.type === types$1.backQuote) {
  17166. if (optional || optionalChained) {
  17167. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  17168. }
  17169. var node$2 = this.startNodeAt(startPos, startLoc);
  17170. node$2.tag = base;
  17171. node$2.quasi = this.parseTemplate({isTagged: true});
  17172. base = this.finishNode(node$2, "TaggedTemplateExpression");
  17173. }
  17174. return base
  17175. };
  17176. // Parse an atomic expression — either a single token that is an
  17177. // expression, an expression started by a keyword like `function` or
  17178. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  17179. // or `{}`.
  17180. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  17181. // If a division operator appears in an expression position, the
  17182. // tokenizer got confused, and we force it to read a regexp instead.
  17183. if (this.type === types$1.slash) { this.readRegexp(); }
  17184. var node, canBeArrow = this.potentialArrowAt === this.start;
  17185. switch (this.type) {
  17186. case types$1._super:
  17187. if (!this.allowSuper)
  17188. { this.raise(this.start, "'super' keyword outside a method"); }
  17189. node = this.startNode();
  17190. this.next();
  17191. if (this.type === types$1.parenL && !this.allowDirectSuper)
  17192. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  17193. // The `super` keyword can appear at below:
  17194. // SuperProperty:
  17195. // super [ Expression ]
  17196. // super . IdentifierName
  17197. // SuperCall:
  17198. // super ( Arguments )
  17199. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  17200. { this.unexpected(); }
  17201. return this.finishNode(node, "Super")
  17202. case types$1._this:
  17203. node = this.startNode();
  17204. this.next();
  17205. return this.finishNode(node, "ThisExpression")
  17206. case types$1.name:
  17207. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  17208. var id = this.parseIdent(false);
  17209. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  17210. this.overrideContext(types$2.f_expr);
  17211. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  17212. }
  17213. if (canBeArrow && !this.canInsertSemicolon()) {
  17214. if (this.eat(types$1.arrow))
  17215. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  17216. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  17217. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  17218. id = this.parseIdent(false);
  17219. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  17220. { this.unexpected(); }
  17221. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  17222. }
  17223. }
  17224. return id
  17225. case types$1.regexp:
  17226. var value = this.value;
  17227. node = this.parseLiteral(value.value);
  17228. node.regex = {pattern: value.pattern, flags: value.flags};
  17229. return node
  17230. case types$1.num: case types$1.string:
  17231. return this.parseLiteral(this.value)
  17232. case types$1._null: case types$1._true: case types$1._false:
  17233. node = this.startNode();
  17234. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  17235. node.raw = this.type.keyword;
  17236. this.next();
  17237. return this.finishNode(node, "Literal")
  17238. case types$1.parenL:
  17239. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  17240. if (refDestructuringErrors) {
  17241. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  17242. { refDestructuringErrors.parenthesizedAssign = start; }
  17243. if (refDestructuringErrors.parenthesizedBind < 0)
  17244. { refDestructuringErrors.parenthesizedBind = start; }
  17245. }
  17246. return expr
  17247. case types$1.bracketL:
  17248. node = this.startNode();
  17249. this.next();
  17250. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  17251. return this.finishNode(node, "ArrayExpression")
  17252. case types$1.braceL:
  17253. this.overrideContext(types$2.b_expr);
  17254. return this.parseObj(false, refDestructuringErrors)
  17255. case types$1._function:
  17256. node = this.startNode();
  17257. this.next();
  17258. return this.parseFunction(node, 0)
  17259. case types$1._class:
  17260. return this.parseClass(this.startNode(), false)
  17261. case types$1._new:
  17262. return this.parseNew()
  17263. case types$1.backQuote:
  17264. return this.parseTemplate()
  17265. case types$1._import:
  17266. if (this.options.ecmaVersion >= 11) {
  17267. return this.parseExprImport()
  17268. } else {
  17269. return this.unexpected()
  17270. }
  17271. default:
  17272. this.unexpected();
  17273. }
  17274. };
  17275. pp$5.parseExprImport = function() {
  17276. var node = this.startNode();
  17277. // Consume `import` as an identifier for `import.meta`.
  17278. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  17279. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  17280. var meta = this.parseIdent(true);
  17281. switch (this.type) {
  17282. case types$1.parenL:
  17283. return this.parseDynamicImport(node)
  17284. case types$1.dot:
  17285. node.meta = meta;
  17286. return this.parseImportMeta(node)
  17287. default:
  17288. this.unexpected();
  17289. }
  17290. };
  17291. pp$5.parseDynamicImport = function(node) {
  17292. this.next(); // skip `(`
  17293. // Parse node.source.
  17294. node.source = this.parseMaybeAssign();
  17295. // Verify ending.
  17296. if (!this.eat(types$1.parenR)) {
  17297. var errorPos = this.start;
  17298. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  17299. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  17300. } else {
  17301. this.unexpected(errorPos);
  17302. }
  17303. }
  17304. return this.finishNode(node, "ImportExpression")
  17305. };
  17306. pp$5.parseImportMeta = function(node) {
  17307. this.next(); // skip `.`
  17308. var containsEsc = this.containsEsc;
  17309. node.property = this.parseIdent(true);
  17310. if (node.property.name !== "meta")
  17311. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  17312. if (containsEsc)
  17313. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  17314. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  17315. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  17316. return this.finishNode(node, "MetaProperty")
  17317. };
  17318. pp$5.parseLiteral = function(value) {
  17319. var node = this.startNode();
  17320. node.value = value;
  17321. node.raw = this.input.slice(this.start, this.end);
  17322. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  17323. this.next();
  17324. return this.finishNode(node, "Literal")
  17325. };
  17326. pp$5.parseParenExpression = function() {
  17327. this.expect(types$1.parenL);
  17328. var val = this.parseExpression();
  17329. this.expect(types$1.parenR);
  17330. return val
  17331. };
  17332. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  17333. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  17334. if (this.options.ecmaVersion >= 6) {
  17335. this.next();
  17336. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  17337. var exprList = [], first = true, lastIsComma = false;
  17338. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  17339. this.yieldPos = 0;
  17340. this.awaitPos = 0;
  17341. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  17342. while (this.type !== types$1.parenR) {
  17343. first ? first = false : this.expect(types$1.comma);
  17344. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  17345. lastIsComma = true;
  17346. break
  17347. } else if (this.type === types$1.ellipsis) {
  17348. spreadStart = this.start;
  17349. exprList.push(this.parseParenItem(this.parseRestBinding()));
  17350. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17351. break
  17352. } else {
  17353. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  17354. }
  17355. }
  17356. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  17357. this.expect(types$1.parenR);
  17358. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17359. this.checkPatternErrors(refDestructuringErrors, false);
  17360. this.checkYieldAwaitInDefaultParams();
  17361. this.yieldPos = oldYieldPos;
  17362. this.awaitPos = oldAwaitPos;
  17363. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  17364. }
  17365. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  17366. if (spreadStart) { this.unexpected(spreadStart); }
  17367. this.checkExpressionErrors(refDestructuringErrors, true);
  17368. this.yieldPos = oldYieldPos || this.yieldPos;
  17369. this.awaitPos = oldAwaitPos || this.awaitPos;
  17370. if (exprList.length > 1) {
  17371. val = this.startNodeAt(innerStartPos, innerStartLoc);
  17372. val.expressions = exprList;
  17373. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  17374. } else {
  17375. val = exprList[0];
  17376. }
  17377. } else {
  17378. val = this.parseParenExpression();
  17379. }
  17380. if (this.options.preserveParens) {
  17381. var par = this.startNodeAt(startPos, startLoc);
  17382. par.expression = val;
  17383. return this.finishNode(par, "ParenthesizedExpression")
  17384. } else {
  17385. return val
  17386. }
  17387. };
  17388. pp$5.parseParenItem = function(item) {
  17389. return item
  17390. };
  17391. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  17392. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  17393. };
  17394. // New's precedence is slightly tricky. It must allow its argument to
  17395. // be a `[]` or dot subscript expression, but not a call — at least,
  17396. // not without wrapping it in parentheses. Thus, it uses the noCalls
  17397. // argument to parseSubscripts to prevent it from consuming the
  17398. // argument list.
  17399. var empty = [];
  17400. pp$5.parseNew = function() {
  17401. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  17402. var node = this.startNode();
  17403. var meta = this.parseIdent(true);
  17404. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  17405. node.meta = meta;
  17406. var containsEsc = this.containsEsc;
  17407. node.property = this.parseIdent(true);
  17408. if (node.property.name !== "target")
  17409. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  17410. if (containsEsc)
  17411. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  17412. if (!this.allowNewDotTarget)
  17413. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  17414. return this.finishNode(node, "MetaProperty")
  17415. }
  17416. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  17417. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  17418. if (isImport && node.callee.type === "ImportExpression") {
  17419. this.raise(startPos, "Cannot use new with import()");
  17420. }
  17421. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  17422. else { node.arguments = empty; }
  17423. return this.finishNode(node, "NewExpression")
  17424. };
  17425. // Parse template expression.
  17426. pp$5.parseTemplateElement = function(ref) {
  17427. var isTagged = ref.isTagged;
  17428. var elem = this.startNode();
  17429. if (this.type === types$1.invalidTemplate) {
  17430. if (!isTagged) {
  17431. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  17432. }
  17433. elem.value = {
  17434. raw: this.value,
  17435. cooked: null
  17436. };
  17437. } else {
  17438. elem.value = {
  17439. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  17440. cooked: this.value
  17441. };
  17442. }
  17443. this.next();
  17444. elem.tail = this.type === types$1.backQuote;
  17445. return this.finishNode(elem, "TemplateElement")
  17446. };
  17447. pp$5.parseTemplate = function(ref) {
  17448. if ( ref === void 0 ) ref = {};
  17449. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  17450. var node = this.startNode();
  17451. this.next();
  17452. node.expressions = [];
  17453. var curElt = this.parseTemplateElement({isTagged: isTagged});
  17454. node.quasis = [curElt];
  17455. while (!curElt.tail) {
  17456. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  17457. this.expect(types$1.dollarBraceL);
  17458. node.expressions.push(this.parseExpression());
  17459. this.expect(types$1.braceR);
  17460. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  17461. }
  17462. this.next();
  17463. return this.finishNode(node, "TemplateLiteral")
  17464. };
  17465. pp$5.isAsyncProp = function(prop) {
  17466. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  17467. (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
  17468. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  17469. };
  17470. // Parse an object literal or binding pattern.
  17471. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  17472. var node = this.startNode(), first = true, propHash = {};
  17473. node.properties = [];
  17474. this.next();
  17475. while (!this.eat(types$1.braceR)) {
  17476. if (!first) {
  17477. this.expect(types$1.comma);
  17478. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  17479. } else { first = false; }
  17480. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  17481. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  17482. node.properties.push(prop);
  17483. }
  17484. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  17485. };
  17486. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  17487. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  17488. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  17489. if (isPattern) {
  17490. prop.argument = this.parseIdent(false);
  17491. if (this.type === types$1.comma) {
  17492. this.raise(this.start, "Comma is not permitted after the rest element");
  17493. }
  17494. return this.finishNode(prop, "RestElement")
  17495. }
  17496. // Parse argument.
  17497. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  17498. // To disallow trailing comma via `this.toAssignable()`.
  17499. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  17500. refDestructuringErrors.trailingComma = this.start;
  17501. }
  17502. // Finish
  17503. return this.finishNode(prop, "SpreadElement")
  17504. }
  17505. if (this.options.ecmaVersion >= 6) {
  17506. prop.method = false;
  17507. prop.shorthand = false;
  17508. if (isPattern || refDestructuringErrors) {
  17509. startPos = this.start;
  17510. startLoc = this.startLoc;
  17511. }
  17512. if (!isPattern)
  17513. { isGenerator = this.eat(types$1.star); }
  17514. }
  17515. var containsEsc = this.containsEsc;
  17516. this.parsePropertyName(prop);
  17517. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  17518. isAsync = true;
  17519. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  17520. this.parsePropertyName(prop);
  17521. } else {
  17522. isAsync = false;
  17523. }
  17524. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  17525. return this.finishNode(prop, "Property")
  17526. };
  17527. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  17528. if ((isGenerator || isAsync) && this.type === types$1.colon)
  17529. { this.unexpected(); }
  17530. if (this.eat(types$1.colon)) {
  17531. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  17532. prop.kind = "init";
  17533. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  17534. if (isPattern) { this.unexpected(); }
  17535. prop.kind = "init";
  17536. prop.method = true;
  17537. prop.value = this.parseMethod(isGenerator, isAsync);
  17538. } else if (!isPattern && !containsEsc &&
  17539. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  17540. (prop.key.name === "get" || prop.key.name === "set") &&
  17541. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  17542. if (isGenerator || isAsync) { this.unexpected(); }
  17543. prop.kind = prop.key.name;
  17544. this.parsePropertyName(prop);
  17545. prop.value = this.parseMethod(false);
  17546. var paramCount = prop.kind === "get" ? 0 : 1;
  17547. if (prop.value.params.length !== paramCount) {
  17548. var start = prop.value.start;
  17549. if (prop.kind === "get")
  17550. { this.raiseRecoverable(start, "getter should have no params"); }
  17551. else
  17552. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  17553. } else {
  17554. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  17555. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  17556. }
  17557. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  17558. if (isGenerator || isAsync) { this.unexpected(); }
  17559. this.checkUnreserved(prop.key);
  17560. if (prop.key.name === "await" && !this.awaitIdentPos)
  17561. { this.awaitIdentPos = startPos; }
  17562. prop.kind = "init";
  17563. if (isPattern) {
  17564. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  17565. } else if (this.type === types$1.eq && refDestructuringErrors) {
  17566. if (refDestructuringErrors.shorthandAssign < 0)
  17567. { refDestructuringErrors.shorthandAssign = this.start; }
  17568. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  17569. } else {
  17570. prop.value = this.copyNode(prop.key);
  17571. }
  17572. prop.shorthand = true;
  17573. } else { this.unexpected(); }
  17574. };
  17575. pp$5.parsePropertyName = function(prop) {
  17576. if (this.options.ecmaVersion >= 6) {
  17577. if (this.eat(types$1.bracketL)) {
  17578. prop.computed = true;
  17579. prop.key = this.parseMaybeAssign();
  17580. this.expect(types$1.bracketR);
  17581. return prop.key
  17582. } else {
  17583. prop.computed = false;
  17584. }
  17585. }
  17586. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  17587. };
  17588. // Initialize empty function node.
  17589. pp$5.initFunction = function(node) {
  17590. node.id = null;
  17591. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  17592. if (this.options.ecmaVersion >= 8) { node.async = false; }
  17593. };
  17594. // Parse object or class method.
  17595. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  17596. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17597. this.initFunction(node);
  17598. if (this.options.ecmaVersion >= 6)
  17599. { node.generator = isGenerator; }
  17600. if (this.options.ecmaVersion >= 8)
  17601. { node.async = !!isAsync; }
  17602. this.yieldPos = 0;
  17603. this.awaitPos = 0;
  17604. this.awaitIdentPos = 0;
  17605. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  17606. this.expect(types$1.parenL);
  17607. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  17608. this.checkYieldAwaitInDefaultParams();
  17609. this.parseFunctionBody(node, false, true, false);
  17610. this.yieldPos = oldYieldPos;
  17611. this.awaitPos = oldAwaitPos;
  17612. this.awaitIdentPos = oldAwaitIdentPos;
  17613. return this.finishNode(node, "FunctionExpression")
  17614. };
  17615. // Parse arrow function expression with given parameters.
  17616. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  17617. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17618. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  17619. this.initFunction(node);
  17620. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  17621. this.yieldPos = 0;
  17622. this.awaitPos = 0;
  17623. this.awaitIdentPos = 0;
  17624. node.params = this.toAssignableList(params, true);
  17625. this.parseFunctionBody(node, true, false, forInit);
  17626. this.yieldPos = oldYieldPos;
  17627. this.awaitPos = oldAwaitPos;
  17628. this.awaitIdentPos = oldAwaitIdentPos;
  17629. return this.finishNode(node, "ArrowFunctionExpression")
  17630. };
  17631. // Parse function body and check parameters.
  17632. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  17633. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  17634. var oldStrict = this.strict, useStrict = false;
  17635. if (isExpression) {
  17636. node.body = this.parseMaybeAssign(forInit);
  17637. node.expression = true;
  17638. this.checkParams(node, false);
  17639. } else {
  17640. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  17641. if (!oldStrict || nonSimple) {
  17642. useStrict = this.strictDirective(this.end);
  17643. // If this is a strict mode function, verify that argument names
  17644. // are not repeated, and it does not try to bind the words `eval`
  17645. // or `arguments`.
  17646. if (useStrict && nonSimple)
  17647. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  17648. }
  17649. // Start a new scope with regard to labels and the `inFunction`
  17650. // flag (restore them to their old value afterwards).
  17651. var oldLabels = this.labels;
  17652. this.labels = [];
  17653. if (useStrict) { this.strict = true; }
  17654. // Add the params to varDeclaredNames to ensure that an error is thrown
  17655. // if a let/const declaration in the function clashes with one of the params.
  17656. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  17657. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  17658. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  17659. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  17660. node.expression = false;
  17661. this.adaptDirectivePrologue(node.body.body);
  17662. this.labels = oldLabels;
  17663. }
  17664. this.exitScope();
  17665. };
  17666. pp$5.isSimpleParamList = function(params) {
  17667. for (var i = 0, list = params; i < list.length; i += 1)
  17668. {
  17669. var param = list[i];
  17670. if (param.type !== "Identifier") { return false
  17671. } }
  17672. return true
  17673. };
  17674. // Checks function params for various disallowed patterns such as using "eval"
  17675. // or "arguments" and duplicate parameters.
  17676. pp$5.checkParams = function(node, allowDuplicates) {
  17677. var nameHash = Object.create(null);
  17678. for (var i = 0, list = node.params; i < list.length; i += 1)
  17679. {
  17680. var param = list[i];
  17681. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  17682. }
  17683. };
  17684. // Parses a comma-separated list of expressions, and returns them as
  17685. // an array. `close` is the token type that ends the list, and
  17686. // `allowEmpty` can be turned on to allow subsequent commas with
  17687. // nothing in between them to be parsed as `null` (which is needed
  17688. // for array literals).
  17689. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  17690. var elts = [], first = true;
  17691. while (!this.eat(close)) {
  17692. if (!first) {
  17693. this.expect(types$1.comma);
  17694. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  17695. } else { first = false; }
  17696. var elt = (void 0);
  17697. if (allowEmpty && this.type === types$1.comma)
  17698. { elt = null; }
  17699. else if (this.type === types$1.ellipsis) {
  17700. elt = this.parseSpread(refDestructuringErrors);
  17701. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  17702. { refDestructuringErrors.trailingComma = this.start; }
  17703. } else {
  17704. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  17705. }
  17706. elts.push(elt);
  17707. }
  17708. return elts
  17709. };
  17710. pp$5.checkUnreserved = function(ref) {
  17711. var start = ref.start;
  17712. var end = ref.end;
  17713. var name = ref.name;
  17714. if (this.inGenerator && name === "yield")
  17715. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  17716. if (this.inAsync && name === "await")
  17717. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  17718. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  17719. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  17720. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  17721. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  17722. if (this.keywords.test(name))
  17723. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  17724. if (this.options.ecmaVersion < 6 &&
  17725. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  17726. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  17727. if (re.test(name)) {
  17728. if (!this.inAsync && name === "await")
  17729. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  17730. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  17731. }
  17732. };
  17733. // Parse the next token as an identifier. If `liberal` is true (used
  17734. // when parsing properties), it will also convert keywords into
  17735. // identifiers.
  17736. pp$5.parseIdent = function(liberal) {
  17737. var node = this.startNode();
  17738. if (this.type === types$1.name) {
  17739. node.name = this.value;
  17740. } else if (this.type.keyword) {
  17741. node.name = this.type.keyword;
  17742. // To fix https://github.com/acornjs/acorn/issues/575
  17743. // `class` and `function` keywords push new context into this.context.
  17744. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  17745. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  17746. if ((node.name === "class" || node.name === "function") &&
  17747. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  17748. this.context.pop();
  17749. }
  17750. } else {
  17751. this.unexpected();
  17752. }
  17753. this.next(!!liberal);
  17754. this.finishNode(node, "Identifier");
  17755. if (!liberal) {
  17756. this.checkUnreserved(node);
  17757. if (node.name === "await" && !this.awaitIdentPos)
  17758. { this.awaitIdentPos = node.start; }
  17759. }
  17760. return node
  17761. };
  17762. pp$5.parsePrivateIdent = function() {
  17763. var node = this.startNode();
  17764. if (this.type === types$1.privateId) {
  17765. node.name = this.value;
  17766. } else {
  17767. this.unexpected();
  17768. }
  17769. this.next();
  17770. this.finishNode(node, "PrivateIdentifier");
  17771. // For validating existence
  17772. if (this.privateNameStack.length === 0) {
  17773. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  17774. } else {
  17775. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  17776. }
  17777. return node
  17778. };
  17779. // Parses yield expression inside generator.
  17780. pp$5.parseYield = function(forInit) {
  17781. if (!this.yieldPos) { this.yieldPos = this.start; }
  17782. var node = this.startNode();
  17783. this.next();
  17784. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  17785. node.delegate = false;
  17786. node.argument = null;
  17787. } else {
  17788. node.delegate = this.eat(types$1.star);
  17789. node.argument = this.parseMaybeAssign(forInit);
  17790. }
  17791. return this.finishNode(node, "YieldExpression")
  17792. };
  17793. pp$5.parseAwait = function(forInit) {
  17794. if (!this.awaitPos) { this.awaitPos = this.start; }
  17795. var node = this.startNode();
  17796. this.next();
  17797. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  17798. return this.finishNode(node, "AwaitExpression")
  17799. };
  17800. var pp$4 = Parser$1.prototype;
  17801. // This function is used to raise exceptions on parse errors. It
  17802. // takes an offset integer (into the current `input`) to indicate
  17803. // the location of the error, attaches the position to the end
  17804. // of the error message, and then raises a `SyntaxError` with that
  17805. // message.
  17806. pp$4.raise = function(pos, message) {
  17807. var loc = getLineInfo(this.input, pos);
  17808. message += " (" + loc.line + ":" + loc.column + ")";
  17809. var err = new SyntaxError(message);
  17810. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  17811. throw err
  17812. };
  17813. pp$4.raiseRecoverable = pp$4.raise;
  17814. pp$4.curPosition = function() {
  17815. if (this.options.locations) {
  17816. return new Position(this.curLine, this.pos - this.lineStart)
  17817. }
  17818. };
  17819. var pp$3 = Parser$1.prototype;
  17820. var Scope = function Scope(flags) {
  17821. this.flags = flags;
  17822. // A list of var-declared names in the current lexical scope
  17823. this.var = [];
  17824. // A list of lexically-declared names in the current lexical scope
  17825. this.lexical = [];
  17826. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  17827. this.functions = [];
  17828. // A switch to disallow the identifier reference 'arguments'
  17829. this.inClassFieldInit = false;
  17830. };
  17831. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  17832. pp$3.enterScope = function(flags) {
  17833. this.scopeStack.push(new Scope(flags));
  17834. };
  17835. pp$3.exitScope = function() {
  17836. this.scopeStack.pop();
  17837. };
  17838. // The spec says:
  17839. // > At the top level of a function, or script, function declarations are
  17840. // > treated like var declarations rather than like lexical declarations.
  17841. pp$3.treatFunctionsAsVarInScope = function(scope) {
  17842. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  17843. };
  17844. pp$3.declareName = function(name, bindingType, pos) {
  17845. var redeclared = false;
  17846. if (bindingType === BIND_LEXICAL) {
  17847. var scope = this.currentScope();
  17848. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  17849. scope.lexical.push(name);
  17850. if (this.inModule && (scope.flags & SCOPE_TOP))
  17851. { delete this.undefinedExports[name]; }
  17852. } else if (bindingType === BIND_SIMPLE_CATCH) {
  17853. var scope$1 = this.currentScope();
  17854. scope$1.lexical.push(name);
  17855. } else if (bindingType === BIND_FUNCTION) {
  17856. var scope$2 = this.currentScope();
  17857. if (this.treatFunctionsAsVar)
  17858. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  17859. else
  17860. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  17861. scope$2.functions.push(name);
  17862. } else {
  17863. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  17864. var scope$3 = this.scopeStack[i];
  17865. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  17866. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  17867. redeclared = true;
  17868. break
  17869. }
  17870. scope$3.var.push(name);
  17871. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  17872. { delete this.undefinedExports[name]; }
  17873. if (scope$3.flags & SCOPE_VAR) { break }
  17874. }
  17875. }
  17876. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  17877. };
  17878. pp$3.checkLocalExport = function(id) {
  17879. // scope.functions must be empty as Module code is always strict.
  17880. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  17881. this.scopeStack[0].var.indexOf(id.name) === -1) {
  17882. this.undefinedExports[id.name] = id;
  17883. }
  17884. };
  17885. pp$3.currentScope = function() {
  17886. return this.scopeStack[this.scopeStack.length - 1]
  17887. };
  17888. pp$3.currentVarScope = function() {
  17889. for (var i = this.scopeStack.length - 1;; i--) {
  17890. var scope = this.scopeStack[i];
  17891. if (scope.flags & SCOPE_VAR) { return scope }
  17892. }
  17893. };
  17894. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  17895. pp$3.currentThisScope = function() {
  17896. for (var i = this.scopeStack.length - 1;; i--) {
  17897. var scope = this.scopeStack[i];
  17898. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  17899. }
  17900. };
  17901. var Node = function Node(parser, pos, loc) {
  17902. this.type = "";
  17903. this.start = pos;
  17904. this.end = 0;
  17905. if (parser.options.locations)
  17906. { this.loc = new SourceLocation(parser, loc); }
  17907. if (parser.options.directSourceFile)
  17908. { this.sourceFile = parser.options.directSourceFile; }
  17909. if (parser.options.ranges)
  17910. { this.range = [pos, 0]; }
  17911. };
  17912. // Start an AST node, attaching a start offset.
  17913. var pp$2 = Parser$1.prototype;
  17914. pp$2.startNode = function() {
  17915. return new Node(this, this.start, this.startLoc)
  17916. };
  17917. pp$2.startNodeAt = function(pos, loc) {
  17918. return new Node(this, pos, loc)
  17919. };
  17920. // Finish an AST node, adding `type` and `end` properties.
  17921. function finishNodeAt(node, type, pos, loc) {
  17922. node.type = type;
  17923. node.end = pos;
  17924. if (this.options.locations)
  17925. { node.loc.end = loc; }
  17926. if (this.options.ranges)
  17927. { node.range[1] = pos; }
  17928. return node
  17929. }
  17930. pp$2.finishNode = function(node, type) {
  17931. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  17932. };
  17933. // Finish node at given position
  17934. pp$2.finishNodeAt = function(node, type, pos, loc) {
  17935. return finishNodeAt.call(this, node, type, pos, loc)
  17936. };
  17937. pp$2.copyNode = function(node) {
  17938. var newNode = new Node(this, node.start, this.startLoc);
  17939. for (var prop in node) { newNode[prop] = node[prop]; }
  17940. return newNode
  17941. };
  17942. // This file contains Unicode properties extracted from the ECMAScript specification.
  17943. // The lists are extracted like so:
  17944. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  17945. // #table-binary-unicode-properties
  17946. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  17947. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  17948. var ecma11BinaryProperties = ecma10BinaryProperties;
  17949. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  17950. var ecma13BinaryProperties = ecma12BinaryProperties;
  17951. var ecma14BinaryProperties = ecma13BinaryProperties;
  17952. var unicodeBinaryProperties = {
  17953. 9: ecma9BinaryProperties,
  17954. 10: ecma10BinaryProperties,
  17955. 11: ecma11BinaryProperties,
  17956. 12: ecma12BinaryProperties,
  17957. 13: ecma13BinaryProperties,
  17958. 14: ecma14BinaryProperties
  17959. };
  17960. // #table-unicode-general-category-values
  17961. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  17962. // #table-unicode-script-values
  17963. var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  17964. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  17965. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  17966. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  17967. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  17968. var ecma14ScriptValues = ecma13ScriptValues + " Kawi Nag_Mundari Nagm";
  17969. var unicodeScriptValues = {
  17970. 9: ecma9ScriptValues,
  17971. 10: ecma10ScriptValues,
  17972. 11: ecma11ScriptValues,
  17973. 12: ecma12ScriptValues,
  17974. 13: ecma13ScriptValues,
  17975. 14: ecma14ScriptValues
  17976. };
  17977. var data = {};
  17978. function buildUnicodeData(ecmaVersion) {
  17979. var d = data[ecmaVersion] = {
  17980. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  17981. nonBinary: {
  17982. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  17983. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  17984. }
  17985. };
  17986. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  17987. d.nonBinary.gc = d.nonBinary.General_Category;
  17988. d.nonBinary.sc = d.nonBinary.Script;
  17989. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  17990. }
  17991. for (var i$1 = 0, list = [9, 10, 11, 12, 13, 14]; i$1 < list.length; i$1 += 1) {
  17992. var ecmaVersion = list[i$1];
  17993. buildUnicodeData(ecmaVersion);
  17994. }
  17995. var pp$1 = Parser$1.prototype;
  17996. var RegExpValidationState = function RegExpValidationState(parser) {
  17997. this.parser = parser;
  17998. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  17999. this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  18000. this.source = "";
  18001. this.flags = "";
  18002. this.start = 0;
  18003. this.switchU = false;
  18004. this.switchN = false;
  18005. this.pos = 0;
  18006. this.lastIntValue = 0;
  18007. this.lastStringValue = "";
  18008. this.lastAssertionIsQuantifiable = false;
  18009. this.numCapturingParens = 0;
  18010. this.maxBackReference = 0;
  18011. this.groupNames = [];
  18012. this.backReferenceNames = [];
  18013. };
  18014. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  18015. var unicode = flags.indexOf("u") !== -1;
  18016. this.start = start | 0;
  18017. this.source = pattern + "";
  18018. this.flags = flags;
  18019. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  18020. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  18021. };
  18022. RegExpValidationState.prototype.raise = function raise (message) {
  18023. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  18024. };
  18025. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  18026. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  18027. RegExpValidationState.prototype.at = function at (i, forceU) {
  18028. if ( forceU === void 0 ) forceU = false;
  18029. var s = this.source;
  18030. var l = s.length;
  18031. if (i >= l) {
  18032. return -1
  18033. }
  18034. var c = s.charCodeAt(i);
  18035. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  18036. return c
  18037. }
  18038. var next = s.charCodeAt(i + 1);
  18039. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  18040. };
  18041. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  18042. if ( forceU === void 0 ) forceU = false;
  18043. var s = this.source;
  18044. var l = s.length;
  18045. if (i >= l) {
  18046. return l
  18047. }
  18048. var c = s.charCodeAt(i), next;
  18049. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  18050. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  18051. return i + 1
  18052. }
  18053. return i + 2
  18054. };
  18055. RegExpValidationState.prototype.current = function current (forceU) {
  18056. if ( forceU === void 0 ) forceU = false;
  18057. return this.at(this.pos, forceU)
  18058. };
  18059. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  18060. if ( forceU === void 0 ) forceU = false;
  18061. return this.at(this.nextIndex(this.pos, forceU), forceU)
  18062. };
  18063. RegExpValidationState.prototype.advance = function advance (forceU) {
  18064. if ( forceU === void 0 ) forceU = false;
  18065. this.pos = this.nextIndex(this.pos, forceU);
  18066. };
  18067. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  18068. if ( forceU === void 0 ) forceU = false;
  18069. if (this.current(forceU) === ch) {
  18070. this.advance(forceU);
  18071. return true
  18072. }
  18073. return false
  18074. };
  18075. /**
  18076. * Validate the flags part of a given RegExpLiteral.
  18077. *
  18078. * @param {RegExpValidationState} state The state to validate RegExp.
  18079. * @returns {void}
  18080. */
  18081. pp$1.validateRegExpFlags = function(state) {
  18082. var validFlags = state.validFlags;
  18083. var flags = state.flags;
  18084. for (var i = 0; i < flags.length; i++) {
  18085. var flag = flags.charAt(i);
  18086. if (validFlags.indexOf(flag) === -1) {
  18087. this.raise(state.start, "Invalid regular expression flag");
  18088. }
  18089. if (flags.indexOf(flag, i + 1) > -1) {
  18090. this.raise(state.start, "Duplicate regular expression flag");
  18091. }
  18092. }
  18093. };
  18094. /**
  18095. * Validate the pattern part of a given RegExpLiteral.
  18096. *
  18097. * @param {RegExpValidationState} state The state to validate RegExp.
  18098. * @returns {void}
  18099. */
  18100. pp$1.validateRegExpPattern = function(state) {
  18101. this.regexp_pattern(state);
  18102. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  18103. // parsing contains a |GroupName|, reparse with the goal symbol
  18104. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  18105. // exception if _P_ did not conform to the grammar, if any elements of _P_
  18106. // were not matched by the parse, or if any Early Error conditions exist.
  18107. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  18108. state.switchN = true;
  18109. this.regexp_pattern(state);
  18110. }
  18111. };
  18112. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  18113. pp$1.regexp_pattern = function(state) {
  18114. state.pos = 0;
  18115. state.lastIntValue = 0;
  18116. state.lastStringValue = "";
  18117. state.lastAssertionIsQuantifiable = false;
  18118. state.numCapturingParens = 0;
  18119. state.maxBackReference = 0;
  18120. state.groupNames.length = 0;
  18121. state.backReferenceNames.length = 0;
  18122. this.regexp_disjunction(state);
  18123. if (state.pos !== state.source.length) {
  18124. // Make the same messages as V8.
  18125. if (state.eat(0x29 /* ) */)) {
  18126. state.raise("Unmatched ')'");
  18127. }
  18128. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  18129. state.raise("Lone quantifier brackets");
  18130. }
  18131. }
  18132. if (state.maxBackReference > state.numCapturingParens) {
  18133. state.raise("Invalid escape");
  18134. }
  18135. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  18136. var name = list[i];
  18137. if (state.groupNames.indexOf(name) === -1) {
  18138. state.raise("Invalid named capture referenced");
  18139. }
  18140. }
  18141. };
  18142. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  18143. pp$1.regexp_disjunction = function(state) {
  18144. this.regexp_alternative(state);
  18145. while (state.eat(0x7C /* | */)) {
  18146. this.regexp_alternative(state);
  18147. }
  18148. // Make the same message as V8.
  18149. if (this.regexp_eatQuantifier(state, true)) {
  18150. state.raise("Nothing to repeat");
  18151. }
  18152. if (state.eat(0x7B /* { */)) {
  18153. state.raise("Lone quantifier brackets");
  18154. }
  18155. };
  18156. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  18157. pp$1.regexp_alternative = function(state) {
  18158. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  18159. { }
  18160. };
  18161. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  18162. pp$1.regexp_eatTerm = function(state) {
  18163. if (this.regexp_eatAssertion(state)) {
  18164. // Handle `QuantifiableAssertion Quantifier` alternative.
  18165. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  18166. // is a QuantifiableAssertion.
  18167. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  18168. // Make the same message as V8.
  18169. if (state.switchU) {
  18170. state.raise("Invalid quantifier");
  18171. }
  18172. }
  18173. return true
  18174. }
  18175. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  18176. this.regexp_eatQuantifier(state);
  18177. return true
  18178. }
  18179. return false
  18180. };
  18181. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  18182. pp$1.regexp_eatAssertion = function(state) {
  18183. var start = state.pos;
  18184. state.lastAssertionIsQuantifiable = false;
  18185. // ^, $
  18186. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  18187. return true
  18188. }
  18189. // \b \B
  18190. if (state.eat(0x5C /* \ */)) {
  18191. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  18192. return true
  18193. }
  18194. state.pos = start;
  18195. }
  18196. // Lookahead / Lookbehind
  18197. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  18198. var lookbehind = false;
  18199. if (this.options.ecmaVersion >= 9) {
  18200. lookbehind = state.eat(0x3C /* < */);
  18201. }
  18202. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  18203. this.regexp_disjunction(state);
  18204. if (!state.eat(0x29 /* ) */)) {
  18205. state.raise("Unterminated group");
  18206. }
  18207. state.lastAssertionIsQuantifiable = !lookbehind;
  18208. return true
  18209. }
  18210. }
  18211. state.pos = start;
  18212. return false
  18213. };
  18214. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  18215. pp$1.regexp_eatQuantifier = function(state, noError) {
  18216. if ( noError === void 0 ) noError = false;
  18217. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  18218. state.eat(0x3F /* ? */);
  18219. return true
  18220. }
  18221. return false
  18222. };
  18223. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  18224. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  18225. return (
  18226. state.eat(0x2A /* * */) ||
  18227. state.eat(0x2B /* + */) ||
  18228. state.eat(0x3F /* ? */) ||
  18229. this.regexp_eatBracedQuantifier(state, noError)
  18230. )
  18231. };
  18232. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  18233. var start = state.pos;
  18234. if (state.eat(0x7B /* { */)) {
  18235. var min = 0, max = -1;
  18236. if (this.regexp_eatDecimalDigits(state)) {
  18237. min = state.lastIntValue;
  18238. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  18239. max = state.lastIntValue;
  18240. }
  18241. if (state.eat(0x7D /* } */)) {
  18242. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  18243. if (max !== -1 && max < min && !noError) {
  18244. state.raise("numbers out of order in {} quantifier");
  18245. }
  18246. return true
  18247. }
  18248. }
  18249. if (state.switchU && !noError) {
  18250. state.raise("Incomplete quantifier");
  18251. }
  18252. state.pos = start;
  18253. }
  18254. return false
  18255. };
  18256. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  18257. pp$1.regexp_eatAtom = function(state) {
  18258. return (
  18259. this.regexp_eatPatternCharacters(state) ||
  18260. state.eat(0x2E /* . */) ||
  18261. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18262. this.regexp_eatCharacterClass(state) ||
  18263. this.regexp_eatUncapturingGroup(state) ||
  18264. this.regexp_eatCapturingGroup(state)
  18265. )
  18266. };
  18267. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  18268. var start = state.pos;
  18269. if (state.eat(0x5C /* \ */)) {
  18270. if (this.regexp_eatAtomEscape(state)) {
  18271. return true
  18272. }
  18273. state.pos = start;
  18274. }
  18275. return false
  18276. };
  18277. pp$1.regexp_eatUncapturingGroup = function(state) {
  18278. var start = state.pos;
  18279. if (state.eat(0x28 /* ( */)) {
  18280. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  18281. this.regexp_disjunction(state);
  18282. if (state.eat(0x29 /* ) */)) {
  18283. return true
  18284. }
  18285. state.raise("Unterminated group");
  18286. }
  18287. state.pos = start;
  18288. }
  18289. return false
  18290. };
  18291. pp$1.regexp_eatCapturingGroup = function(state) {
  18292. if (state.eat(0x28 /* ( */)) {
  18293. if (this.options.ecmaVersion >= 9) {
  18294. this.regexp_groupSpecifier(state);
  18295. } else if (state.current() === 0x3F /* ? */) {
  18296. state.raise("Invalid group");
  18297. }
  18298. this.regexp_disjunction(state);
  18299. if (state.eat(0x29 /* ) */)) {
  18300. state.numCapturingParens += 1;
  18301. return true
  18302. }
  18303. state.raise("Unterminated group");
  18304. }
  18305. return false
  18306. };
  18307. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  18308. pp$1.regexp_eatExtendedAtom = function(state) {
  18309. return (
  18310. state.eat(0x2E /* . */) ||
  18311. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18312. this.regexp_eatCharacterClass(state) ||
  18313. this.regexp_eatUncapturingGroup(state) ||
  18314. this.regexp_eatCapturingGroup(state) ||
  18315. this.regexp_eatInvalidBracedQuantifier(state) ||
  18316. this.regexp_eatExtendedPatternCharacter(state)
  18317. )
  18318. };
  18319. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  18320. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  18321. if (this.regexp_eatBracedQuantifier(state, true)) {
  18322. state.raise("Nothing to repeat");
  18323. }
  18324. return false
  18325. };
  18326. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  18327. pp$1.regexp_eatSyntaxCharacter = function(state) {
  18328. var ch = state.current();
  18329. if (isSyntaxCharacter(ch)) {
  18330. state.lastIntValue = ch;
  18331. state.advance();
  18332. return true
  18333. }
  18334. return false
  18335. };
  18336. function isSyntaxCharacter(ch) {
  18337. return (
  18338. ch === 0x24 /* $ */ ||
  18339. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  18340. ch === 0x2E /* . */ ||
  18341. ch === 0x3F /* ? */ ||
  18342. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  18343. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  18344. )
  18345. }
  18346. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  18347. // But eat eager.
  18348. pp$1.regexp_eatPatternCharacters = function(state) {
  18349. var start = state.pos;
  18350. var ch = 0;
  18351. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  18352. state.advance();
  18353. }
  18354. return state.pos !== start
  18355. };
  18356. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  18357. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  18358. var ch = state.current();
  18359. if (
  18360. ch !== -1 &&
  18361. ch !== 0x24 /* $ */ &&
  18362. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  18363. ch !== 0x2E /* . */ &&
  18364. ch !== 0x3F /* ? */ &&
  18365. ch !== 0x5B /* [ */ &&
  18366. ch !== 0x5E /* ^ */ &&
  18367. ch !== 0x7C /* | */
  18368. ) {
  18369. state.advance();
  18370. return true
  18371. }
  18372. return false
  18373. };
  18374. // GroupSpecifier ::
  18375. // [empty]
  18376. // `?` GroupName
  18377. pp$1.regexp_groupSpecifier = function(state) {
  18378. if (state.eat(0x3F /* ? */)) {
  18379. if (this.regexp_eatGroupName(state)) {
  18380. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  18381. state.raise("Duplicate capture group name");
  18382. }
  18383. state.groupNames.push(state.lastStringValue);
  18384. return
  18385. }
  18386. state.raise("Invalid group");
  18387. }
  18388. };
  18389. // GroupName ::
  18390. // `<` RegExpIdentifierName `>`
  18391. // Note: this updates `state.lastStringValue` property with the eaten name.
  18392. pp$1.regexp_eatGroupName = function(state) {
  18393. state.lastStringValue = "";
  18394. if (state.eat(0x3C /* < */)) {
  18395. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  18396. return true
  18397. }
  18398. state.raise("Invalid capture group name");
  18399. }
  18400. return false
  18401. };
  18402. // RegExpIdentifierName ::
  18403. // RegExpIdentifierStart
  18404. // RegExpIdentifierName RegExpIdentifierPart
  18405. // Note: this updates `state.lastStringValue` property with the eaten name.
  18406. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  18407. state.lastStringValue = "";
  18408. if (this.regexp_eatRegExpIdentifierStart(state)) {
  18409. state.lastStringValue += codePointToString(state.lastIntValue);
  18410. while (this.regexp_eatRegExpIdentifierPart(state)) {
  18411. state.lastStringValue += codePointToString(state.lastIntValue);
  18412. }
  18413. return true
  18414. }
  18415. return false
  18416. };
  18417. // RegExpIdentifierStart ::
  18418. // UnicodeIDStart
  18419. // `$`
  18420. // `_`
  18421. // `\` RegExpUnicodeEscapeSequence[+U]
  18422. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  18423. var start = state.pos;
  18424. var forceU = this.options.ecmaVersion >= 11;
  18425. var ch = state.current(forceU);
  18426. state.advance(forceU);
  18427. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18428. ch = state.lastIntValue;
  18429. }
  18430. if (isRegExpIdentifierStart(ch)) {
  18431. state.lastIntValue = ch;
  18432. return true
  18433. }
  18434. state.pos = start;
  18435. return false
  18436. };
  18437. function isRegExpIdentifierStart(ch) {
  18438. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  18439. }
  18440. // RegExpIdentifierPart ::
  18441. // UnicodeIDContinue
  18442. // `$`
  18443. // `_`
  18444. // `\` RegExpUnicodeEscapeSequence[+U]
  18445. // <ZWNJ>
  18446. // <ZWJ>
  18447. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  18448. var start = state.pos;
  18449. var forceU = this.options.ecmaVersion >= 11;
  18450. var ch = state.current(forceU);
  18451. state.advance(forceU);
  18452. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18453. ch = state.lastIntValue;
  18454. }
  18455. if (isRegExpIdentifierPart(ch)) {
  18456. state.lastIntValue = ch;
  18457. return true
  18458. }
  18459. state.pos = start;
  18460. return false
  18461. };
  18462. function isRegExpIdentifierPart(ch) {
  18463. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  18464. }
  18465. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  18466. pp$1.regexp_eatAtomEscape = function(state) {
  18467. if (
  18468. this.regexp_eatBackReference(state) ||
  18469. this.regexp_eatCharacterClassEscape(state) ||
  18470. this.regexp_eatCharacterEscape(state) ||
  18471. (state.switchN && this.regexp_eatKGroupName(state))
  18472. ) {
  18473. return true
  18474. }
  18475. if (state.switchU) {
  18476. // Make the same message as V8.
  18477. if (state.current() === 0x63 /* c */) {
  18478. state.raise("Invalid unicode escape");
  18479. }
  18480. state.raise("Invalid escape");
  18481. }
  18482. return false
  18483. };
  18484. pp$1.regexp_eatBackReference = function(state) {
  18485. var start = state.pos;
  18486. if (this.regexp_eatDecimalEscape(state)) {
  18487. var n = state.lastIntValue;
  18488. if (state.switchU) {
  18489. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  18490. if (n > state.maxBackReference) {
  18491. state.maxBackReference = n;
  18492. }
  18493. return true
  18494. }
  18495. if (n <= state.numCapturingParens) {
  18496. return true
  18497. }
  18498. state.pos = start;
  18499. }
  18500. return false
  18501. };
  18502. pp$1.regexp_eatKGroupName = function(state) {
  18503. if (state.eat(0x6B /* k */)) {
  18504. if (this.regexp_eatGroupName(state)) {
  18505. state.backReferenceNames.push(state.lastStringValue);
  18506. return true
  18507. }
  18508. state.raise("Invalid named reference");
  18509. }
  18510. return false
  18511. };
  18512. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  18513. pp$1.regexp_eatCharacterEscape = function(state) {
  18514. return (
  18515. this.regexp_eatControlEscape(state) ||
  18516. this.regexp_eatCControlLetter(state) ||
  18517. this.regexp_eatZero(state) ||
  18518. this.regexp_eatHexEscapeSequence(state) ||
  18519. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  18520. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  18521. this.regexp_eatIdentityEscape(state)
  18522. )
  18523. };
  18524. pp$1.regexp_eatCControlLetter = function(state) {
  18525. var start = state.pos;
  18526. if (state.eat(0x63 /* c */)) {
  18527. if (this.regexp_eatControlLetter(state)) {
  18528. return true
  18529. }
  18530. state.pos = start;
  18531. }
  18532. return false
  18533. };
  18534. pp$1.regexp_eatZero = function(state) {
  18535. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  18536. state.lastIntValue = 0;
  18537. state.advance();
  18538. return true
  18539. }
  18540. return false
  18541. };
  18542. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  18543. pp$1.regexp_eatControlEscape = function(state) {
  18544. var ch = state.current();
  18545. if (ch === 0x74 /* t */) {
  18546. state.lastIntValue = 0x09; /* \t */
  18547. state.advance();
  18548. return true
  18549. }
  18550. if (ch === 0x6E /* n */) {
  18551. state.lastIntValue = 0x0A; /* \n */
  18552. state.advance();
  18553. return true
  18554. }
  18555. if (ch === 0x76 /* v */) {
  18556. state.lastIntValue = 0x0B; /* \v */
  18557. state.advance();
  18558. return true
  18559. }
  18560. if (ch === 0x66 /* f */) {
  18561. state.lastIntValue = 0x0C; /* \f */
  18562. state.advance();
  18563. return true
  18564. }
  18565. if (ch === 0x72 /* r */) {
  18566. state.lastIntValue = 0x0D; /* \r */
  18567. state.advance();
  18568. return true
  18569. }
  18570. return false
  18571. };
  18572. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  18573. pp$1.regexp_eatControlLetter = function(state) {
  18574. var ch = state.current();
  18575. if (isControlLetter(ch)) {
  18576. state.lastIntValue = ch % 0x20;
  18577. state.advance();
  18578. return true
  18579. }
  18580. return false
  18581. };
  18582. function isControlLetter(ch) {
  18583. return (
  18584. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  18585. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  18586. )
  18587. }
  18588. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  18589. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  18590. if ( forceU === void 0 ) forceU = false;
  18591. var start = state.pos;
  18592. var switchU = forceU || state.switchU;
  18593. if (state.eat(0x75 /* u */)) {
  18594. if (this.regexp_eatFixedHexDigits(state, 4)) {
  18595. var lead = state.lastIntValue;
  18596. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  18597. var leadSurrogateEnd = state.pos;
  18598. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  18599. var trail = state.lastIntValue;
  18600. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  18601. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  18602. return true
  18603. }
  18604. }
  18605. state.pos = leadSurrogateEnd;
  18606. state.lastIntValue = lead;
  18607. }
  18608. return true
  18609. }
  18610. if (
  18611. switchU &&
  18612. state.eat(0x7B /* { */) &&
  18613. this.regexp_eatHexDigits(state) &&
  18614. state.eat(0x7D /* } */) &&
  18615. isValidUnicode(state.lastIntValue)
  18616. ) {
  18617. return true
  18618. }
  18619. if (switchU) {
  18620. state.raise("Invalid unicode escape");
  18621. }
  18622. state.pos = start;
  18623. }
  18624. return false
  18625. };
  18626. function isValidUnicode(ch) {
  18627. return ch >= 0 && ch <= 0x10FFFF
  18628. }
  18629. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  18630. pp$1.regexp_eatIdentityEscape = function(state) {
  18631. if (state.switchU) {
  18632. if (this.regexp_eatSyntaxCharacter(state)) {
  18633. return true
  18634. }
  18635. if (state.eat(0x2F /* / */)) {
  18636. state.lastIntValue = 0x2F; /* / */
  18637. return true
  18638. }
  18639. return false
  18640. }
  18641. var ch = state.current();
  18642. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  18643. state.lastIntValue = ch;
  18644. state.advance();
  18645. return true
  18646. }
  18647. return false
  18648. };
  18649. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  18650. pp$1.regexp_eatDecimalEscape = function(state) {
  18651. state.lastIntValue = 0;
  18652. var ch = state.current();
  18653. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  18654. do {
  18655. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  18656. state.advance();
  18657. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  18658. return true
  18659. }
  18660. return false
  18661. };
  18662. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  18663. pp$1.regexp_eatCharacterClassEscape = function(state) {
  18664. var ch = state.current();
  18665. if (isCharacterClassEscape(ch)) {
  18666. state.lastIntValue = -1;
  18667. state.advance();
  18668. return true
  18669. }
  18670. if (
  18671. state.switchU &&
  18672. this.options.ecmaVersion >= 9 &&
  18673. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  18674. ) {
  18675. state.lastIntValue = -1;
  18676. state.advance();
  18677. if (
  18678. state.eat(0x7B /* { */) &&
  18679. this.regexp_eatUnicodePropertyValueExpression(state) &&
  18680. state.eat(0x7D /* } */)
  18681. ) {
  18682. return true
  18683. }
  18684. state.raise("Invalid property name");
  18685. }
  18686. return false
  18687. };
  18688. function isCharacterClassEscape(ch) {
  18689. return (
  18690. ch === 0x64 /* d */ ||
  18691. ch === 0x44 /* D */ ||
  18692. ch === 0x73 /* s */ ||
  18693. ch === 0x53 /* S */ ||
  18694. ch === 0x77 /* w */ ||
  18695. ch === 0x57 /* W */
  18696. )
  18697. }
  18698. // UnicodePropertyValueExpression ::
  18699. // UnicodePropertyName `=` UnicodePropertyValue
  18700. // LoneUnicodePropertyNameOrValue
  18701. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  18702. var start = state.pos;
  18703. // UnicodePropertyName `=` UnicodePropertyValue
  18704. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  18705. var name = state.lastStringValue;
  18706. if (this.regexp_eatUnicodePropertyValue(state)) {
  18707. var value = state.lastStringValue;
  18708. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  18709. return true
  18710. }
  18711. }
  18712. state.pos = start;
  18713. // LoneUnicodePropertyNameOrValue
  18714. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  18715. var nameOrValue = state.lastStringValue;
  18716. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  18717. return true
  18718. }
  18719. return false
  18720. };
  18721. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  18722. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  18723. { state.raise("Invalid property name"); }
  18724. if (!state.unicodeProperties.nonBinary[name].test(value))
  18725. { state.raise("Invalid property value"); }
  18726. };
  18727. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  18728. if (!state.unicodeProperties.binary.test(nameOrValue))
  18729. { state.raise("Invalid property name"); }
  18730. };
  18731. // UnicodePropertyName ::
  18732. // UnicodePropertyNameCharacters
  18733. pp$1.regexp_eatUnicodePropertyName = function(state) {
  18734. var ch = 0;
  18735. state.lastStringValue = "";
  18736. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  18737. state.lastStringValue += codePointToString(ch);
  18738. state.advance();
  18739. }
  18740. return state.lastStringValue !== ""
  18741. };
  18742. function isUnicodePropertyNameCharacter(ch) {
  18743. return isControlLetter(ch) || ch === 0x5F /* _ */
  18744. }
  18745. // UnicodePropertyValue ::
  18746. // UnicodePropertyValueCharacters
  18747. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  18748. var ch = 0;
  18749. state.lastStringValue = "";
  18750. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  18751. state.lastStringValue += codePointToString(ch);
  18752. state.advance();
  18753. }
  18754. return state.lastStringValue !== ""
  18755. };
  18756. function isUnicodePropertyValueCharacter(ch) {
  18757. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  18758. }
  18759. // LoneUnicodePropertyNameOrValue ::
  18760. // UnicodePropertyValueCharacters
  18761. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  18762. return this.regexp_eatUnicodePropertyValue(state)
  18763. };
  18764. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  18765. pp$1.regexp_eatCharacterClass = function(state) {
  18766. if (state.eat(0x5B /* [ */)) {
  18767. state.eat(0x5E /* ^ */);
  18768. this.regexp_classRanges(state);
  18769. if (state.eat(0x5D /* ] */)) {
  18770. return true
  18771. }
  18772. // Unreachable since it threw "unterminated regular expression" error before.
  18773. state.raise("Unterminated character class");
  18774. }
  18775. return false
  18776. };
  18777. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  18778. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  18779. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  18780. pp$1.regexp_classRanges = function(state) {
  18781. while (this.regexp_eatClassAtom(state)) {
  18782. var left = state.lastIntValue;
  18783. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  18784. var right = state.lastIntValue;
  18785. if (state.switchU && (left === -1 || right === -1)) {
  18786. state.raise("Invalid character class");
  18787. }
  18788. if (left !== -1 && right !== -1 && left > right) {
  18789. state.raise("Range out of order in character class");
  18790. }
  18791. }
  18792. }
  18793. };
  18794. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  18795. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  18796. pp$1.regexp_eatClassAtom = function(state) {
  18797. var start = state.pos;
  18798. if (state.eat(0x5C /* \ */)) {
  18799. if (this.regexp_eatClassEscape(state)) {
  18800. return true
  18801. }
  18802. if (state.switchU) {
  18803. // Make the same message as V8.
  18804. var ch$1 = state.current();
  18805. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  18806. state.raise("Invalid class escape");
  18807. }
  18808. state.raise("Invalid escape");
  18809. }
  18810. state.pos = start;
  18811. }
  18812. var ch = state.current();
  18813. if (ch !== 0x5D /* ] */) {
  18814. state.lastIntValue = ch;
  18815. state.advance();
  18816. return true
  18817. }
  18818. return false
  18819. };
  18820. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  18821. pp$1.regexp_eatClassEscape = function(state) {
  18822. var start = state.pos;
  18823. if (state.eat(0x62 /* b */)) {
  18824. state.lastIntValue = 0x08; /* <BS> */
  18825. return true
  18826. }
  18827. if (state.switchU && state.eat(0x2D /* - */)) {
  18828. state.lastIntValue = 0x2D; /* - */
  18829. return true
  18830. }
  18831. if (!state.switchU && state.eat(0x63 /* c */)) {
  18832. if (this.regexp_eatClassControlLetter(state)) {
  18833. return true
  18834. }
  18835. state.pos = start;
  18836. }
  18837. return (
  18838. this.regexp_eatCharacterClassEscape(state) ||
  18839. this.regexp_eatCharacterEscape(state)
  18840. )
  18841. };
  18842. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  18843. pp$1.regexp_eatClassControlLetter = function(state) {
  18844. var ch = state.current();
  18845. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  18846. state.lastIntValue = ch % 0x20;
  18847. state.advance();
  18848. return true
  18849. }
  18850. return false
  18851. };
  18852. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  18853. pp$1.regexp_eatHexEscapeSequence = function(state) {
  18854. var start = state.pos;
  18855. if (state.eat(0x78 /* x */)) {
  18856. if (this.regexp_eatFixedHexDigits(state, 2)) {
  18857. return true
  18858. }
  18859. if (state.switchU) {
  18860. state.raise("Invalid escape");
  18861. }
  18862. state.pos = start;
  18863. }
  18864. return false
  18865. };
  18866. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  18867. pp$1.regexp_eatDecimalDigits = function(state) {
  18868. var start = state.pos;
  18869. var ch = 0;
  18870. state.lastIntValue = 0;
  18871. while (isDecimalDigit(ch = state.current())) {
  18872. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  18873. state.advance();
  18874. }
  18875. return state.pos !== start
  18876. };
  18877. function isDecimalDigit(ch) {
  18878. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  18879. }
  18880. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  18881. pp$1.regexp_eatHexDigits = function(state) {
  18882. var start = state.pos;
  18883. var ch = 0;
  18884. state.lastIntValue = 0;
  18885. while (isHexDigit(ch = state.current())) {
  18886. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  18887. state.advance();
  18888. }
  18889. return state.pos !== start
  18890. };
  18891. function isHexDigit(ch) {
  18892. return (
  18893. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  18894. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  18895. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  18896. )
  18897. }
  18898. function hexToInt(ch) {
  18899. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  18900. return 10 + (ch - 0x41 /* A */)
  18901. }
  18902. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  18903. return 10 + (ch - 0x61 /* a */)
  18904. }
  18905. return ch - 0x30 /* 0 */
  18906. }
  18907. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  18908. // Allows only 0-377(octal) i.e. 0-255(decimal).
  18909. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  18910. if (this.regexp_eatOctalDigit(state)) {
  18911. var n1 = state.lastIntValue;
  18912. if (this.regexp_eatOctalDigit(state)) {
  18913. var n2 = state.lastIntValue;
  18914. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  18915. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  18916. } else {
  18917. state.lastIntValue = n1 * 8 + n2;
  18918. }
  18919. } else {
  18920. state.lastIntValue = n1;
  18921. }
  18922. return true
  18923. }
  18924. return false
  18925. };
  18926. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  18927. pp$1.regexp_eatOctalDigit = function(state) {
  18928. var ch = state.current();
  18929. if (isOctalDigit(ch)) {
  18930. state.lastIntValue = ch - 0x30; /* 0 */
  18931. state.advance();
  18932. return true
  18933. }
  18934. state.lastIntValue = 0;
  18935. return false
  18936. };
  18937. function isOctalDigit(ch) {
  18938. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  18939. }
  18940. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  18941. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  18942. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  18943. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  18944. var start = state.pos;
  18945. state.lastIntValue = 0;
  18946. for (var i = 0; i < length; ++i) {
  18947. var ch = state.current();
  18948. if (!isHexDigit(ch)) {
  18949. state.pos = start;
  18950. return false
  18951. }
  18952. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  18953. state.advance();
  18954. }
  18955. return true
  18956. };
  18957. // Object type used to represent tokens. Note that normally, tokens
  18958. // simply exist as properties on the parser object. This is only
  18959. // used for the onToken callback and the external tokenizer.
  18960. var Token = function Token(p) {
  18961. this.type = p.type;
  18962. this.value = p.value;
  18963. this.start = p.start;
  18964. this.end = p.end;
  18965. if (p.options.locations)
  18966. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  18967. if (p.options.ranges)
  18968. { this.range = [p.start, p.end]; }
  18969. };
  18970. // ## Tokenizer
  18971. var pp = Parser$1.prototype;
  18972. // Move to the next token
  18973. pp.next = function(ignoreEscapeSequenceInKeyword) {
  18974. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  18975. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  18976. if (this.options.onToken)
  18977. { this.options.onToken(new Token(this)); }
  18978. this.lastTokEnd = this.end;
  18979. this.lastTokStart = this.start;
  18980. this.lastTokEndLoc = this.endLoc;
  18981. this.lastTokStartLoc = this.startLoc;
  18982. this.nextToken();
  18983. };
  18984. pp.getToken = function() {
  18985. this.next();
  18986. return new Token(this)
  18987. };
  18988. // If we're in an ES6 environment, make parsers iterable
  18989. if (typeof Symbol !== "undefined")
  18990. { pp[Symbol.iterator] = function() {
  18991. var this$1$1 = this;
  18992. return {
  18993. next: function () {
  18994. var token = this$1$1.getToken();
  18995. return {
  18996. done: token.type === types$1.eof,
  18997. value: token
  18998. }
  18999. }
  19000. }
  19001. }; }
  19002. // Toggle strict mode. Re-reads the next number or string to please
  19003. // pedantic tests (`"use strict"; 010;` should fail).
  19004. // Read a single token, updating the parser object's token-related
  19005. // properties.
  19006. pp.nextToken = function() {
  19007. var curContext = this.curContext();
  19008. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  19009. this.start = this.pos;
  19010. if (this.options.locations) { this.startLoc = this.curPosition(); }
  19011. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  19012. if (curContext.override) { return curContext.override(this) }
  19013. else { this.readToken(this.fullCharCodeAtPos()); }
  19014. };
  19015. pp.readToken = function(code) {
  19016. // Identifier or keyword. '\uXXXX' sequences are allowed in
  19017. // identifiers, so '\' also dispatches to that.
  19018. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  19019. { return this.readWord() }
  19020. return this.getTokenFromCode(code)
  19021. };
  19022. pp.fullCharCodeAtPos = function() {
  19023. var code = this.input.charCodeAt(this.pos);
  19024. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  19025. var next = this.input.charCodeAt(this.pos + 1);
  19026. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  19027. };
  19028. pp.skipBlockComment = function() {
  19029. var startLoc = this.options.onComment && this.curPosition();
  19030. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  19031. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  19032. this.pos = end + 2;
  19033. if (this.options.locations) {
  19034. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  19035. ++this.curLine;
  19036. pos = this.lineStart = nextBreak;
  19037. }
  19038. }
  19039. if (this.options.onComment)
  19040. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  19041. startLoc, this.curPosition()); }
  19042. };
  19043. pp.skipLineComment = function(startSkip) {
  19044. var start = this.pos;
  19045. var startLoc = this.options.onComment && this.curPosition();
  19046. var ch = this.input.charCodeAt(this.pos += startSkip);
  19047. while (this.pos < this.input.length && !isNewLine(ch)) {
  19048. ch = this.input.charCodeAt(++this.pos);
  19049. }
  19050. if (this.options.onComment)
  19051. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  19052. startLoc, this.curPosition()); }
  19053. };
  19054. // Called at the start of the parse and after every token. Skips
  19055. // whitespace and comments, and.
  19056. pp.skipSpace = function() {
  19057. loop: while (this.pos < this.input.length) {
  19058. var ch = this.input.charCodeAt(this.pos);
  19059. switch (ch) {
  19060. case 32: case 160: // ' '
  19061. ++this.pos;
  19062. break
  19063. case 13:
  19064. if (this.input.charCodeAt(this.pos + 1) === 10) {
  19065. ++this.pos;
  19066. }
  19067. case 10: case 8232: case 8233:
  19068. ++this.pos;
  19069. if (this.options.locations) {
  19070. ++this.curLine;
  19071. this.lineStart = this.pos;
  19072. }
  19073. break
  19074. case 47: // '/'
  19075. switch (this.input.charCodeAt(this.pos + 1)) {
  19076. case 42: // '*'
  19077. this.skipBlockComment();
  19078. break
  19079. case 47:
  19080. this.skipLineComment(2);
  19081. break
  19082. default:
  19083. break loop
  19084. }
  19085. break
  19086. default:
  19087. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  19088. ++this.pos;
  19089. } else {
  19090. break loop
  19091. }
  19092. }
  19093. }
  19094. };
  19095. // Called at the end of every token. Sets `end`, `val`, and
  19096. // maintains `context` and `exprAllowed`, and skips the space after
  19097. // the token, so that the next one's `start` will point at the
  19098. // right position.
  19099. pp.finishToken = function(type, val) {
  19100. this.end = this.pos;
  19101. if (this.options.locations) { this.endLoc = this.curPosition(); }
  19102. var prevType = this.type;
  19103. this.type = type;
  19104. this.value = val;
  19105. this.updateContext(prevType);
  19106. };
  19107. // ### Token reading
  19108. // This is the function that is called to fetch the next token. It
  19109. // is somewhat obscure, because it works in character codes rather
  19110. // than characters, and because operator parsing has been inlined
  19111. // into it.
  19112. //
  19113. // All in the name of speed.
  19114. //
  19115. pp.readToken_dot = function() {
  19116. var next = this.input.charCodeAt(this.pos + 1);
  19117. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  19118. var next2 = this.input.charCodeAt(this.pos + 2);
  19119. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  19120. this.pos += 3;
  19121. return this.finishToken(types$1.ellipsis)
  19122. } else {
  19123. ++this.pos;
  19124. return this.finishToken(types$1.dot)
  19125. }
  19126. };
  19127. pp.readToken_slash = function() { // '/'
  19128. var next = this.input.charCodeAt(this.pos + 1);
  19129. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  19130. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19131. return this.finishOp(types$1.slash, 1)
  19132. };
  19133. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  19134. var next = this.input.charCodeAt(this.pos + 1);
  19135. var size = 1;
  19136. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  19137. // exponentiation operator ** and **=
  19138. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  19139. ++size;
  19140. tokentype = types$1.starstar;
  19141. next = this.input.charCodeAt(this.pos + 2);
  19142. }
  19143. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  19144. return this.finishOp(tokentype, size)
  19145. };
  19146. pp.readToken_pipe_amp = function(code) { // '|&'
  19147. var next = this.input.charCodeAt(this.pos + 1);
  19148. if (next === code) {
  19149. if (this.options.ecmaVersion >= 12) {
  19150. var next2 = this.input.charCodeAt(this.pos + 2);
  19151. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  19152. }
  19153. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  19154. }
  19155. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19156. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  19157. };
  19158. pp.readToken_caret = function() { // '^'
  19159. var next = this.input.charCodeAt(this.pos + 1);
  19160. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19161. return this.finishOp(types$1.bitwiseXOR, 1)
  19162. };
  19163. pp.readToken_plus_min = function(code) { // '+-'
  19164. var next = this.input.charCodeAt(this.pos + 1);
  19165. if (next === code) {
  19166. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  19167. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  19168. // A `-->` line comment
  19169. this.skipLineComment(3);
  19170. this.skipSpace();
  19171. return this.nextToken()
  19172. }
  19173. return this.finishOp(types$1.incDec, 2)
  19174. }
  19175. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19176. return this.finishOp(types$1.plusMin, 1)
  19177. };
  19178. pp.readToken_lt_gt = function(code) { // '<>'
  19179. var next = this.input.charCodeAt(this.pos + 1);
  19180. var size = 1;
  19181. if (next === code) {
  19182. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  19183. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  19184. return this.finishOp(types$1.bitShift, size)
  19185. }
  19186. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  19187. this.input.charCodeAt(this.pos + 3) === 45) {
  19188. // `<!--`, an XML-style comment that should be interpreted as a line comment
  19189. this.skipLineComment(4);
  19190. this.skipSpace();
  19191. return this.nextToken()
  19192. }
  19193. if (next === 61) { size = 2; }
  19194. return this.finishOp(types$1.relational, size)
  19195. };
  19196. pp.readToken_eq_excl = function(code) { // '=!'
  19197. var next = this.input.charCodeAt(this.pos + 1);
  19198. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  19199. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  19200. this.pos += 2;
  19201. return this.finishToken(types$1.arrow)
  19202. }
  19203. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  19204. };
  19205. pp.readToken_question = function() { // '?'
  19206. var ecmaVersion = this.options.ecmaVersion;
  19207. if (ecmaVersion >= 11) {
  19208. var next = this.input.charCodeAt(this.pos + 1);
  19209. if (next === 46) {
  19210. var next2 = this.input.charCodeAt(this.pos + 2);
  19211. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  19212. }
  19213. if (next === 63) {
  19214. if (ecmaVersion >= 12) {
  19215. var next2$1 = this.input.charCodeAt(this.pos + 2);
  19216. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  19217. }
  19218. return this.finishOp(types$1.coalesce, 2)
  19219. }
  19220. }
  19221. return this.finishOp(types$1.question, 1)
  19222. };
  19223. pp.readToken_numberSign = function() { // '#'
  19224. var ecmaVersion = this.options.ecmaVersion;
  19225. var code = 35; // '#'
  19226. if (ecmaVersion >= 13) {
  19227. ++this.pos;
  19228. code = this.fullCharCodeAtPos();
  19229. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  19230. return this.finishToken(types$1.privateId, this.readWord1())
  19231. }
  19232. }
  19233. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19234. };
  19235. pp.getTokenFromCode = function(code) {
  19236. switch (code) {
  19237. // The interpretation of a dot depends on whether it is followed
  19238. // by a digit or another two dots.
  19239. case 46: // '.'
  19240. return this.readToken_dot()
  19241. // Punctuation tokens.
  19242. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  19243. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  19244. case 59: ++this.pos; return this.finishToken(types$1.semi)
  19245. case 44: ++this.pos; return this.finishToken(types$1.comma)
  19246. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  19247. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  19248. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  19249. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  19250. case 58: ++this.pos; return this.finishToken(types$1.colon)
  19251. case 96: // '`'
  19252. if (this.options.ecmaVersion < 6) { break }
  19253. ++this.pos;
  19254. return this.finishToken(types$1.backQuote)
  19255. case 48: // '0'
  19256. var next = this.input.charCodeAt(this.pos + 1);
  19257. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  19258. if (this.options.ecmaVersion >= 6) {
  19259. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  19260. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  19261. }
  19262. // Anything else beginning with a digit is an integer, octal
  19263. // number, or float.
  19264. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  19265. return this.readNumber(false)
  19266. // Quotes produce strings.
  19267. case 34: case 39: // '"', "'"
  19268. return this.readString(code)
  19269. // Operators are parsed inline in tiny state machines. '=' (61) is
  19270. // often referred to. `finishOp` simply skips the amount of
  19271. // characters it is given as second argument, and returns a token
  19272. // of the type given by its first argument.
  19273. case 47: // '/'
  19274. return this.readToken_slash()
  19275. case 37: case 42: // '%*'
  19276. return this.readToken_mult_modulo_exp(code)
  19277. case 124: case 38: // '|&'
  19278. return this.readToken_pipe_amp(code)
  19279. case 94: // '^'
  19280. return this.readToken_caret()
  19281. case 43: case 45: // '+-'
  19282. return this.readToken_plus_min(code)
  19283. case 60: case 62: // '<>'
  19284. return this.readToken_lt_gt(code)
  19285. case 61: case 33: // '=!'
  19286. return this.readToken_eq_excl(code)
  19287. case 63: // '?'
  19288. return this.readToken_question()
  19289. case 126: // '~'
  19290. return this.finishOp(types$1.prefix, 1)
  19291. case 35: // '#'
  19292. return this.readToken_numberSign()
  19293. }
  19294. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19295. };
  19296. pp.finishOp = function(type, size) {
  19297. var str = this.input.slice(this.pos, this.pos + size);
  19298. this.pos += size;
  19299. return this.finishToken(type, str)
  19300. };
  19301. pp.readRegexp = function() {
  19302. var escaped, inClass, start = this.pos;
  19303. for (;;) {
  19304. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  19305. var ch = this.input.charAt(this.pos);
  19306. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  19307. if (!escaped) {
  19308. if (ch === "[") { inClass = true; }
  19309. else if (ch === "]" && inClass) { inClass = false; }
  19310. else if (ch === "/" && !inClass) { break }
  19311. escaped = ch === "\\";
  19312. } else { escaped = false; }
  19313. ++this.pos;
  19314. }
  19315. var pattern = this.input.slice(start, this.pos);
  19316. ++this.pos;
  19317. var flagsStart = this.pos;
  19318. var flags = this.readWord1();
  19319. if (this.containsEsc) { this.unexpected(flagsStart); }
  19320. // Validate pattern
  19321. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  19322. state.reset(start, pattern, flags);
  19323. this.validateRegExpFlags(state);
  19324. this.validateRegExpPattern(state);
  19325. // Create Literal#value property value.
  19326. var value = null;
  19327. try {
  19328. value = new RegExp(pattern, flags);
  19329. } catch (e) {
  19330. // ESTree requires null if it failed to instantiate RegExp object.
  19331. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  19332. }
  19333. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  19334. };
  19335. // Read an integer in the given radix. Return null if zero digits
  19336. // were read, the integer value otherwise. When `len` is given, this
  19337. // will return `null` unless the integer has exactly `len` digits.
  19338. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  19339. // `len` is used for character escape sequences. In that case, disallow separators.
  19340. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  19341. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  19342. // and isn't fraction part nor exponent part. In that case, if the first digit
  19343. // is zero then disallow separators.
  19344. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  19345. var start = this.pos, total = 0, lastCode = 0;
  19346. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  19347. var code = this.input.charCodeAt(this.pos), val = (void 0);
  19348. if (allowSeparators && code === 95) {
  19349. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  19350. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  19351. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  19352. lastCode = code;
  19353. continue
  19354. }
  19355. if (code >= 97) { val = code - 97 + 10; } // a
  19356. else if (code >= 65) { val = code - 65 + 10; } // A
  19357. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  19358. else { val = Infinity; }
  19359. if (val >= radix) { break }
  19360. lastCode = code;
  19361. total = total * radix + val;
  19362. }
  19363. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  19364. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  19365. return total
  19366. };
  19367. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  19368. if (isLegacyOctalNumericLiteral) {
  19369. return parseInt(str, 8)
  19370. }
  19371. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  19372. return parseFloat(str.replace(/_/g, ""))
  19373. }
  19374. function stringToBigInt(str) {
  19375. if (typeof BigInt !== "function") {
  19376. return null
  19377. }
  19378. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  19379. return BigInt(str.replace(/_/g, ""))
  19380. }
  19381. pp.readRadixNumber = function(radix) {
  19382. var start = this.pos;
  19383. this.pos += 2; // 0x
  19384. var val = this.readInt(radix);
  19385. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  19386. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  19387. val = stringToBigInt(this.input.slice(start, this.pos));
  19388. ++this.pos;
  19389. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19390. return this.finishToken(types$1.num, val)
  19391. };
  19392. // Read an integer, octal integer, or floating-point number.
  19393. pp.readNumber = function(startsWithDot) {
  19394. var start = this.pos;
  19395. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  19396. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  19397. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  19398. var next = this.input.charCodeAt(this.pos);
  19399. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  19400. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  19401. ++this.pos;
  19402. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19403. return this.finishToken(types$1.num, val$1)
  19404. }
  19405. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  19406. if (next === 46 && !octal) { // '.'
  19407. ++this.pos;
  19408. this.readInt(10);
  19409. next = this.input.charCodeAt(this.pos);
  19410. }
  19411. if ((next === 69 || next === 101) && !octal) { // 'eE'
  19412. next = this.input.charCodeAt(++this.pos);
  19413. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  19414. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  19415. }
  19416. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19417. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  19418. return this.finishToken(types$1.num, val)
  19419. };
  19420. // Read a string value, interpreting backslash-escapes.
  19421. pp.readCodePoint = function() {
  19422. var ch = this.input.charCodeAt(this.pos), code;
  19423. if (ch === 123) { // '{'
  19424. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  19425. var codePos = ++this.pos;
  19426. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  19427. ++this.pos;
  19428. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  19429. } else {
  19430. code = this.readHexChar(4);
  19431. }
  19432. return code
  19433. };
  19434. pp.readString = function(quote) {
  19435. var out = "", chunkStart = ++this.pos;
  19436. for (;;) {
  19437. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  19438. var ch = this.input.charCodeAt(this.pos);
  19439. if (ch === quote) { break }
  19440. if (ch === 92) { // '\'
  19441. out += this.input.slice(chunkStart, this.pos);
  19442. out += this.readEscapedChar(false);
  19443. chunkStart = this.pos;
  19444. } else if (ch === 0x2028 || ch === 0x2029) {
  19445. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  19446. ++this.pos;
  19447. if (this.options.locations) {
  19448. this.curLine++;
  19449. this.lineStart = this.pos;
  19450. }
  19451. } else {
  19452. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  19453. ++this.pos;
  19454. }
  19455. }
  19456. out += this.input.slice(chunkStart, this.pos++);
  19457. return this.finishToken(types$1.string, out)
  19458. };
  19459. // Reads template string tokens.
  19460. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  19461. pp.tryReadTemplateToken = function() {
  19462. this.inTemplateElement = true;
  19463. try {
  19464. this.readTmplToken();
  19465. } catch (err) {
  19466. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  19467. this.readInvalidTemplateToken();
  19468. } else {
  19469. throw err
  19470. }
  19471. }
  19472. this.inTemplateElement = false;
  19473. };
  19474. pp.invalidStringToken = function(position, message) {
  19475. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  19476. throw INVALID_TEMPLATE_ESCAPE_ERROR
  19477. } else {
  19478. this.raise(position, message);
  19479. }
  19480. };
  19481. pp.readTmplToken = function() {
  19482. var out = "", chunkStart = this.pos;
  19483. for (;;) {
  19484. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  19485. var ch = this.input.charCodeAt(this.pos);
  19486. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  19487. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  19488. if (ch === 36) {
  19489. this.pos += 2;
  19490. return this.finishToken(types$1.dollarBraceL)
  19491. } else {
  19492. ++this.pos;
  19493. return this.finishToken(types$1.backQuote)
  19494. }
  19495. }
  19496. out += this.input.slice(chunkStart, this.pos);
  19497. return this.finishToken(types$1.template, out)
  19498. }
  19499. if (ch === 92) { // '\'
  19500. out += this.input.slice(chunkStart, this.pos);
  19501. out += this.readEscapedChar(true);
  19502. chunkStart = this.pos;
  19503. } else if (isNewLine(ch)) {
  19504. out += this.input.slice(chunkStart, this.pos);
  19505. ++this.pos;
  19506. switch (ch) {
  19507. case 13:
  19508. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  19509. case 10:
  19510. out += "\n";
  19511. break
  19512. default:
  19513. out += String.fromCharCode(ch);
  19514. break
  19515. }
  19516. if (this.options.locations) {
  19517. ++this.curLine;
  19518. this.lineStart = this.pos;
  19519. }
  19520. chunkStart = this.pos;
  19521. } else {
  19522. ++this.pos;
  19523. }
  19524. }
  19525. };
  19526. // Reads a template token to search for the end, without validating any escape sequences
  19527. pp.readInvalidTemplateToken = function() {
  19528. for (; this.pos < this.input.length; this.pos++) {
  19529. switch (this.input[this.pos]) {
  19530. case "\\":
  19531. ++this.pos;
  19532. break
  19533. case "$":
  19534. if (this.input[this.pos + 1] !== "{") {
  19535. break
  19536. }
  19537. // falls through
  19538. case "`":
  19539. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  19540. // no default
  19541. }
  19542. }
  19543. this.raise(this.start, "Unterminated template");
  19544. };
  19545. // Used to read escaped characters
  19546. pp.readEscapedChar = function(inTemplate) {
  19547. var ch = this.input.charCodeAt(++this.pos);
  19548. ++this.pos;
  19549. switch (ch) {
  19550. case 110: return "\n" // 'n' -> '\n'
  19551. case 114: return "\r" // 'r' -> '\r'
  19552. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  19553. case 117: return codePointToString(this.readCodePoint()) // 'u'
  19554. case 116: return "\t" // 't' -> '\t'
  19555. case 98: return "\b" // 'b' -> '\b'
  19556. case 118: return "\u000b" // 'v' -> '\u000b'
  19557. case 102: return "\f" // 'f' -> '\f'
  19558. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  19559. case 10: // ' \n'
  19560. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  19561. return ""
  19562. case 56:
  19563. case 57:
  19564. if (this.strict) {
  19565. this.invalidStringToken(
  19566. this.pos - 1,
  19567. "Invalid escape sequence"
  19568. );
  19569. }
  19570. if (inTemplate) {
  19571. var codePos = this.pos - 1;
  19572. this.invalidStringToken(
  19573. codePos,
  19574. "Invalid escape sequence in template string"
  19575. );
  19576. }
  19577. default:
  19578. if (ch >= 48 && ch <= 55) {
  19579. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  19580. var octal = parseInt(octalStr, 8);
  19581. if (octal > 255) {
  19582. octalStr = octalStr.slice(0, -1);
  19583. octal = parseInt(octalStr, 8);
  19584. }
  19585. this.pos += octalStr.length - 1;
  19586. ch = this.input.charCodeAt(this.pos);
  19587. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  19588. this.invalidStringToken(
  19589. this.pos - 1 - octalStr.length,
  19590. inTemplate
  19591. ? "Octal literal in template string"
  19592. : "Octal literal in strict mode"
  19593. );
  19594. }
  19595. return String.fromCharCode(octal)
  19596. }
  19597. if (isNewLine(ch)) {
  19598. // Unicode new line characters after \ get removed from output in both
  19599. // template literals and strings
  19600. return ""
  19601. }
  19602. return String.fromCharCode(ch)
  19603. }
  19604. };
  19605. // Used to read character escape sequences ('\x', '\u', '\U').
  19606. pp.readHexChar = function(len) {
  19607. var codePos = this.pos;
  19608. var n = this.readInt(16, len);
  19609. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  19610. return n
  19611. };
  19612. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  19613. // to whether the word contained a '\u' escape.
  19614. //
  19615. // Incrementally adds only escaped chars, adding other chunks as-is
  19616. // as a micro-optimization.
  19617. pp.readWord1 = function() {
  19618. this.containsEsc = false;
  19619. var word = "", first = true, chunkStart = this.pos;
  19620. var astral = this.options.ecmaVersion >= 6;
  19621. while (this.pos < this.input.length) {
  19622. var ch = this.fullCharCodeAtPos();
  19623. if (isIdentifierChar(ch, astral)) {
  19624. this.pos += ch <= 0xffff ? 1 : 2;
  19625. } else if (ch === 92) { // "\"
  19626. this.containsEsc = true;
  19627. word += this.input.slice(chunkStart, this.pos);
  19628. var escStart = this.pos;
  19629. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  19630. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  19631. ++this.pos;
  19632. var esc = this.readCodePoint();
  19633. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  19634. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  19635. word += codePointToString(esc);
  19636. chunkStart = this.pos;
  19637. } else {
  19638. break
  19639. }
  19640. first = false;
  19641. }
  19642. return word + this.input.slice(chunkStart, this.pos)
  19643. };
  19644. // Read an identifier or keyword token. Will check for reserved
  19645. // words when necessary.
  19646. pp.readWord = function() {
  19647. var word = this.readWord1();
  19648. var type = types$1.name;
  19649. if (this.keywords.test(word)) {
  19650. type = keywords$2[word];
  19651. }
  19652. return this.finishToken(type, word)
  19653. };
  19654. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  19655. var version$2 = "8.8.2";
  19656. Parser$1.acorn = {
  19657. Parser: Parser$1,
  19658. version: version$2,
  19659. defaultOptions: defaultOptions,
  19660. Position: Position,
  19661. SourceLocation: SourceLocation,
  19662. getLineInfo: getLineInfo,
  19663. Node: Node,
  19664. TokenType: TokenType,
  19665. tokTypes: types$1,
  19666. keywordTypes: keywords$2,
  19667. TokContext: TokContext,
  19668. tokContexts: types$2,
  19669. isIdentifierChar: isIdentifierChar,
  19670. isIdentifierStart: isIdentifierStart,
  19671. Token: Token,
  19672. isNewLine: isNewLine,
  19673. lineBreak: lineBreak,
  19674. lineBreakG: lineBreakG,
  19675. nonASCIIwhitespace: nonASCIIwhitespace
  19676. };
  19677. // The main exported interface (under `self.acorn` when in the
  19678. // browser) is a `parse` function that takes a code string and
  19679. // returns an abstract syntax tree as specified by [Mozilla parser
  19680. // API][api].
  19681. //
  19682. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  19683. function parse$d(input, options) {
  19684. return Parser$1.parse(input, options)
  19685. }
  19686. // This function tries to parse a single expression at a given
  19687. // offset in a string. Useful for parsing mixed-language formats
  19688. // that embed JavaScript expressions.
  19689. function parseExpressionAt(input, pos, options) {
  19690. return Parser$1.parseExpressionAt(input, pos, options)
  19691. }
  19692. // Acorn is organized as a tokenizer and a recursive-descent parser.
  19693. // The `tokenizer` export provides an interface to the tokenizer.
  19694. function tokenizer(input, options) {
  19695. return Parser$1.tokenizer(input, options)
  19696. }
  19697. var acorn = {
  19698. __proto__: null,
  19699. Node: Node,
  19700. Parser: Parser$1,
  19701. Position: Position,
  19702. SourceLocation: SourceLocation,
  19703. TokContext: TokContext,
  19704. Token: Token,
  19705. TokenType: TokenType,
  19706. defaultOptions: defaultOptions,
  19707. getLineInfo: getLineInfo,
  19708. isIdentifierChar: isIdentifierChar,
  19709. isIdentifierStart: isIdentifierStart,
  19710. isNewLine: isNewLine,
  19711. keywordTypes: keywords$2,
  19712. lineBreak: lineBreak,
  19713. lineBreakG: lineBreakG,
  19714. nonASCIIwhitespace: nonASCIIwhitespace,
  19715. parse: parse$d,
  19716. parseExpressionAt: parseExpressionAt,
  19717. tokContexts: types$2,
  19718. tokTypes: types$1,
  19719. tokenizer: tokenizer,
  19720. version: version$2
  19721. };
  19722. const HASH_RE = /#/g;
  19723. const AMPERSAND_RE = /&/g;
  19724. const EQUAL_RE = /=/g;
  19725. const PLUS_RE = /\+/g;
  19726. const ENC_CARET_RE = /%5e/gi;
  19727. const ENC_BACKTICK_RE = /%60/gi;
  19728. const ENC_PIPE_RE = /%7c/gi;
  19729. const ENC_SPACE_RE = /%20/gi;
  19730. function encode(text) {
  19731. return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
  19732. }
  19733. function encodeQueryValue(input) {
  19734. return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^");
  19735. }
  19736. function encodeQueryKey(text) {
  19737. return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
  19738. }
  19739. function encodeQueryItem(key, value) {
  19740. if (typeof value === "number" || typeof value === "boolean") {
  19741. value = String(value);
  19742. }
  19743. if (!value) {
  19744. return encodeQueryKey(key);
  19745. }
  19746. if (Array.isArray(value)) {
  19747. return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
  19748. }
  19749. return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
  19750. }
  19751. function stringifyQuery(query) {
  19752. return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).join("&");
  19753. }
  19754. function matchAll(regex, string, addition) {
  19755. const matches = [];
  19756. for (const match of string.matchAll(regex)) {
  19757. matches.push({
  19758. ...addition,
  19759. ...match.groups,
  19760. code: match[0],
  19761. start: match.index,
  19762. end: match.index + match[0].length
  19763. });
  19764. }
  19765. return matches;
  19766. }
  19767. /**
  19768. * @typedef ErrnoExceptionFields
  19769. * @property {number | undefined} [errnode]
  19770. * @property {string | undefined} [code]
  19771. * @property {string | undefined} [path]
  19772. * @property {string | undefined} [syscall]
  19773. * @property {string | undefined} [url]
  19774. *
  19775. * @typedef {Error & ErrnoExceptionFields} ErrnoException
  19776. */
  19777. const isWindows$3 = process$1.platform === 'win32';
  19778. const own$1 = {}.hasOwnProperty;
  19779. /**
  19780. * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
  19781. * We cannot use Intl.ListFormat because it's not available in
  19782. * --without-intl builds.
  19783. *
  19784. * @param {Array<string>} array
  19785. * An array of strings.
  19786. * @param {string} [type]
  19787. * The list type to be inserted before the last element.
  19788. * @returns {string}
  19789. */
  19790. function formatList(array, type = 'and') {
  19791. return array.length < 3
  19792. ? array.join(` ${type} `)
  19793. : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
  19794. }
  19795. /** @type {Map<string, MessageFunction|string>} */
  19796. const messages = new Map();
  19797. const nodeInternalPrefix = '__node_internal_';
  19798. /** @type {number} */
  19799. let userStackTraceLimit;
  19800. createError(
  19801. 'ERR_INVALID_MODULE_SPECIFIER',
  19802. /**
  19803. * @param {string} request
  19804. * @param {string} reason
  19805. * @param {string} [base]
  19806. */
  19807. (request, reason, base = undefined) => {
  19808. return `Invalid module "${request}" ${reason}${
  19809. base ? ` imported from ${base}` : ''
  19810. }`
  19811. },
  19812. TypeError
  19813. );
  19814. createError(
  19815. 'ERR_INVALID_PACKAGE_CONFIG',
  19816. /**
  19817. * @param {string} path
  19818. * @param {string} [base]
  19819. * @param {string} [message]
  19820. */
  19821. (path, base, message) => {
  19822. return `Invalid package config ${path}${
  19823. base ? ` while importing ${base}` : ''
  19824. }${message ? `. ${message}` : ''}`
  19825. },
  19826. Error
  19827. );
  19828. createError(
  19829. 'ERR_INVALID_PACKAGE_TARGET',
  19830. /**
  19831. * @param {string} pkgPath
  19832. * @param {string} key
  19833. * @param {unknown} target
  19834. * @param {boolean} [isImport=false]
  19835. * @param {string} [base]
  19836. */
  19837. (pkgPath, key, target, isImport = false, base = undefined) => {
  19838. const relError =
  19839. typeof target === 'string' &&
  19840. !isImport &&
  19841. target.length > 0 &&
  19842. !target.startsWith('./');
  19843. if (key === '.') {
  19844. assert$1(isImport === false);
  19845. return (
  19846. `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
  19847. `in the package config ${pkgPath}package.json${
  19848. base ? ` imported from ${base}` : ''
  19849. }${relError ? '; targets must start with "./"' : ''}`
  19850. )
  19851. }
  19852. return `Invalid "${
  19853. isImport ? 'imports' : 'exports'
  19854. }" target ${JSON.stringify(
  19855. target
  19856. )} defined for '${key}' in the package config ${pkgPath}package.json${
  19857. base ? ` imported from ${base}` : ''
  19858. }${relError ? '; targets must start with "./"' : ''}`
  19859. },
  19860. Error
  19861. );
  19862. createError(
  19863. 'ERR_MODULE_NOT_FOUND',
  19864. /**
  19865. * @param {string} path
  19866. * @param {string} base
  19867. * @param {string} [type]
  19868. */
  19869. (path, base, type = 'package') => {
  19870. return `Cannot find ${type} '${path}' imported from ${base}`
  19871. },
  19872. Error
  19873. );
  19874. createError(
  19875. 'ERR_NETWORK_IMPORT_DISALLOWED',
  19876. "import of '%s' by %s is not supported: %s",
  19877. Error
  19878. );
  19879. createError(
  19880. 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
  19881. /**
  19882. * @param {string} specifier
  19883. * @param {string} packagePath
  19884. * @param {string} base
  19885. */
  19886. (specifier, packagePath, base) => {
  19887. return `Package import specifier "${specifier}" is not defined${
  19888. packagePath ? ` in package ${packagePath}package.json` : ''
  19889. } imported from ${base}`
  19890. },
  19891. TypeError
  19892. );
  19893. createError(
  19894. 'ERR_PACKAGE_PATH_NOT_EXPORTED',
  19895. /**
  19896. * @param {string} pkgPath
  19897. * @param {string} subpath
  19898. * @param {string} [base]
  19899. */
  19900. (pkgPath, subpath, base = undefined) => {
  19901. if (subpath === '.')
  19902. return `No "exports" main defined in ${pkgPath}package.json${
  19903. base ? ` imported from ${base}` : ''
  19904. }`
  19905. return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${
  19906. base ? ` imported from ${base}` : ''
  19907. }`
  19908. },
  19909. Error
  19910. );
  19911. createError(
  19912. 'ERR_UNSUPPORTED_DIR_IMPORT',
  19913. "Directory import '%s' is not supported " +
  19914. 'resolving ES modules imported from %s',
  19915. Error
  19916. );
  19917. createError(
  19918. 'ERR_UNKNOWN_FILE_EXTENSION',
  19919. /**
  19920. * @param {string} ext
  19921. * @param {string} path
  19922. */
  19923. (ext, path) => {
  19924. return `Unknown file extension "${ext}" for ${path}`
  19925. },
  19926. TypeError
  19927. );
  19928. createError(
  19929. 'ERR_INVALID_ARG_VALUE',
  19930. /**
  19931. * @param {string} name
  19932. * @param {unknown} value
  19933. * @param {string} [reason='is invalid']
  19934. */
  19935. (name, value, reason = 'is invalid') => {
  19936. let inspected = inspect(value);
  19937. if (inspected.length > 128) {
  19938. inspected = `${inspected.slice(0, 128)}...`;
  19939. }
  19940. const type = name.includes('.') ? 'property' : 'argument';
  19941. return `The ${type} '${name}' ${reason}. Received ${inspected}`
  19942. },
  19943. TypeError
  19944. // Note: extra classes have been shaken out.
  19945. // , RangeError
  19946. );
  19947. createError(
  19948. 'ERR_UNSUPPORTED_ESM_URL_SCHEME',
  19949. /**
  19950. * @param {URL} url
  19951. * @param {Array<string>} supported
  19952. */
  19953. (url, supported) => {
  19954. let message = `Only URLs with a scheme in: ${formatList(
  19955. supported
  19956. )} are supported by the default ESM loader`;
  19957. if (isWindows$3 && url.protocol.length === 2) {
  19958. message += '. On Windows, absolute paths must be valid file:// URLs';
  19959. }
  19960. message += `. Received protocol '${url.protocol}'`;
  19961. return message
  19962. },
  19963. Error
  19964. );
  19965. /**
  19966. * Utility function for registering the error codes. Only used here. Exported
  19967. * *only* to allow for testing.
  19968. * @param {string} sym
  19969. * @param {MessageFunction|string} value
  19970. * @param {ErrorConstructor} def
  19971. * @returns {new (...args: Array<any>) => Error}
  19972. */
  19973. function createError(sym, value, def) {
  19974. // Special case for SystemError that formats the error message differently
  19975. // The SystemErrors only have SystemError as their base classes.
  19976. messages.set(sym, value);
  19977. return makeNodeErrorWithCode(def, sym)
  19978. }
  19979. /**
  19980. * @param {ErrorConstructor} Base
  19981. * @param {string} key
  19982. * @returns {ErrorConstructor}
  19983. */
  19984. function makeNodeErrorWithCode(Base, key) {
  19985. // @ts-expect-error It’s a Node error.
  19986. return NodeError
  19987. /**
  19988. * @param {Array<unknown>} args
  19989. */
  19990. function NodeError(...args) {
  19991. const limit = Error.stackTraceLimit;
  19992. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
  19993. const error = new Base();
  19994. // Reset the limit and setting the name property.
  19995. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
  19996. const message = getMessage(key, args, error);
  19997. Object.defineProperties(error, {
  19998. // Note: no need to implement `kIsNodeError` symbol, would be hard,
  19999. // probably.
  20000. message: {
  20001. value: message,
  20002. enumerable: false,
  20003. writable: true,
  20004. configurable: true
  20005. },
  20006. toString: {
  20007. /** @this {Error} */
  20008. value() {
  20009. return `${this.name} [${key}]: ${this.message}`
  20010. },
  20011. enumerable: false,
  20012. writable: true,
  20013. configurable: true
  20014. }
  20015. });
  20016. captureLargerStackTrace(error);
  20017. // @ts-expect-error It’s a Node error.
  20018. error.code = key;
  20019. return error
  20020. }
  20021. }
  20022. /**
  20023. * @returns {boolean}
  20024. */
  20025. function isErrorStackTraceLimitWritable() {
  20026. // Do no touch Error.stackTraceLimit as V8 would attempt to install
  20027. // it again during deserialization.
  20028. try {
  20029. // @ts-expect-error: not in types?
  20030. if (v8.startupSnapshot.isBuildingSnapshot()) {
  20031. return false
  20032. }
  20033. } catch {}
  20034. const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
  20035. if (desc === undefined) {
  20036. return Object.isExtensible(Error)
  20037. }
  20038. return own$1.call(desc, 'writable') && desc.writable !== undefined
  20039. ? desc.writable
  20040. : desc.set !== undefined
  20041. }
  20042. /**
  20043. * This function removes unnecessary frames from Node.js core errors.
  20044. * @template {(...args: unknown[]) => unknown} T
  20045. * @param {T} fn
  20046. * @returns {T}
  20047. */
  20048. function hideStackFrames(fn) {
  20049. // We rename the functions that will be hidden to cut off the stacktrace
  20050. // at the outermost one
  20051. const hidden = nodeInternalPrefix + fn.name;
  20052. Object.defineProperty(fn, 'name', {value: hidden});
  20053. return fn
  20054. }
  20055. const captureLargerStackTrace = hideStackFrames(
  20056. /**
  20057. * @param {Error} error
  20058. * @returns {Error}
  20059. */
  20060. // @ts-expect-error: fine
  20061. function (error) {
  20062. const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
  20063. if (stackTraceLimitIsWritable) {
  20064. userStackTraceLimit = Error.stackTraceLimit;
  20065. Error.stackTraceLimit = Number.POSITIVE_INFINITY;
  20066. }
  20067. Error.captureStackTrace(error);
  20068. // Reset the limit
  20069. if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
  20070. return error
  20071. }
  20072. );
  20073. /**
  20074. * @param {string} key
  20075. * @param {Array<unknown>} args
  20076. * @param {Error} self
  20077. * @returns {string}
  20078. */
  20079. function getMessage(key, args, self) {
  20080. const message = messages.get(key);
  20081. assert$1(typeof message !== 'undefined', 'expected `message` to be found');
  20082. if (typeof message === 'function') {
  20083. assert$1(
  20084. message.length <= args.length, // Default options do not count.
  20085. `Code: ${key}; The provided arguments length (${args.length}) does not ` +
  20086. `match the required ones (${message.length}).`
  20087. );
  20088. return Reflect.apply(message, self, args)
  20089. }
  20090. const regex = /%[dfijoOs]/g;
  20091. let expectedLength = 0;
  20092. while (regex.exec(message) !== null) expectedLength++;
  20093. assert$1(
  20094. expectedLength === args.length,
  20095. `Code: ${key}; The provided arguments length (${args.length}) does not ` +
  20096. `match the required ones (${expectedLength}).`
  20097. );
  20098. if (args.length === 0) return message
  20099. args.unshift(message);
  20100. return Reflect.apply(format$2, null, args)
  20101. }
  20102. pathToFileURL(process.cwd());
  20103. const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;)import\s*([\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm;
  20104. const TYPE_RE = /^\s*?type\s/;
  20105. function findStaticImports(code) {
  20106. return matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" });
  20107. }
  20108. function parseStaticImport(matched) {
  20109. const cleanedImports = (matched.imports || "").replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "").replace(/\s+/g, " ");
  20110. const namedImports = {};
  20111. for (const namedImport of cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []) {
  20112. const [, source = namedImport.trim(), importName = source] = namedImport.match(/^\s*(\S*) as (\S*)\s*$/) || [];
  20113. if (source && !TYPE_RE.test(source)) {
  20114. namedImports[source] = importName;
  20115. }
  20116. }
  20117. const topLevelImports = cleanedImports.replace(/{([^}]*)}/, "");
  20118. const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1];
  20119. const defaultImport = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0;
  20120. return {
  20121. ...matched,
  20122. defaultImport,
  20123. namespacedImport,
  20124. namedImports
  20125. };
  20126. }
  20127. const ESM_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
  20128. function hasESMSyntax(code) {
  20129. return ESM_RE.test(code);
  20130. }
  20131. const normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY);
  20132. const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
  20133. // special id for paths marked with browser: false
  20134. // https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module
  20135. const browserExternalId = '__vite-browser-external';
  20136. // special id for packages that are optional peer deps
  20137. const optionalPeerDepId = '__vite-optional-peer-dep';
  20138. const subpathImportsPrefix = '#';
  20139. const startsWithWordCharRE = /^\w/;
  20140. const debug$d = createDebugger('vite:resolve-details', {
  20141. onlyWhenFocused: true,
  20142. });
  20143. function resolvePlugin(resolveOptions) {
  20144. const { root, isProduction, asSrc, ssrConfig, preferRelative = false, } = resolveOptions;
  20145. const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig ?? {};
  20146. // In unix systems, absolute paths inside root first needs to be checked as an
  20147. // absolute URL (/root/root/path-to-file) resulting in failed checks before falling
  20148. // back to checking the path as absolute. If /root/root isn't a valid path, we can
  20149. // avoid these checks. Absolute paths inside root are common in user code as many
  20150. // paths are resolved by the user. For example for an alias.
  20151. const rootInRoot = tryStatSync(path$o.join(root, root))?.isDirectory() ?? false;
  20152. return {
  20153. name: 'vite:resolve',
  20154. async resolveId(id, importer, resolveOpts) {
  20155. if (id[0] === '\0' ||
  20156. id.startsWith('virtual:') ||
  20157. // When injected directly in html/client code
  20158. id.startsWith('/virtual:')) {
  20159. return;
  20160. }
  20161. const ssr = resolveOpts?.ssr === true;
  20162. // We need to delay depsOptimizer until here instead of passing it as an option
  20163. // the resolvePlugin because the optimizer is created on server listen during dev
  20164. const depsOptimizer = resolveOptions.getDepsOptimizer?.(ssr);
  20165. if (id.startsWith(browserExternalId)) {
  20166. return id;
  20167. }
  20168. const targetWeb = !ssr || ssrTarget === 'webworker';
  20169. // this is passed by @rollup/plugin-commonjs
  20170. const isRequire = resolveOpts?.custom?.['node-resolve']?.isRequire ?? false;
  20171. const options = {
  20172. isRequire,
  20173. ...resolveOptions,
  20174. scan: resolveOpts?.scan ?? resolveOptions.scan,
  20175. };
  20176. const resolvedImports = resolveSubpathImports(id, importer, options, targetWeb);
  20177. if (resolvedImports) {
  20178. id = resolvedImports;
  20179. }
  20180. if (importer) {
  20181. if (isTsRequest(importer) ||
  20182. resolveOpts.custom?.depScan?.loader?.startsWith('ts')) {
  20183. options.isFromTsImporter = true;
  20184. }
  20185. else {
  20186. const moduleLang = this.getModuleInfo(importer)?.meta?.vite?.lang;
  20187. options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`);
  20188. }
  20189. }
  20190. let res;
  20191. // resolve pre-bundled deps requests, these could be resolved by
  20192. // tryFileResolve or /fs/ resolution but these files may not yet
  20193. // exists if we are in the middle of a deps re-processing
  20194. if (asSrc && depsOptimizer?.isOptimizedDepUrl(id)) {
  20195. const optimizedPath = id.startsWith(FS_PREFIX)
  20196. ? fsPathFromId(id)
  20197. : normalizePath$3(path$o.resolve(root, id.slice(1)));
  20198. return optimizedPath;
  20199. }
  20200. // explicit fs paths that starts with /@fs/*
  20201. if (asSrc && id.startsWith(FS_PREFIX)) {
  20202. res = fsPathFromId(id);
  20203. // We don't need to resolve these paths since they are already resolved
  20204. // always return here even if res doesn't exist since /@fs/ is explicit
  20205. // if the file doesn't exist it should be a 404.
  20206. debug$d?.(`[@fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  20207. return ensureVersionQuery(res, id, options, depsOptimizer);
  20208. }
  20209. // URL
  20210. // /foo -> /fs-root/foo
  20211. if (asSrc && id[0] === '/' && (rootInRoot || !id.startsWith(root))) {
  20212. const fsPath = path$o.resolve(root, id.slice(1));
  20213. if ((res = tryFsResolve(fsPath, options))) {
  20214. debug$d?.(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  20215. return ensureVersionQuery(res, id, options, depsOptimizer);
  20216. }
  20217. }
  20218. // relative
  20219. if (id[0] === '.' ||
  20220. ((preferRelative || importer?.endsWith('.html')) &&
  20221. startsWithWordCharRE.test(id))) {
  20222. const basedir = importer ? path$o.dirname(importer) : process.cwd();
  20223. const fsPath = path$o.resolve(basedir, id);
  20224. // handle browser field mapping for relative imports
  20225. const normalizedFsPath = normalizePath$3(fsPath);
  20226. if (depsOptimizer?.isOptimizedDepFile(normalizedFsPath)) {
  20227. // Optimized files could not yet exist in disk, resolve to the full path
  20228. // Inject the current browserHash version if the path doesn't have one
  20229. if (!normalizedFsPath.match(DEP_VERSION_RE)) {
  20230. const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata, normalizedFsPath)?.browserHash;
  20231. if (browserHash) {
  20232. return injectQuery(normalizedFsPath, `v=${browserHash}`);
  20233. }
  20234. }
  20235. return normalizedFsPath;
  20236. }
  20237. if (targetWeb &&
  20238. options.browserField &&
  20239. (res = tryResolveBrowserMapping(fsPath, importer, options, true))) {
  20240. return res;
  20241. }
  20242. if ((res = tryFsResolve(fsPath, options))) {
  20243. res = ensureVersionQuery(res, id, options, depsOptimizer);
  20244. debug$d?.(`[relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  20245. // If this isn't a script imported from a .html file, include side effects
  20246. // hints so the non-used code is properly tree-shaken during build time.
  20247. if (!options.idOnly &&
  20248. !options.scan &&
  20249. options.isBuild &&
  20250. !importer?.endsWith('.html')) {
  20251. const resPkg = findNearestPackageData(path$o.dirname(res), options.packageCache);
  20252. if (resPkg) {
  20253. return {
  20254. id: res,
  20255. moduleSideEffects: resPkg.hasSideEffects(res),
  20256. };
  20257. }
  20258. }
  20259. return res;
  20260. }
  20261. }
  20262. // drive relative fs paths (only windows)
  20263. if (isWindows$4 && id[0] === '/') {
  20264. const basedir = importer ? path$o.dirname(importer) : process.cwd();
  20265. const fsPath = path$o.resolve(basedir, id);
  20266. if ((res = tryFsResolve(fsPath, options))) {
  20267. debug$d?.(`[drive-relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  20268. return ensureVersionQuery(res, id, options, depsOptimizer);
  20269. }
  20270. }
  20271. // absolute fs paths
  20272. if (isNonDriveRelativeAbsolutePath(id) &&
  20273. (res = tryFsResolve(id, options))) {
  20274. debug$d?.(`[fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  20275. return ensureVersionQuery(res, id, options, depsOptimizer);
  20276. }
  20277. // external
  20278. if (isExternalUrl(id)) {
  20279. return options.idOnly ? id : { id, external: true };
  20280. }
  20281. // data uri: pass through (this only happens during build and will be
  20282. // handled by dedicated plugin)
  20283. if (isDataUrl(id)) {
  20284. return null;
  20285. }
  20286. // bare package imports, perform node resolve
  20287. if (bareImportRE.test(id)) {
  20288. const external = options.shouldExternalize?.(id);
  20289. if (!external &&
  20290. asSrc &&
  20291. depsOptimizer &&
  20292. !options.scan &&
  20293. (res = await tryOptimizedResolve(depsOptimizer, id, importer, options.preserveSymlinks, options.packageCache))) {
  20294. return res;
  20295. }
  20296. if (targetWeb &&
  20297. options.browserField &&
  20298. (res = tryResolveBrowserMapping(id, importer, options, false, external))) {
  20299. return res;
  20300. }
  20301. if ((res = tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, external))) {
  20302. return res;
  20303. }
  20304. // node built-ins.
  20305. // externalize if building for SSR, otherwise redirect to empty module
  20306. if (isBuiltin(id)) {
  20307. if (ssr) {
  20308. if (ssrNoExternal === true) {
  20309. let message = `Cannot bundle Node.js built-in "${id}"`;
  20310. if (importer) {
  20311. message += ` imported from "${path$o.relative(process.cwd(), importer)}"`;
  20312. }
  20313. message += `. Consider disabling ssr.noExternal or remove the built-in dependency.`;
  20314. this.error(message);
  20315. }
  20316. return options.idOnly ? id : { id, external: true };
  20317. }
  20318. else {
  20319. if (!asSrc) {
  20320. debug$d?.(`externalized node built-in "${id}" to empty module. ` +
  20321. `(imported by: ${colors$1.white(colors$1.dim(importer))})`);
  20322. }
  20323. else if (isProduction) {
  20324. this.warn(`Module "${id}" has been externalized for browser compatibility, imported by "${importer}". ` +
  20325. `See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
  20326. }
  20327. return isProduction
  20328. ? browserExternalId
  20329. : `${browserExternalId}:${id}`;
  20330. }
  20331. }
  20332. }
  20333. debug$d?.(`[fallthrough] ${colors$1.dim(id)}`);
  20334. },
  20335. load(id) {
  20336. if (id.startsWith(browserExternalId)) {
  20337. if (isProduction) {
  20338. return `export default {}`;
  20339. }
  20340. else {
  20341. id = id.slice(browserExternalId.length + 1);
  20342. return `\
  20343. export default new Proxy({}, {
  20344. get(_, key) {
  20345. throw new Error(\`Module "${id}" has been externalized for browser compatibility. Cannot access "${id}.\${key}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
  20346. }
  20347. })`;
  20348. }
  20349. }
  20350. if (id.startsWith(optionalPeerDepId)) {
  20351. if (isProduction) {
  20352. return `export default {}`;
  20353. }
  20354. else {
  20355. const [, peerDep, parentDep] = id.split(':');
  20356. return `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`;
  20357. }
  20358. }
  20359. },
  20360. };
  20361. }
  20362. function resolveSubpathImports(id, importer, options, targetWeb) {
  20363. if (!importer || !id.startsWith(subpathImportsPrefix))
  20364. return;
  20365. const basedir = path$o.dirname(importer);
  20366. const pkgData = findNearestPackageData(basedir, options.packageCache);
  20367. if (!pkgData)
  20368. return;
  20369. let importsPath = resolveExportsOrImports(pkgData.data, id, options, targetWeb, 'imports');
  20370. if (importsPath?.[0] === '.') {
  20371. importsPath = path$o.relative(basedir, path$o.join(pkgData.dir, importsPath));
  20372. if (importsPath[0] !== '.') {
  20373. importsPath = `./${importsPath}`;
  20374. }
  20375. }
  20376. return importsPath;
  20377. }
  20378. function ensureVersionQuery(resolved, id, options, depsOptimizer) {
  20379. if (!options.isBuild &&
  20380. !options.scan &&
  20381. depsOptimizer &&
  20382. !(resolved === normalizedClientEntry$1 || resolved === normalizedEnvEntry$1)) {
  20383. // Ensure that direct imports of node_modules have the same version query
  20384. // as if they would have been imported through a bare import
  20385. // Use the original id to do the check as the resolved id may be the real
  20386. // file path after symlinks resolution
  20387. const isNodeModule = isInNodeModules(id) || isInNodeModules(resolved);
  20388. if (isNodeModule && !resolved.match(DEP_VERSION_RE)) {
  20389. const versionHash = depsOptimizer.metadata.browserHash;
  20390. if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
  20391. resolved = injectQuery(resolved, `v=${versionHash}`);
  20392. }
  20393. }
  20394. }
  20395. return resolved;
  20396. }
  20397. function splitFileAndPostfix(path) {
  20398. const file = cleanUrl(path);
  20399. return { file, postfix: path.slice(file.length) };
  20400. }
  20401. function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
  20402. // Dependencies like es5-ext use `#` in their paths. We don't support `#` in user
  20403. // source code so we only need to perform the check for dependencies.
  20404. // We don't support `?` in node_modules paths, so we only need to check in this branch.
  20405. const hashIndex = fsPath.indexOf('#');
  20406. if (hashIndex >= 0 && isInNodeModules(fsPath)) {
  20407. const queryIndex = fsPath.indexOf('?');
  20408. // We only need to check foo#bar?baz and foo#bar, ignore foo?bar#baz
  20409. if (queryIndex < 0 || queryIndex > hashIndex) {
  20410. const file = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
  20411. const res = tryCleanFsResolve(file, options, tryIndex, targetWeb, skipPackageJson);
  20412. if (res)
  20413. return res + fsPath.slice(file.length);
  20414. }
  20415. }
  20416. const { file, postfix } = splitFileAndPostfix(fsPath);
  20417. const res = tryCleanFsResolve(file, options, tryIndex, targetWeb, skipPackageJson);
  20418. if (res)
  20419. return res + postfix;
  20420. }
  20421. const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
  20422. const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
  20423. function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
  20424. const { tryPrefix, extensions, preserveSymlinks } = options;
  20425. const fileStat = tryStatSync(file);
  20426. // Try direct match first
  20427. if (fileStat?.isFile())
  20428. return getRealPath(file, options.preserveSymlinks);
  20429. let res;
  20430. // If path.dirname is a valid directory, try extensions and ts resolution logic
  20431. const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file);
  20432. if (possibleJsToTs || extensions.length || tryPrefix) {
  20433. const dirPath = path$o.dirname(file);
  20434. const dirStat = tryStatSync(dirPath);
  20435. if (dirStat?.isDirectory()) {
  20436. if (possibleJsToTs) {
  20437. // try resolve .js, .mjs, .cjs or .jsx import to typescript file
  20438. const fileExt = path$o.extname(file);
  20439. const fileName = file.slice(0, -fileExt.length);
  20440. if ((res = tryResolveRealFile(fileName + fileExt.replace('js', 'ts'), preserveSymlinks)))
  20441. return res;
  20442. // for .js, also try .tsx
  20443. if (fileExt === '.js' &&
  20444. (res = tryResolveRealFile(fileName + '.tsx', preserveSymlinks)))
  20445. return res;
  20446. }
  20447. if ((res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)))
  20448. return res;
  20449. if (tryPrefix) {
  20450. const prefixed = `${dirPath}/${options.tryPrefix}${path$o.basename(file)}`;
  20451. if ((res = tryResolveRealFile(prefixed, preserveSymlinks)))
  20452. return res;
  20453. if ((res = tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)))
  20454. return res;
  20455. }
  20456. }
  20457. }
  20458. if (tryIndex && fileStat) {
  20459. // Path points to a directory, check for package.json and entry and /index file
  20460. const dirPath = file;
  20461. if (!skipPackageJson) {
  20462. let pkgPath = `${dirPath}/package.json`;
  20463. try {
  20464. if (fs$l.existsSync(pkgPath)) {
  20465. if (!options.preserveSymlinks) {
  20466. pkgPath = safeRealpathSync(pkgPath);
  20467. }
  20468. // path points to a node package
  20469. const pkg = loadPackageData(pkgPath);
  20470. return resolvePackageEntry(dirPath, pkg, targetWeb, options);
  20471. }
  20472. }
  20473. catch (e) {
  20474. if (e.code !== 'ENOENT')
  20475. throw e;
  20476. }
  20477. }
  20478. if ((res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)))
  20479. return res;
  20480. if (tryPrefix) {
  20481. if ((res = tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)))
  20482. return res;
  20483. }
  20484. }
  20485. }
  20486. function tryResolveRealFile(file, preserveSymlinks) {
  20487. const stat = tryStatSync(file);
  20488. if (stat?.isFile())
  20489. return getRealPath(file, preserveSymlinks);
  20490. }
  20491. function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
  20492. for (const ext of extensions) {
  20493. const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
  20494. if (res)
  20495. return res;
  20496. }
  20497. }
  20498. function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = false, externalize, allowLinkedExternal = true) {
  20499. const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
  20500. // check for deep import, e.g. "my-lib/foo"
  20501. const deepMatch = id.match(deepImportRE);
  20502. const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : id;
  20503. let basedir;
  20504. if (dedupe?.includes(pkgId)) {
  20505. basedir = root;
  20506. }
  20507. else if (importer &&
  20508. path$o.isAbsolute(importer) &&
  20509. // css processing appends `*` for importer
  20510. (importer[importer.length - 1] === '*' || fs$l.existsSync(cleanUrl(importer)))) {
  20511. basedir = path$o.dirname(importer);
  20512. }
  20513. else {
  20514. basedir = root;
  20515. }
  20516. const pkg = resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
  20517. if (!pkg) {
  20518. // if import can't be found, check if it's an optional peer dep.
  20519. // if so, we can resolve to a special id that errors only when imported.
  20520. if (basedir !== root && // root has no peer dep
  20521. !isBuiltin(id) &&
  20522. !id.includes('\0') &&
  20523. bareImportRE.test(id)) {
  20524. const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
  20525. if (mainPkg) {
  20526. if (mainPkg.peerDependencies?.[id] &&
  20527. mainPkg.peerDependenciesMeta?.[id]?.optional) {
  20528. return {
  20529. id: `${optionalPeerDepId}:${id}:${mainPkg.name}`,
  20530. };
  20531. }
  20532. }
  20533. }
  20534. return;
  20535. }
  20536. const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry;
  20537. const unresolvedId = deepMatch ? '.' + id.slice(pkgId.length) : pkgId;
  20538. let resolved;
  20539. try {
  20540. resolved = resolveId(unresolvedId, pkg, targetWeb, options);
  20541. }
  20542. catch (err) {
  20543. if (!options.tryEsmOnly) {
  20544. throw err;
  20545. }
  20546. }
  20547. if (!resolved && options.tryEsmOnly) {
  20548. resolved = resolveId(unresolvedId, pkg, targetWeb, {
  20549. ...options,
  20550. isRequire: false,
  20551. mainFields: DEFAULT_MAIN_FIELDS,
  20552. extensions: DEFAULT_EXTENSIONS$1,
  20553. });
  20554. }
  20555. if (!resolved) {
  20556. return;
  20557. }
  20558. const processResult = (resolved) => {
  20559. if (!externalize) {
  20560. return resolved;
  20561. }
  20562. // don't external symlink packages
  20563. if (!allowLinkedExternal && !isInNodeModules(resolved.id)) {
  20564. return resolved;
  20565. }
  20566. const resolvedExt = path$o.extname(resolved.id);
  20567. // don't external non-js imports
  20568. if (resolvedExt &&
  20569. resolvedExt !== '.js' &&
  20570. resolvedExt !== '.mjs' &&
  20571. resolvedExt !== '.cjs') {
  20572. return resolved;
  20573. }
  20574. let resolvedId = id;
  20575. if (deepMatch && !pkg?.data.exports && path$o.extname(id) !== resolvedExt) {
  20576. // id date-fns/locale
  20577. // resolve.id ...date-fns/esm/locale/index.js
  20578. const index = resolved.id.indexOf(id);
  20579. if (index > -1) {
  20580. resolvedId = resolved.id.slice(index);
  20581. debug$d?.(`[processResult] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedId)}`);
  20582. }
  20583. }
  20584. return { ...resolved, id: resolvedId, external: true };
  20585. };
  20586. if (!options.idOnly &&
  20587. ((!options.scan && isBuild && !depsOptimizer) || externalize)) {
  20588. // Resolve package side effects for build so that rollup can better
  20589. // perform tree-shaking
  20590. return processResult({
  20591. id: resolved,
  20592. moduleSideEffects: pkg.hasSideEffects(resolved),
  20593. });
  20594. }
  20595. const ext = path$o.extname(resolved);
  20596. if (!options.ssrOptimizeCheck &&
  20597. (!isInNodeModules(resolved) || // linked
  20598. !depsOptimizer || // resolving before listening to the server
  20599. options.scan) // initial esbuild scan phase
  20600. ) {
  20601. return { id: resolved };
  20602. }
  20603. // if we reach here, it's a valid dep import that hasn't been optimized.
  20604. const isJsType = depsOptimizer
  20605. ? isOptimizable(resolved, depsOptimizer.options)
  20606. : OPTIMIZABLE_ENTRY_RE.test(resolved);
  20607. let exclude = depsOptimizer?.options.exclude;
  20608. let include = depsOptimizer?.options.include;
  20609. if (options.ssrOptimizeCheck) {
  20610. // we don't have the depsOptimizer
  20611. exclude = options.ssrConfig?.optimizeDeps?.exclude;
  20612. include = options.ssrConfig?.optimizeDeps?.include;
  20613. }
  20614. const skipOptimization = depsOptimizer?.options.noDiscovery ||
  20615. !isJsType ||
  20616. (importer && isInNodeModules(importer)) ||
  20617. exclude?.includes(pkgId) ||
  20618. exclude?.includes(id) ||
  20619. SPECIAL_QUERY_RE.test(resolved) ||
  20620. // During dev SSR, we don't have a way to reload the module graph if
  20621. // a non-optimized dep is found. So we need to skip optimization here.
  20622. // The only optimized deps are the ones explicitly listed in the config.
  20623. (!options.ssrOptimizeCheck && !isBuild && ssr) ||
  20624. // Only optimize non-external CJS deps during SSR by default
  20625. (ssr &&
  20626. !(ext === '.cjs' ||
  20627. (ext === '.js' &&
  20628. findNearestPackageData(path$o.dirname(resolved), options.packageCache)
  20629. ?.data.type !== 'module')) &&
  20630. !(include?.includes(pkgId) || include?.includes(id)));
  20631. if (options.ssrOptimizeCheck) {
  20632. return {
  20633. id: skipOptimization
  20634. ? injectQuery(resolved, `__vite_skip_optimization`)
  20635. : resolved,
  20636. };
  20637. }
  20638. if (skipOptimization) {
  20639. // excluded from optimization
  20640. // Inject a version query to npm deps so that the browser
  20641. // can cache it without re-validation, but only do so for known js types.
  20642. // otherwise we may introduce duplicated modules for externalized files
  20643. // from pre-bundled deps.
  20644. if (!isBuild) {
  20645. const versionHash = depsOptimizer.metadata.browserHash;
  20646. if (versionHash && isJsType) {
  20647. resolved = injectQuery(resolved, `v=${versionHash}`);
  20648. }
  20649. }
  20650. }
  20651. else {
  20652. // this is a missing import, queue optimize-deps re-run and
  20653. // get a resolved its optimized info
  20654. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
  20655. resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
  20656. }
  20657. if (!options.idOnly && !options.scan && isBuild) {
  20658. // Resolve package side effects for build so that rollup can better
  20659. // perform tree-shaking
  20660. return {
  20661. id: resolved,
  20662. moduleSideEffects: pkg.hasSideEffects(resolved),
  20663. };
  20664. }
  20665. else {
  20666. return { id: resolved };
  20667. }
  20668. }
  20669. async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
  20670. // TODO: we need to wait until scanning is done here as this function
  20671. // is used in the preAliasPlugin to decide if an aliased dep is optimized,
  20672. // and avoid replacing the bare import with the resolved path.
  20673. // We should be able to remove this in the future
  20674. await depsOptimizer.scanProcessing;
  20675. const metadata = depsOptimizer.metadata;
  20676. const depInfo = optimizedDepInfoFromId(metadata, id);
  20677. if (depInfo) {
  20678. return depsOptimizer.getOptimizedDepId(depInfo);
  20679. }
  20680. if (!importer)
  20681. return;
  20682. // further check if id is imported by nested dependency
  20683. let idPkgDir;
  20684. const nestedIdMatch = `> ${id}`;
  20685. for (const optimizedData of metadata.depInfoList) {
  20686. if (!optimizedData.src)
  20687. continue; // Ignore chunks
  20688. // check where "foo" is nested in "my-lib > foo"
  20689. if (!optimizedData.id.endsWith(nestedIdMatch))
  20690. continue;
  20691. // lazily initialize idPkgDir
  20692. if (idPkgDir == null) {
  20693. idPkgDir = resolvePackageData(id, importer, preserveSymlinks, packageCache)?.dir;
  20694. // if still null, it likely means that this id isn't a dep for importer.
  20695. // break to bail early
  20696. if (idPkgDir == null)
  20697. break;
  20698. idPkgDir = normalizePath$3(idPkgDir);
  20699. }
  20700. // match by src to correctly identify if id belongs to nested dependency
  20701. if (optimizedData.src.startsWith(idPkgDir)) {
  20702. return depsOptimizer.getOptimizedDepId(optimizedData);
  20703. }
  20704. }
  20705. }
  20706. function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, targetWeb, options) {
  20707. const cached = getResolvedCache('.', targetWeb);
  20708. if (cached) {
  20709. return cached;
  20710. }
  20711. try {
  20712. let entryPoint;
  20713. // resolve exports field with highest priority
  20714. // using https://github.com/lukeed/resolve.exports
  20715. if (data.exports) {
  20716. entryPoint = resolveExportsOrImports(data, '.', options, targetWeb, 'exports');
  20717. }
  20718. const resolvedFromExports = !!entryPoint;
  20719. // if exports resolved to .mjs, still resolve other fields.
  20720. // This is because .mjs files can technically import .cjs files which would
  20721. // make them invalid for pure ESM environments - so if other module/browser
  20722. // fields are present, prioritize those instead.
  20723. if (targetWeb &&
  20724. options.browserField &&
  20725. (!entryPoint || entryPoint.endsWith('.mjs'))) {
  20726. // check browser field
  20727. // https://github.com/defunctzombie/package-browser-field-spec
  20728. const browserEntry = typeof data.browser === 'string'
  20729. ? data.browser
  20730. : isObject$2(data.browser) && data.browser['.'];
  20731. if (browserEntry) {
  20732. // check if the package also has a "module" field.
  20733. if (!options.isRequire &&
  20734. options.mainFields.includes('module') &&
  20735. typeof data.module === 'string' &&
  20736. data.module !== browserEntry) {
  20737. // if both are present, we may have a problem: some package points both
  20738. // to ESM, with "module" targeting Node.js, while some packages points
  20739. // "module" to browser ESM and "browser" to UMD/IIFE.
  20740. // the heuristics here is to actually read the browser entry when
  20741. // possible and check for hints of ESM. If it is not ESM, prefer "module"
  20742. // instead; Otherwise, assume it's ESM and use it.
  20743. const resolvedBrowserEntry = tryFsResolve(path$o.join(dir, browserEntry), options);
  20744. if (resolvedBrowserEntry) {
  20745. const content = fs$l.readFileSync(resolvedBrowserEntry, 'utf-8');
  20746. if (hasESMSyntax(content)) {
  20747. // likely ESM, prefer browser
  20748. entryPoint = browserEntry;
  20749. }
  20750. else {
  20751. // non-ESM, UMD or IIFE or CJS(!!! e.g. firebase 7.x), prefer module
  20752. entryPoint = data.module;
  20753. }
  20754. }
  20755. }
  20756. else {
  20757. entryPoint = browserEntry;
  20758. }
  20759. }
  20760. }
  20761. // fallback to mainFields if still not resolved
  20762. // TODO: review if `.mjs` check is still needed
  20763. if (!resolvedFromExports && (!entryPoint || entryPoint.endsWith('.mjs'))) {
  20764. for (const field of options.mainFields) {
  20765. if (field === 'browser')
  20766. continue; // already checked above
  20767. if (typeof data[field] === 'string') {
  20768. entryPoint = data[field];
  20769. break;
  20770. }
  20771. }
  20772. }
  20773. entryPoint || (entryPoint = data.main);
  20774. // try default entry when entry is not define
  20775. // https://nodejs.org/api/modules.html#all-together
  20776. const entryPoints = entryPoint
  20777. ? [entryPoint]
  20778. : ['index.js', 'index.json', 'index.node'];
  20779. for (let entry of entryPoints) {
  20780. // make sure we don't get scripts when looking for sass
  20781. let skipPackageJson = false;
  20782. if (options.mainFields[0] === 'sass' &&
  20783. !options.extensions.includes(path$o.extname(entry))) {
  20784. entry = '';
  20785. skipPackageJson = true;
  20786. }
  20787. else {
  20788. // resolve object browser field in package.json
  20789. const { browser: browserField } = data;
  20790. if (targetWeb && options.browserField && isObject$2(browserField)) {
  20791. entry = mapWithBrowserField(entry, browserField) || entry;
  20792. }
  20793. }
  20794. const entryPointPath = path$o.join(dir, entry);
  20795. const resolvedEntryPoint = tryFsResolve(entryPointPath, options, true, true, skipPackageJson);
  20796. if (resolvedEntryPoint) {
  20797. debug$d?.(`[package entry] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedEntryPoint)}`);
  20798. setResolvedCache('.', resolvedEntryPoint, targetWeb);
  20799. return resolvedEntryPoint;
  20800. }
  20801. }
  20802. }
  20803. catch (e) {
  20804. packageEntryFailure(id, e.message);
  20805. }
  20806. packageEntryFailure(id);
  20807. }
  20808. function packageEntryFailure(id, details) {
  20809. throw new Error(`Failed to resolve entry for package "${id}". ` +
  20810. `The package may have incorrect main/module/exports specified in its package.json` +
  20811. (details ? ': ' + details : '.'));
  20812. }
  20813. function resolveExportsOrImports(pkg, key, options, targetWeb, type) {
  20814. const additionalConditions = new Set(options.overrideConditions || [
  20815. 'production',
  20816. 'development',
  20817. 'module',
  20818. ...options.conditions,
  20819. ]);
  20820. const conditions = [...additionalConditions].filter((condition) => {
  20821. switch (condition) {
  20822. case 'production':
  20823. return options.isProduction;
  20824. case 'development':
  20825. return !options.isProduction;
  20826. case 'module':
  20827. return !options.isRequire;
  20828. }
  20829. return true;
  20830. });
  20831. const fn = type === 'imports' ? f : o;
  20832. const result = fn(pkg, key, {
  20833. browser: targetWeb && !additionalConditions.has('node'),
  20834. require: options.isRequire && !additionalConditions.has('import'),
  20835. conditions,
  20836. });
  20837. return result ? result[0] : undefined;
  20838. }
  20839. function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolvedCache, dir, data, }, targetWeb, options) {
  20840. const cache = getResolvedCache(id, targetWeb);
  20841. if (cache) {
  20842. return cache;
  20843. }
  20844. let relativeId = id;
  20845. const { exports: exportsField, browser: browserField } = data;
  20846. // map relative based on exports data
  20847. if (exportsField) {
  20848. if (isObject$2(exportsField) && !Array.isArray(exportsField)) {
  20849. // resolve without postfix (see #7098)
  20850. const { file, postfix } = splitFileAndPostfix(relativeId);
  20851. const exportsId = resolveExportsOrImports(data, file, options, targetWeb, 'exports');
  20852. if (exportsId !== undefined) {
  20853. relativeId = exportsId + postfix;
  20854. }
  20855. else {
  20856. relativeId = undefined;
  20857. }
  20858. }
  20859. else {
  20860. // not exposed
  20861. relativeId = undefined;
  20862. }
  20863. if (!relativeId) {
  20864. throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ` +
  20865. `${path$o.join(dir, 'package.json')}.`);
  20866. }
  20867. }
  20868. else if (targetWeb && options.browserField && isObject$2(browserField)) {
  20869. // resolve without postfix (see #7098)
  20870. const { file, postfix } = splitFileAndPostfix(relativeId);
  20871. const mapped = mapWithBrowserField(file, browserField);
  20872. if (mapped) {
  20873. relativeId = mapped + postfix;
  20874. }
  20875. else if (mapped === false) {
  20876. return (webResolvedImports[id] = browserExternalId);
  20877. }
  20878. }
  20879. if (relativeId) {
  20880. const resolved = tryFsResolve(path$o.join(dir, relativeId), options, !exportsField, // try index only if no exports field
  20881. targetWeb);
  20882. if (resolved) {
  20883. debug$d?.(`[node/deep-import] ${colors$1.cyan(id)} -> ${colors$1.dim(resolved)}`);
  20884. setResolvedCache(id, resolved, targetWeb);
  20885. return resolved;
  20886. }
  20887. }
  20888. }
  20889. function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) {
  20890. let res;
  20891. const pkg = importer &&
  20892. findNearestPackageData(path$o.dirname(importer), options.packageCache);
  20893. if (pkg && isObject$2(pkg.data.browser)) {
  20894. const mapId = isFilePath ? './' + slash$1(path$o.relative(pkg.dir, id)) : id;
  20895. const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
  20896. if (browserMappedPath) {
  20897. if ((res = bareImportRE.test(browserMappedPath)
  20898. ? tryNodeResolve(browserMappedPath, importer, options, true)?.id
  20899. : tryFsResolve(path$o.join(pkg.dir, browserMappedPath), options))) {
  20900. debug$d?.(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  20901. let result = { id: res };
  20902. if (options.idOnly) {
  20903. return result;
  20904. }
  20905. if (!options.scan && options.isBuild) {
  20906. const resPkg = findNearestPackageData(path$o.dirname(res), options.packageCache);
  20907. if (resPkg) {
  20908. result = {
  20909. id: res,
  20910. moduleSideEffects: resPkg.hasSideEffects(res),
  20911. };
  20912. }
  20913. }
  20914. return externalize ? { ...result, external: true } : result;
  20915. }
  20916. }
  20917. else if (browserMappedPath === false) {
  20918. return browserExternalId;
  20919. }
  20920. }
  20921. }
  20922. /**
  20923. * given a relative path in pkg dir,
  20924. * return a relative path in pkg dir,
  20925. * mapped with the "map" object
  20926. *
  20927. * - Returning `undefined` means there is no browser mapping for this id
  20928. * - Returning `false` means this id is explicitly externalized for browser
  20929. */
  20930. function mapWithBrowserField(relativePathInPkgDir, map) {
  20931. const normalizedPath = path$o.posix.normalize(relativePathInPkgDir);
  20932. for (const key in map) {
  20933. const normalizedKey = path$o.posix.normalize(key);
  20934. if (normalizedPath === normalizedKey ||
  20935. equalWithoutSuffix(normalizedPath, normalizedKey, '.js') ||
  20936. equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')) {
  20937. return map[key];
  20938. }
  20939. }
  20940. }
  20941. function equalWithoutSuffix(path, key, suffix) {
  20942. return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
  20943. }
  20944. function getRealPath(resolved, preserveSymlinks) {
  20945. if (!preserveSymlinks && browserExternalId !== resolved) {
  20946. resolved = safeRealpathSync(resolved);
  20947. }
  20948. return normalizePath$3(resolved);
  20949. }
  20950. const externalWithConversionNamespace = 'vite:dep-pre-bundle:external-conversion';
  20951. const convertedExternalPrefix = 'vite-dep-pre-bundle-external:';
  20952. const cjsExternalFacadeNamespace = 'vite:cjs-external-facade';
  20953. const nonFacadePrefix = 'vite-cjs-external-facade:';
  20954. const externalTypes = [
  20955. 'css',
  20956. // supported pre-processor types
  20957. 'less',
  20958. 'sass',
  20959. 'scss',
  20960. 'styl',
  20961. 'stylus',
  20962. 'pcss',
  20963. 'postcss',
  20964. // wasm
  20965. 'wasm',
  20966. // known SFC types
  20967. 'vue',
  20968. 'svelte',
  20969. 'marko',
  20970. 'astro',
  20971. 'imba',
  20972. // JSX/TSX may be configured to be compiled differently from how esbuild
  20973. // handles it by default, so exclude them as well
  20974. 'jsx',
  20975. 'tsx',
  20976. ...KNOWN_ASSET_TYPES,
  20977. ];
  20978. function esbuildDepPlugin(qualified, external, config, ssr) {
  20979. const { extensions } = getDepOptimizationConfig(config, ssr);
  20980. // remove optimizable extensions from `externalTypes` list
  20981. const allExternalTypes = extensions
  20982. ? externalTypes.filter((type) => !extensions?.includes('.' + type))
  20983. : externalTypes;
  20984. // use separate package cache for optimizer as it caches paths around node_modules
  20985. // and it's unlikely for the core Vite process to traverse into node_modules again
  20986. const esmPackageCache = new Map();
  20987. const cjsPackageCache = new Map();
  20988. // default resolver which prefers ESM
  20989. const _resolve = config.createResolver({
  20990. asSrc: false,
  20991. scan: true,
  20992. packageCache: esmPackageCache,
  20993. });
  20994. // cjs resolver that prefers Node
  20995. const _resolveRequire = config.createResolver({
  20996. asSrc: false,
  20997. isRequire: true,
  20998. scan: true,
  20999. packageCache: cjsPackageCache,
  21000. });
  21001. const resolve = (id, importer, kind, resolveDir) => {
  21002. let _importer;
  21003. // explicit resolveDir - this is passed only during yarn pnp resolve for
  21004. // entries
  21005. if (resolveDir) {
  21006. _importer = normalizePath$3(path$o.join(resolveDir, '*'));
  21007. }
  21008. else {
  21009. // map importer ids to file paths for correct resolution
  21010. _importer = importer in qualified ? qualified[importer] : importer;
  21011. }
  21012. const resolver = kind.startsWith('require') ? _resolveRequire : _resolve;
  21013. return resolver(id, _importer, undefined, ssr);
  21014. };
  21015. const resolveResult = (id, resolved) => {
  21016. if (resolved.startsWith(browserExternalId)) {
  21017. return {
  21018. path: id,
  21019. namespace: 'browser-external',
  21020. };
  21021. }
  21022. if (resolved.startsWith(optionalPeerDepId)) {
  21023. return {
  21024. path: resolved,
  21025. namespace: 'optional-peer-dep',
  21026. };
  21027. }
  21028. if (ssr && isBuiltin(resolved)) {
  21029. return;
  21030. }
  21031. if (isExternalUrl(resolved)) {
  21032. return {
  21033. path: resolved,
  21034. external: true,
  21035. };
  21036. }
  21037. return {
  21038. path: path$o.resolve(resolved),
  21039. };
  21040. };
  21041. return {
  21042. name: 'vite:dep-pre-bundle',
  21043. setup(build) {
  21044. // clear package cache when esbuild is finished
  21045. build.onEnd(() => {
  21046. esmPackageCache.clear();
  21047. cjsPackageCache.clear();
  21048. });
  21049. // externalize assets and commonly known non-js file types
  21050. // See #8459 for more details about this require-import conversion
  21051. build.onResolve({
  21052. filter: new RegExp(`\\.(` + allExternalTypes.join('|') + `)(\\?.*)?$`),
  21053. }, async ({ path: id, importer, kind }) => {
  21054. // if the prefix exist, it is already converted to `import`, so set `external: true`
  21055. if (id.startsWith(convertedExternalPrefix)) {
  21056. return {
  21057. path: id.slice(convertedExternalPrefix.length),
  21058. external: true,
  21059. };
  21060. }
  21061. const resolved = await resolve(id, importer, kind);
  21062. if (resolved) {
  21063. if (kind === 'require-call') {
  21064. // here it is not set to `external: true` to convert `require` to `import`
  21065. return {
  21066. path: resolved,
  21067. namespace: externalWithConversionNamespace,
  21068. };
  21069. }
  21070. return {
  21071. path: resolved,
  21072. external: true,
  21073. };
  21074. }
  21075. });
  21076. build.onLoad({ filter: /./, namespace: externalWithConversionNamespace }, (args) => {
  21077. // import itself with prefix (this is the actual part of require-import conversion)
  21078. const modulePath = `"${convertedExternalPrefix}${args.path}"`;
  21079. return {
  21080. contents: CSS_LANGS_RE.test(args.path)
  21081. ? `import ${modulePath};`
  21082. : `export { default } from ${modulePath};` +
  21083. `export * from ${modulePath};`,
  21084. loader: 'js',
  21085. };
  21086. });
  21087. function resolveEntry(id) {
  21088. const flatId = flattenId(id);
  21089. if (flatId in qualified) {
  21090. return {
  21091. path: qualified[flatId],
  21092. };
  21093. }
  21094. }
  21095. build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => {
  21096. if (moduleListContains(external, id)) {
  21097. return {
  21098. path: id,
  21099. external: true,
  21100. };
  21101. }
  21102. // ensure esbuild uses our resolved entries
  21103. let entry;
  21104. // if this is an entry, return entry namespace resolve result
  21105. if (!importer) {
  21106. if ((entry = resolveEntry(id)))
  21107. return entry;
  21108. // check if this is aliased to an entry - also return entry namespace
  21109. const aliased = await _resolve(id, undefined, true);
  21110. if (aliased && (entry = resolveEntry(aliased))) {
  21111. return entry;
  21112. }
  21113. }
  21114. // use vite's own resolver
  21115. const resolved = await resolve(id, importer, kind);
  21116. if (resolved) {
  21117. return resolveResult(id, resolved);
  21118. }
  21119. });
  21120. build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path }) => {
  21121. if (config.isProduction) {
  21122. return {
  21123. contents: 'module.exports = {}',
  21124. };
  21125. }
  21126. else {
  21127. return {
  21128. // Return in CJS to intercept named imports. Use `Object.create` to
  21129. // create the Proxy in the prototype to workaround esbuild issue. Why?
  21130. //
  21131. // In short, esbuild cjs->esm flow:
  21132. // 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`.
  21133. // 2. Assign props of `module.exports` to the object.
  21134. // 3. Return object for ESM use.
  21135. //
  21136. // If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object,
  21137. // step 2 does nothing as there's no props for `module.exports`. The final object
  21138. // is just an empty object.
  21139. //
  21140. // Creating the Proxy in the prototype satisfies step 1 immediately, which means
  21141. // the returned object is a Proxy that we can intercept.
  21142. //
  21143. // Note: Skip keys that are accessed by esbuild and browser devtools.
  21144. contents: `\
  21145. module.exports = Object.create(new Proxy({}, {
  21146. get(_, key) {
  21147. if (
  21148. key !== '__esModule' &&
  21149. key !== '__proto__' &&
  21150. key !== 'constructor' &&
  21151. key !== 'splice'
  21152. ) {
  21153. console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
  21154. }
  21155. }
  21156. }))`,
  21157. };
  21158. }
  21159. });
  21160. build.onLoad({ filter: /.*/, namespace: 'optional-peer-dep' }, ({ path }) => {
  21161. if (config.isProduction) {
  21162. return {
  21163. contents: 'module.exports = {}',
  21164. };
  21165. }
  21166. else {
  21167. const [, peerDep, parentDep] = path.split(':');
  21168. return {
  21169. contents: `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`,
  21170. };
  21171. }
  21172. });
  21173. },
  21174. };
  21175. }
  21176. const matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
  21177. // esbuild doesn't transpile `require('foo')` into `import` statements if 'foo' is externalized
  21178. // https://github.com/evanw/esbuild/issues/566#issuecomment-735551834
  21179. function esbuildCjsExternalPlugin(externals, platform) {
  21180. return {
  21181. name: 'cjs-external',
  21182. setup(build) {
  21183. const filter = new RegExp(externals.map(matchesEntireLine).join('|'));
  21184. build.onResolve({ filter: new RegExp(`^${nonFacadePrefix}`) }, (args) => {
  21185. return {
  21186. path: args.path.slice(nonFacadePrefix.length),
  21187. external: true,
  21188. };
  21189. });
  21190. build.onResolve({ filter }, (args) => {
  21191. // preserve `require` for node because it's more accurate than converting it to import
  21192. if (args.kind === 'require-call' && platform !== 'node') {
  21193. return {
  21194. path: args.path,
  21195. namespace: cjsExternalFacadeNamespace,
  21196. };
  21197. }
  21198. return {
  21199. path: args.path,
  21200. external: true,
  21201. };
  21202. });
  21203. build.onLoad({ filter: /.*/, namespace: cjsExternalFacadeNamespace }, (args) => ({
  21204. contents: `import * as m from ${JSON.stringify(nonFacadePrefix + args.path)};` + `module.exports = m;`,
  21205. }));
  21206. },
  21207. };
  21208. }
  21209. var tasks = {};
  21210. var utils$g = {};
  21211. var array$1 = {};
  21212. Object.defineProperty(array$1, "__esModule", { value: true });
  21213. array$1.splitWhen = array$1.flatten = void 0;
  21214. function flatten$1(items) {
  21215. return items.reduce((collection, item) => [].concat(collection, item), []);
  21216. }
  21217. array$1.flatten = flatten$1;
  21218. function splitWhen(items, predicate) {
  21219. const result = [[]];
  21220. let groupIndex = 0;
  21221. for (const item of items) {
  21222. if (predicate(item)) {
  21223. groupIndex++;
  21224. result[groupIndex] = [];
  21225. }
  21226. else {
  21227. result[groupIndex].push(item);
  21228. }
  21229. }
  21230. return result;
  21231. }
  21232. array$1.splitWhen = splitWhen;
  21233. var errno$1 = {};
  21234. Object.defineProperty(errno$1, "__esModule", { value: true });
  21235. errno$1.isEnoentCodeError = void 0;
  21236. function isEnoentCodeError(error) {
  21237. return error.code === 'ENOENT';
  21238. }
  21239. errno$1.isEnoentCodeError = isEnoentCodeError;
  21240. var fs$h = {};
  21241. Object.defineProperty(fs$h, "__esModule", { value: true });
  21242. fs$h.createDirentFromStats = void 0;
  21243. let DirentFromStats$1 = class DirentFromStats {
  21244. constructor(name, stats) {
  21245. this.name = name;
  21246. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  21247. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  21248. this.isDirectory = stats.isDirectory.bind(stats);
  21249. this.isFIFO = stats.isFIFO.bind(stats);
  21250. this.isFile = stats.isFile.bind(stats);
  21251. this.isSocket = stats.isSocket.bind(stats);
  21252. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  21253. }
  21254. };
  21255. function createDirentFromStats$1(name, stats) {
  21256. return new DirentFromStats$1(name, stats);
  21257. }
  21258. fs$h.createDirentFromStats = createDirentFromStats$1;
  21259. var path$h = {};
  21260. Object.defineProperty(path$h, "__esModule", { value: true });
  21261. path$h.removeLeadingDotSegment = path$h.escape = path$h.makeAbsolute = path$h.unixify = void 0;
  21262. const path$g = require$$0$4;
  21263. const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
  21264. const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
  21265. /**
  21266. * Designed to work only with simple paths: `dir\\file`.
  21267. */
  21268. function unixify(filepath) {
  21269. return filepath.replace(/\\/g, '/');
  21270. }
  21271. path$h.unixify = unixify;
  21272. function makeAbsolute(cwd, filepath) {
  21273. return path$g.resolve(cwd, filepath);
  21274. }
  21275. path$h.makeAbsolute = makeAbsolute;
  21276. function escape$2(pattern) {
  21277. return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
  21278. }
  21279. path$h.escape = escape$2;
  21280. function removeLeadingDotSegment(entry) {
  21281. // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
  21282. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  21283. if (entry.charAt(0) === '.') {
  21284. const secondCharactery = entry.charAt(1);
  21285. if (secondCharactery === '/' || secondCharactery === '\\') {
  21286. return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
  21287. }
  21288. }
  21289. return entry;
  21290. }
  21291. path$h.removeLeadingDotSegment = removeLeadingDotSegment;
  21292. var pattern$1 = {};
  21293. /*!
  21294. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  21295. *
  21296. * Copyright (c) 2014-2016, Jon Schlinkert.
  21297. * Licensed under the MIT License.
  21298. */
  21299. var isExtglob$1 = function isExtglob(str) {
  21300. if (typeof str !== 'string' || str === '') {
  21301. return false;
  21302. }
  21303. var match;
  21304. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  21305. if (match[2]) return true;
  21306. str = str.slice(match.index + match[0].length);
  21307. }
  21308. return false;
  21309. };
  21310. /*!
  21311. * is-glob <https://github.com/jonschlinkert/is-glob>
  21312. *
  21313. * Copyright (c) 2014-2017, Jon Schlinkert.
  21314. * Released under the MIT License.
  21315. */
  21316. var isExtglob = isExtglob$1;
  21317. var chars = { '{': '}', '(': ')', '[': ']'};
  21318. var strictCheck = function(str) {
  21319. if (str[0] === '!') {
  21320. return true;
  21321. }
  21322. var index = 0;
  21323. var pipeIndex = -2;
  21324. var closeSquareIndex = -2;
  21325. var closeCurlyIndex = -2;
  21326. var closeParenIndex = -2;
  21327. var backSlashIndex = -2;
  21328. while (index < str.length) {
  21329. if (str[index] === '*') {
  21330. return true;
  21331. }
  21332. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  21333. return true;
  21334. }
  21335. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  21336. if (closeSquareIndex < index) {
  21337. closeSquareIndex = str.indexOf(']', index);
  21338. }
  21339. if (closeSquareIndex > index) {
  21340. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  21341. return true;
  21342. }
  21343. backSlashIndex = str.indexOf('\\', index);
  21344. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  21345. return true;
  21346. }
  21347. }
  21348. }
  21349. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  21350. closeCurlyIndex = str.indexOf('}', index);
  21351. if (closeCurlyIndex > index) {
  21352. backSlashIndex = str.indexOf('\\', index);
  21353. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  21354. return true;
  21355. }
  21356. }
  21357. }
  21358. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  21359. closeParenIndex = str.indexOf(')', index);
  21360. if (closeParenIndex > index) {
  21361. backSlashIndex = str.indexOf('\\', index);
  21362. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  21363. return true;
  21364. }
  21365. }
  21366. }
  21367. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  21368. if (pipeIndex < index) {
  21369. pipeIndex = str.indexOf('|', index);
  21370. }
  21371. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  21372. closeParenIndex = str.indexOf(')', pipeIndex);
  21373. if (closeParenIndex > pipeIndex) {
  21374. backSlashIndex = str.indexOf('\\', pipeIndex);
  21375. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  21376. return true;
  21377. }
  21378. }
  21379. }
  21380. }
  21381. if (str[index] === '\\') {
  21382. var open = str[index + 1];
  21383. index += 2;
  21384. var close = chars[open];
  21385. if (close) {
  21386. var n = str.indexOf(close, index);
  21387. if (n !== -1) {
  21388. index = n + 1;
  21389. }
  21390. }
  21391. if (str[index] === '!') {
  21392. return true;
  21393. }
  21394. } else {
  21395. index++;
  21396. }
  21397. }
  21398. return false;
  21399. };
  21400. var relaxedCheck = function(str) {
  21401. if (str[0] === '!') {
  21402. return true;
  21403. }
  21404. var index = 0;
  21405. while (index < str.length) {
  21406. if (/[*?{}()[\]]/.test(str[index])) {
  21407. return true;
  21408. }
  21409. if (str[index] === '\\') {
  21410. var open = str[index + 1];
  21411. index += 2;
  21412. var close = chars[open];
  21413. if (close) {
  21414. var n = str.indexOf(close, index);
  21415. if (n !== -1) {
  21416. index = n + 1;
  21417. }
  21418. }
  21419. if (str[index] === '!') {
  21420. return true;
  21421. }
  21422. } else {
  21423. index++;
  21424. }
  21425. }
  21426. return false;
  21427. };
  21428. var isGlob$2 = function isGlob(str, options) {
  21429. if (typeof str !== 'string' || str === '') {
  21430. return false;
  21431. }
  21432. if (isExtglob(str)) {
  21433. return true;
  21434. }
  21435. var check = strictCheck;
  21436. // optionally relax check
  21437. if (options && options.strict === false) {
  21438. check = relaxedCheck;
  21439. }
  21440. return check(str);
  21441. };
  21442. var isGlob$1 = isGlob$2;
  21443. var pathPosixDirname = require$$0$4.posix.dirname;
  21444. var isWin32 = require$$2.platform() === 'win32';
  21445. var slash = '/';
  21446. var backslash = /\\/g;
  21447. var enclosure = /[\{\[].*[\}\]]$/;
  21448. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  21449. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  21450. /**
  21451. * @param {string} str
  21452. * @param {Object} opts
  21453. * @param {boolean} [opts.flipBackslashes=true]
  21454. * @returns {string}
  21455. */
  21456. var globParent$2 = function globParent(str, opts) {
  21457. var options = Object.assign({ flipBackslashes: true }, opts);
  21458. // flip windows path separators
  21459. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  21460. str = str.replace(backslash, slash);
  21461. }
  21462. // special case for strings ending in enclosure containing path separator
  21463. if (enclosure.test(str)) {
  21464. str += slash;
  21465. }
  21466. // preserves full path in case of trailing path separator
  21467. str += 'a';
  21468. // remove path parts that are globby
  21469. do {
  21470. str = pathPosixDirname(str);
  21471. } while (isGlob$1(str) || globby.test(str));
  21472. // remove escape chars and return result
  21473. return str.replace(escaped, '$1');
  21474. };
  21475. var utils$f = {};
  21476. (function (exports) {
  21477. exports.isInteger = num => {
  21478. if (typeof num === 'number') {
  21479. return Number.isInteger(num);
  21480. }
  21481. if (typeof num === 'string' && num.trim() !== '') {
  21482. return Number.isInteger(Number(num));
  21483. }
  21484. return false;
  21485. };
  21486. /**
  21487. * Find a node of the given type
  21488. */
  21489. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  21490. /**
  21491. * Find a node of the given type
  21492. */
  21493. exports.exceedsLimit = (min, max, step = 1, limit) => {
  21494. if (limit === false) return false;
  21495. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  21496. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  21497. };
  21498. /**
  21499. * Escape the given node with '\\' before node.value
  21500. */
  21501. exports.escapeNode = (block, n = 0, type) => {
  21502. let node = block.nodes[n];
  21503. if (!node) return;
  21504. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  21505. if (node.escaped !== true) {
  21506. node.value = '\\' + node.value;
  21507. node.escaped = true;
  21508. }
  21509. }
  21510. };
  21511. /**
  21512. * Returns true if the given brace node should be enclosed in literal braces
  21513. */
  21514. exports.encloseBrace = node => {
  21515. if (node.type !== 'brace') return false;
  21516. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  21517. node.invalid = true;
  21518. return true;
  21519. }
  21520. return false;
  21521. };
  21522. /**
  21523. * Returns true if a brace node is invalid.
  21524. */
  21525. exports.isInvalidBrace = block => {
  21526. if (block.type !== 'brace') return false;
  21527. if (block.invalid === true || block.dollar) return true;
  21528. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  21529. block.invalid = true;
  21530. return true;
  21531. }
  21532. if (block.open !== true || block.close !== true) {
  21533. block.invalid = true;
  21534. return true;
  21535. }
  21536. return false;
  21537. };
  21538. /**
  21539. * Returns true if a node is an open or close node
  21540. */
  21541. exports.isOpenOrClose = node => {
  21542. if (node.type === 'open' || node.type === 'close') {
  21543. return true;
  21544. }
  21545. return node.open === true || node.close === true;
  21546. };
  21547. /**
  21548. * Reduce an array of text nodes.
  21549. */
  21550. exports.reduce = nodes => nodes.reduce((acc, node) => {
  21551. if (node.type === 'text') acc.push(node.value);
  21552. if (node.type === 'range') node.type = 'text';
  21553. return acc;
  21554. }, []);
  21555. /**
  21556. * Flatten an array
  21557. */
  21558. exports.flatten = (...args) => {
  21559. const result = [];
  21560. const flat = arr => {
  21561. for (let i = 0; i < arr.length; i++) {
  21562. let ele = arr[i];
  21563. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  21564. }
  21565. return result;
  21566. };
  21567. flat(args);
  21568. return result;
  21569. };
  21570. } (utils$f));
  21571. const utils$e = utils$f;
  21572. var stringify$7 = (ast, options = {}) => {
  21573. let stringify = (node, parent = {}) => {
  21574. let invalidBlock = options.escapeInvalid && utils$e.isInvalidBrace(parent);
  21575. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  21576. let output = '';
  21577. if (node.value) {
  21578. if ((invalidBlock || invalidNode) && utils$e.isOpenOrClose(node)) {
  21579. return '\\' + node.value;
  21580. }
  21581. return node.value;
  21582. }
  21583. if (node.value) {
  21584. return node.value;
  21585. }
  21586. if (node.nodes) {
  21587. for (let child of node.nodes) {
  21588. output += stringify(child);
  21589. }
  21590. }
  21591. return output;
  21592. };
  21593. return stringify(ast);
  21594. };
  21595. /*!
  21596. * is-number <https://github.com/jonschlinkert/is-number>
  21597. *
  21598. * Copyright (c) 2014-present, Jon Schlinkert.
  21599. * Released under the MIT License.
  21600. */
  21601. var isNumber$2 = function(num) {
  21602. if (typeof num === 'number') {
  21603. return num - num === 0;
  21604. }
  21605. if (typeof num === 'string' && num.trim() !== '') {
  21606. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  21607. }
  21608. return false;
  21609. };
  21610. /*!
  21611. * to-regex-range <https://github.com/micromatch/to-regex-range>
  21612. *
  21613. * Copyright (c) 2015-present, Jon Schlinkert.
  21614. * Released under the MIT License.
  21615. */
  21616. const isNumber$1 = isNumber$2;
  21617. const toRegexRange$1 = (min, max, options) => {
  21618. if (isNumber$1(min) === false) {
  21619. throw new TypeError('toRegexRange: expected the first argument to be a number');
  21620. }
  21621. if (max === void 0 || min === max) {
  21622. return String(min);
  21623. }
  21624. if (isNumber$1(max) === false) {
  21625. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  21626. }
  21627. let opts = { relaxZeros: true, ...options };
  21628. if (typeof opts.strictZeros === 'boolean') {
  21629. opts.relaxZeros = opts.strictZeros === false;
  21630. }
  21631. let relax = String(opts.relaxZeros);
  21632. let shorthand = String(opts.shorthand);
  21633. let capture = String(opts.capture);
  21634. let wrap = String(opts.wrap);
  21635. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  21636. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  21637. return toRegexRange$1.cache[cacheKey].result;
  21638. }
  21639. let a = Math.min(min, max);
  21640. let b = Math.max(min, max);
  21641. if (Math.abs(a - b) === 1) {
  21642. let result = min + '|' + max;
  21643. if (opts.capture) {
  21644. return `(${result})`;
  21645. }
  21646. if (opts.wrap === false) {
  21647. return result;
  21648. }
  21649. return `(?:${result})`;
  21650. }
  21651. let isPadded = hasPadding(min) || hasPadding(max);
  21652. let state = { min, max, a, b };
  21653. let positives = [];
  21654. let negatives = [];
  21655. if (isPadded) {
  21656. state.isPadded = isPadded;
  21657. state.maxLen = String(state.max).length;
  21658. }
  21659. if (a < 0) {
  21660. let newMin = b < 0 ? Math.abs(b) : 1;
  21661. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  21662. a = state.a = 0;
  21663. }
  21664. if (b >= 0) {
  21665. positives = splitToPatterns(a, b, state, opts);
  21666. }
  21667. state.negatives = negatives;
  21668. state.positives = positives;
  21669. state.result = collatePatterns(negatives, positives);
  21670. if (opts.capture === true) {
  21671. state.result = `(${state.result})`;
  21672. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  21673. state.result = `(?:${state.result})`;
  21674. }
  21675. toRegexRange$1.cache[cacheKey] = state;
  21676. return state.result;
  21677. };
  21678. function collatePatterns(neg, pos, options) {
  21679. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  21680. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  21681. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  21682. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  21683. return subpatterns.join('|');
  21684. }
  21685. function splitToRanges(min, max) {
  21686. let nines = 1;
  21687. let zeros = 1;
  21688. let stop = countNines(min, nines);
  21689. let stops = new Set([max]);
  21690. while (min <= stop && stop <= max) {
  21691. stops.add(stop);
  21692. nines += 1;
  21693. stop = countNines(min, nines);
  21694. }
  21695. stop = countZeros(max + 1, zeros) - 1;
  21696. while (min < stop && stop <= max) {
  21697. stops.add(stop);
  21698. zeros += 1;
  21699. stop = countZeros(max + 1, zeros) - 1;
  21700. }
  21701. stops = [...stops];
  21702. stops.sort(compare);
  21703. return stops;
  21704. }
  21705. /**
  21706. * Convert a range to a regex pattern
  21707. * @param {Number} `start`
  21708. * @param {Number} `stop`
  21709. * @return {String}
  21710. */
  21711. function rangeToPattern(start, stop, options) {
  21712. if (start === stop) {
  21713. return { pattern: start, count: [], digits: 0 };
  21714. }
  21715. let zipped = zip(start, stop);
  21716. let digits = zipped.length;
  21717. let pattern = '';
  21718. let count = 0;
  21719. for (let i = 0; i < digits; i++) {
  21720. let [startDigit, stopDigit] = zipped[i];
  21721. if (startDigit === stopDigit) {
  21722. pattern += startDigit;
  21723. } else if (startDigit !== '0' || stopDigit !== '9') {
  21724. pattern += toCharacterClass(startDigit, stopDigit);
  21725. } else {
  21726. count++;
  21727. }
  21728. }
  21729. if (count) {
  21730. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  21731. }
  21732. return { pattern, count: [count], digits };
  21733. }
  21734. function splitToPatterns(min, max, tok, options) {
  21735. let ranges = splitToRanges(min, max);
  21736. let tokens = [];
  21737. let start = min;
  21738. let prev;
  21739. for (let i = 0; i < ranges.length; i++) {
  21740. let max = ranges[i];
  21741. let obj = rangeToPattern(String(start), String(max), options);
  21742. let zeros = '';
  21743. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  21744. if (prev.count.length > 1) {
  21745. prev.count.pop();
  21746. }
  21747. prev.count.push(obj.count[0]);
  21748. prev.string = prev.pattern + toQuantifier(prev.count);
  21749. start = max + 1;
  21750. continue;
  21751. }
  21752. if (tok.isPadded) {
  21753. zeros = padZeros(max, tok, options);
  21754. }
  21755. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  21756. tokens.push(obj);
  21757. start = max + 1;
  21758. prev = obj;
  21759. }
  21760. return tokens;
  21761. }
  21762. function filterPatterns(arr, comparison, prefix, intersection, options) {
  21763. let result = [];
  21764. for (let ele of arr) {
  21765. let { string } = ele;
  21766. // only push if _both_ are negative...
  21767. if (!intersection && !contains(comparison, 'string', string)) {
  21768. result.push(prefix + string);
  21769. }
  21770. // or _both_ are positive
  21771. if (intersection && contains(comparison, 'string', string)) {
  21772. result.push(prefix + string);
  21773. }
  21774. }
  21775. return result;
  21776. }
  21777. /**
  21778. * Zip strings
  21779. */
  21780. function zip(a, b) {
  21781. let arr = [];
  21782. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  21783. return arr;
  21784. }
  21785. function compare(a, b) {
  21786. return a > b ? 1 : b > a ? -1 : 0;
  21787. }
  21788. function contains(arr, key, val) {
  21789. return arr.some(ele => ele[key] === val);
  21790. }
  21791. function countNines(min, len) {
  21792. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  21793. }
  21794. function countZeros(integer, zeros) {
  21795. return integer - (integer % Math.pow(10, zeros));
  21796. }
  21797. function toQuantifier(digits) {
  21798. let [start = 0, stop = ''] = digits;
  21799. if (stop || start > 1) {
  21800. return `{${start + (stop ? ',' + stop : '')}}`;
  21801. }
  21802. return '';
  21803. }
  21804. function toCharacterClass(a, b, options) {
  21805. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  21806. }
  21807. function hasPadding(str) {
  21808. return /^-?(0+)\d/.test(str);
  21809. }
  21810. function padZeros(value, tok, options) {
  21811. if (!tok.isPadded) {
  21812. return value;
  21813. }
  21814. let diff = Math.abs(tok.maxLen - String(value).length);
  21815. let relax = options.relaxZeros !== false;
  21816. switch (diff) {
  21817. case 0:
  21818. return '';
  21819. case 1:
  21820. return relax ? '0?' : '0';
  21821. case 2:
  21822. return relax ? '0{0,2}' : '00';
  21823. default: {
  21824. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  21825. }
  21826. }
  21827. }
  21828. /**
  21829. * Cache
  21830. */
  21831. toRegexRange$1.cache = {};
  21832. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  21833. /**
  21834. * Expose `toRegexRange`
  21835. */
  21836. var toRegexRange_1 = toRegexRange$1;
  21837. /*!
  21838. * fill-range <https://github.com/jonschlinkert/fill-range>
  21839. *
  21840. * Copyright (c) 2014-present, Jon Schlinkert.
  21841. * Licensed under the MIT License.
  21842. */
  21843. const util$1 = require$$0$6;
  21844. const toRegexRange = toRegexRange_1;
  21845. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  21846. const transform$1 = toNumber => {
  21847. return value => toNumber === true ? Number(value) : String(value);
  21848. };
  21849. const isValidValue = value => {
  21850. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  21851. };
  21852. const isNumber = num => Number.isInteger(+num);
  21853. const zeros = input => {
  21854. let value = `${input}`;
  21855. let index = -1;
  21856. if (value[0] === '-') value = value.slice(1);
  21857. if (value === '0') return false;
  21858. while (value[++index] === '0');
  21859. return index > 0;
  21860. };
  21861. const stringify$6 = (start, end, options) => {
  21862. if (typeof start === 'string' || typeof end === 'string') {
  21863. return true;
  21864. }
  21865. return options.stringify === true;
  21866. };
  21867. const pad = (input, maxLength, toNumber) => {
  21868. if (maxLength > 0) {
  21869. let dash = input[0] === '-' ? '-' : '';
  21870. if (dash) input = input.slice(1);
  21871. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  21872. }
  21873. if (toNumber === false) {
  21874. return String(input);
  21875. }
  21876. return input;
  21877. };
  21878. const toMaxLen = (input, maxLength) => {
  21879. let negative = input[0] === '-' ? '-' : '';
  21880. if (negative) {
  21881. input = input.slice(1);
  21882. maxLength--;
  21883. }
  21884. while (input.length < maxLength) input = '0' + input;
  21885. return negative ? ('-' + input) : input;
  21886. };
  21887. const toSequence = (parts, options) => {
  21888. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  21889. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  21890. let prefix = options.capture ? '' : '?:';
  21891. let positives = '';
  21892. let negatives = '';
  21893. let result;
  21894. if (parts.positives.length) {
  21895. positives = parts.positives.join('|');
  21896. }
  21897. if (parts.negatives.length) {
  21898. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  21899. }
  21900. if (positives && negatives) {
  21901. result = `${positives}|${negatives}`;
  21902. } else {
  21903. result = positives || negatives;
  21904. }
  21905. if (options.wrap) {
  21906. return `(${prefix}${result})`;
  21907. }
  21908. return result;
  21909. };
  21910. const toRange = (a, b, isNumbers, options) => {
  21911. if (isNumbers) {
  21912. return toRegexRange(a, b, { wrap: false, ...options });
  21913. }
  21914. let start = String.fromCharCode(a);
  21915. if (a === b) return start;
  21916. let stop = String.fromCharCode(b);
  21917. return `[${start}-${stop}]`;
  21918. };
  21919. const toRegex = (start, end, options) => {
  21920. if (Array.isArray(start)) {
  21921. let wrap = options.wrap === true;
  21922. let prefix = options.capture ? '' : '?:';
  21923. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  21924. }
  21925. return toRegexRange(start, end, options);
  21926. };
  21927. const rangeError = (...args) => {
  21928. return new RangeError('Invalid range arguments: ' + util$1.inspect(...args));
  21929. };
  21930. const invalidRange = (start, end, options) => {
  21931. if (options.strictRanges === true) throw rangeError([start, end]);
  21932. return [];
  21933. };
  21934. const invalidStep = (step, options) => {
  21935. if (options.strictRanges === true) {
  21936. throw new TypeError(`Expected step "${step}" to be a number`);
  21937. }
  21938. return [];
  21939. };
  21940. const fillNumbers = (start, end, step = 1, options = {}) => {
  21941. let a = Number(start);
  21942. let b = Number(end);
  21943. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  21944. if (options.strictRanges === true) throw rangeError([start, end]);
  21945. return [];
  21946. }
  21947. // fix negative zero
  21948. if (a === 0) a = 0;
  21949. if (b === 0) b = 0;
  21950. let descending = a > b;
  21951. let startString = String(start);
  21952. let endString = String(end);
  21953. let stepString = String(step);
  21954. step = Math.max(Math.abs(step), 1);
  21955. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  21956. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  21957. let toNumber = padded === false && stringify$6(start, end, options) === false;
  21958. let format = options.transform || transform$1(toNumber);
  21959. if (options.toRegex && step === 1) {
  21960. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  21961. }
  21962. let parts = { negatives: [], positives: [] };
  21963. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  21964. let range = [];
  21965. let index = 0;
  21966. while (descending ? a >= b : a <= b) {
  21967. if (options.toRegex === true && step > 1) {
  21968. push(a);
  21969. } else {
  21970. range.push(pad(format(a, index), maxLen, toNumber));
  21971. }
  21972. a = descending ? a - step : a + step;
  21973. index++;
  21974. }
  21975. if (options.toRegex === true) {
  21976. return step > 1
  21977. ? toSequence(parts, options)
  21978. : toRegex(range, null, { wrap: false, ...options });
  21979. }
  21980. return range;
  21981. };
  21982. const fillLetters = (start, end, step = 1, options = {}) => {
  21983. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  21984. return invalidRange(start, end, options);
  21985. }
  21986. let format = options.transform || (val => String.fromCharCode(val));
  21987. let a = `${start}`.charCodeAt(0);
  21988. let b = `${end}`.charCodeAt(0);
  21989. let descending = a > b;
  21990. let min = Math.min(a, b);
  21991. let max = Math.max(a, b);
  21992. if (options.toRegex && step === 1) {
  21993. return toRange(min, max, false, options);
  21994. }
  21995. let range = [];
  21996. let index = 0;
  21997. while (descending ? a >= b : a <= b) {
  21998. range.push(format(a, index));
  21999. a = descending ? a - step : a + step;
  22000. index++;
  22001. }
  22002. if (options.toRegex === true) {
  22003. return toRegex(range, null, { wrap: false, options });
  22004. }
  22005. return range;
  22006. };
  22007. const fill$2 = (start, end, step, options = {}) => {
  22008. if (end == null && isValidValue(start)) {
  22009. return [start];
  22010. }
  22011. if (!isValidValue(start) || !isValidValue(end)) {
  22012. return invalidRange(start, end, options);
  22013. }
  22014. if (typeof step === 'function') {
  22015. return fill$2(start, end, 1, { transform: step });
  22016. }
  22017. if (isObject(step)) {
  22018. return fill$2(start, end, 0, step);
  22019. }
  22020. let opts = { ...options };
  22021. if (opts.capture === true) opts.wrap = true;
  22022. step = step || opts.step || 1;
  22023. if (!isNumber(step)) {
  22024. if (step != null && !isObject(step)) return invalidStep(step, opts);
  22025. return fill$2(start, end, 1, step);
  22026. }
  22027. if (isNumber(start) && isNumber(end)) {
  22028. return fillNumbers(start, end, step, opts);
  22029. }
  22030. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  22031. };
  22032. var fillRange = fill$2;
  22033. const fill$1 = fillRange;
  22034. const utils$d = utils$f;
  22035. const compile$1 = (ast, options = {}) => {
  22036. let walk = (node, parent = {}) => {
  22037. let invalidBlock = utils$d.isInvalidBrace(parent);
  22038. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  22039. let invalid = invalidBlock === true || invalidNode === true;
  22040. let prefix = options.escapeInvalid === true ? '\\' : '';
  22041. let output = '';
  22042. if (node.isOpen === true) {
  22043. return prefix + node.value;
  22044. }
  22045. if (node.isClose === true) {
  22046. return prefix + node.value;
  22047. }
  22048. if (node.type === 'open') {
  22049. return invalid ? (prefix + node.value) : '(';
  22050. }
  22051. if (node.type === 'close') {
  22052. return invalid ? (prefix + node.value) : ')';
  22053. }
  22054. if (node.type === 'comma') {
  22055. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  22056. }
  22057. if (node.value) {
  22058. return node.value;
  22059. }
  22060. if (node.nodes && node.ranges > 0) {
  22061. let args = utils$d.reduce(node.nodes);
  22062. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  22063. if (range.length !== 0) {
  22064. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  22065. }
  22066. }
  22067. if (node.nodes) {
  22068. for (let child of node.nodes) {
  22069. output += walk(child, node);
  22070. }
  22071. }
  22072. return output;
  22073. };
  22074. return walk(ast);
  22075. };
  22076. var compile_1 = compile$1;
  22077. const fill = fillRange;
  22078. const stringify$5 = stringify$7;
  22079. const utils$c = utils$f;
  22080. const append$1 = (queue = '', stash = '', enclose = false) => {
  22081. let result = [];
  22082. queue = [].concat(queue);
  22083. stash = [].concat(stash);
  22084. if (!stash.length) return queue;
  22085. if (!queue.length) {
  22086. return enclose ? utils$c.flatten(stash).map(ele => `{${ele}}`) : stash;
  22087. }
  22088. for (let item of queue) {
  22089. if (Array.isArray(item)) {
  22090. for (let value of item) {
  22091. result.push(append$1(value, stash, enclose));
  22092. }
  22093. } else {
  22094. for (let ele of stash) {
  22095. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  22096. result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele));
  22097. }
  22098. }
  22099. }
  22100. return utils$c.flatten(result);
  22101. };
  22102. const expand$2 = (ast, options = {}) => {
  22103. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  22104. let walk = (node, parent = {}) => {
  22105. node.queue = [];
  22106. let p = parent;
  22107. let q = parent.queue;
  22108. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  22109. p = p.parent;
  22110. q = p.queue;
  22111. }
  22112. if (node.invalid || node.dollar) {
  22113. q.push(append$1(q.pop(), stringify$5(node, options)));
  22114. return;
  22115. }
  22116. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  22117. q.push(append$1(q.pop(), ['{}']));
  22118. return;
  22119. }
  22120. if (node.nodes && node.ranges > 0) {
  22121. let args = utils$c.reduce(node.nodes);
  22122. if (utils$c.exceedsLimit(...args, options.step, rangeLimit)) {
  22123. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  22124. }
  22125. let range = fill(...args, options);
  22126. if (range.length === 0) {
  22127. range = stringify$5(node, options);
  22128. }
  22129. q.push(append$1(q.pop(), range));
  22130. node.nodes = [];
  22131. return;
  22132. }
  22133. let enclose = utils$c.encloseBrace(node);
  22134. let queue = node.queue;
  22135. let block = node;
  22136. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  22137. block = block.parent;
  22138. queue = block.queue;
  22139. }
  22140. for (let i = 0; i < node.nodes.length; i++) {
  22141. let child = node.nodes[i];
  22142. if (child.type === 'comma' && node.type === 'brace') {
  22143. if (i === 1) queue.push('');
  22144. queue.push('');
  22145. continue;
  22146. }
  22147. if (child.type === 'close') {
  22148. q.push(append$1(q.pop(), queue, enclose));
  22149. continue;
  22150. }
  22151. if (child.value && child.type !== 'open') {
  22152. queue.push(append$1(queue.pop(), child.value));
  22153. continue;
  22154. }
  22155. if (child.nodes) {
  22156. walk(child, node);
  22157. }
  22158. }
  22159. return queue;
  22160. };
  22161. return utils$c.flatten(walk(ast));
  22162. };
  22163. var expand_1$1 = expand$2;
  22164. var constants$3 = {
  22165. MAX_LENGTH: 1024 * 64,
  22166. // Digits
  22167. CHAR_0: '0', /* 0 */
  22168. CHAR_9: '9', /* 9 */
  22169. // Alphabet chars.
  22170. CHAR_UPPERCASE_A: 'A', /* A */
  22171. CHAR_LOWERCASE_A: 'a', /* a */
  22172. CHAR_UPPERCASE_Z: 'Z', /* Z */
  22173. CHAR_LOWERCASE_Z: 'z', /* z */
  22174. CHAR_LEFT_PARENTHESES: '(', /* ( */
  22175. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  22176. CHAR_ASTERISK: '*', /* * */
  22177. // Non-alphabetic chars.
  22178. CHAR_AMPERSAND: '&', /* & */
  22179. CHAR_AT: '@', /* @ */
  22180. CHAR_BACKSLASH: '\\', /* \ */
  22181. CHAR_BACKTICK: '`', /* ` */
  22182. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  22183. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  22184. CHAR_COLON: ':', /* : */
  22185. CHAR_COMMA: ',', /* , */
  22186. CHAR_DOLLAR: '$', /* . */
  22187. CHAR_DOT: '.', /* . */
  22188. CHAR_DOUBLE_QUOTE: '"', /* " */
  22189. CHAR_EQUAL: '=', /* = */
  22190. CHAR_EXCLAMATION_MARK: '!', /* ! */
  22191. CHAR_FORM_FEED: '\f', /* \f */
  22192. CHAR_FORWARD_SLASH: '/', /* / */
  22193. CHAR_HASH: '#', /* # */
  22194. CHAR_HYPHEN_MINUS: '-', /* - */
  22195. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  22196. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  22197. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  22198. CHAR_LINE_FEED: '\n', /* \n */
  22199. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  22200. CHAR_PERCENT: '%', /* % */
  22201. CHAR_PLUS: '+', /* + */
  22202. CHAR_QUESTION_MARK: '?', /* ? */
  22203. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  22204. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  22205. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  22206. CHAR_SEMICOLON: ';', /* ; */
  22207. CHAR_SINGLE_QUOTE: '\'', /* ' */
  22208. CHAR_SPACE: ' ', /* */
  22209. CHAR_TAB: '\t', /* \t */
  22210. CHAR_UNDERSCORE: '_', /* _ */
  22211. CHAR_VERTICAL_LINE: '|', /* | */
  22212. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  22213. };
  22214. const stringify$4 = stringify$7;
  22215. /**
  22216. * Constants
  22217. */
  22218. const {
  22219. MAX_LENGTH,
  22220. CHAR_BACKSLASH, /* \ */
  22221. CHAR_BACKTICK, /* ` */
  22222. CHAR_COMMA, /* , */
  22223. CHAR_DOT, /* . */
  22224. CHAR_LEFT_PARENTHESES, /* ( */
  22225. CHAR_RIGHT_PARENTHESES, /* ) */
  22226. CHAR_LEFT_CURLY_BRACE, /* { */
  22227. CHAR_RIGHT_CURLY_BRACE, /* } */
  22228. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  22229. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  22230. CHAR_DOUBLE_QUOTE, /* " */
  22231. CHAR_SINGLE_QUOTE, /* ' */
  22232. CHAR_NO_BREAK_SPACE,
  22233. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  22234. } = constants$3;
  22235. /**
  22236. * parse
  22237. */
  22238. const parse$c = (input, options = {}) => {
  22239. if (typeof input !== 'string') {
  22240. throw new TypeError('Expected a string');
  22241. }
  22242. let opts = options || {};
  22243. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  22244. if (input.length > max) {
  22245. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  22246. }
  22247. let ast = { type: 'root', input, nodes: [] };
  22248. let stack = [ast];
  22249. let block = ast;
  22250. let prev = ast;
  22251. let brackets = 0;
  22252. let length = input.length;
  22253. let index = 0;
  22254. let depth = 0;
  22255. let value;
  22256. /**
  22257. * Helpers
  22258. */
  22259. const advance = () => input[index++];
  22260. const push = node => {
  22261. if (node.type === 'text' && prev.type === 'dot') {
  22262. prev.type = 'text';
  22263. }
  22264. if (prev && prev.type === 'text' && node.type === 'text') {
  22265. prev.value += node.value;
  22266. return;
  22267. }
  22268. block.nodes.push(node);
  22269. node.parent = block;
  22270. node.prev = prev;
  22271. prev = node;
  22272. return node;
  22273. };
  22274. push({ type: 'bos' });
  22275. while (index < length) {
  22276. block = stack[stack.length - 1];
  22277. value = advance();
  22278. /**
  22279. * Invalid chars
  22280. */
  22281. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  22282. continue;
  22283. }
  22284. /**
  22285. * Escaped chars
  22286. */
  22287. if (value === CHAR_BACKSLASH) {
  22288. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  22289. continue;
  22290. }
  22291. /**
  22292. * Right square bracket (literal): ']'
  22293. */
  22294. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  22295. push({ type: 'text', value: '\\' + value });
  22296. continue;
  22297. }
  22298. /**
  22299. * Left square bracket: '['
  22300. */
  22301. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  22302. brackets++;
  22303. let next;
  22304. while (index < length && (next = advance())) {
  22305. value += next;
  22306. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  22307. brackets++;
  22308. continue;
  22309. }
  22310. if (next === CHAR_BACKSLASH) {
  22311. value += advance();
  22312. continue;
  22313. }
  22314. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  22315. brackets--;
  22316. if (brackets === 0) {
  22317. break;
  22318. }
  22319. }
  22320. }
  22321. push({ type: 'text', value });
  22322. continue;
  22323. }
  22324. /**
  22325. * Parentheses
  22326. */
  22327. if (value === CHAR_LEFT_PARENTHESES) {
  22328. block = push({ type: 'paren', nodes: [] });
  22329. stack.push(block);
  22330. push({ type: 'text', value });
  22331. continue;
  22332. }
  22333. if (value === CHAR_RIGHT_PARENTHESES) {
  22334. if (block.type !== 'paren') {
  22335. push({ type: 'text', value });
  22336. continue;
  22337. }
  22338. block = stack.pop();
  22339. push({ type: 'text', value });
  22340. block = stack[stack.length - 1];
  22341. continue;
  22342. }
  22343. /**
  22344. * Quotes: '|"|`
  22345. */
  22346. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  22347. let open = value;
  22348. let next;
  22349. if (options.keepQuotes !== true) {
  22350. value = '';
  22351. }
  22352. while (index < length && (next = advance())) {
  22353. if (next === CHAR_BACKSLASH) {
  22354. value += next + advance();
  22355. continue;
  22356. }
  22357. if (next === open) {
  22358. if (options.keepQuotes === true) value += next;
  22359. break;
  22360. }
  22361. value += next;
  22362. }
  22363. push({ type: 'text', value });
  22364. continue;
  22365. }
  22366. /**
  22367. * Left curly brace: '{'
  22368. */
  22369. if (value === CHAR_LEFT_CURLY_BRACE) {
  22370. depth++;
  22371. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  22372. let brace = {
  22373. type: 'brace',
  22374. open: true,
  22375. close: false,
  22376. dollar,
  22377. depth,
  22378. commas: 0,
  22379. ranges: 0,
  22380. nodes: []
  22381. };
  22382. block = push(brace);
  22383. stack.push(block);
  22384. push({ type: 'open', value });
  22385. continue;
  22386. }
  22387. /**
  22388. * Right curly brace: '}'
  22389. */
  22390. if (value === CHAR_RIGHT_CURLY_BRACE) {
  22391. if (block.type !== 'brace') {
  22392. push({ type: 'text', value });
  22393. continue;
  22394. }
  22395. let type = 'close';
  22396. block = stack.pop();
  22397. block.close = true;
  22398. push({ type, value });
  22399. depth--;
  22400. block = stack[stack.length - 1];
  22401. continue;
  22402. }
  22403. /**
  22404. * Comma: ','
  22405. */
  22406. if (value === CHAR_COMMA && depth > 0) {
  22407. if (block.ranges > 0) {
  22408. block.ranges = 0;
  22409. let open = block.nodes.shift();
  22410. block.nodes = [open, { type: 'text', value: stringify$4(block) }];
  22411. }
  22412. push({ type: 'comma', value });
  22413. block.commas++;
  22414. continue;
  22415. }
  22416. /**
  22417. * Dot: '.'
  22418. */
  22419. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  22420. let siblings = block.nodes;
  22421. if (depth === 0 || siblings.length === 0) {
  22422. push({ type: 'text', value });
  22423. continue;
  22424. }
  22425. if (prev.type === 'dot') {
  22426. block.range = [];
  22427. prev.value += value;
  22428. prev.type = 'range';
  22429. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  22430. block.invalid = true;
  22431. block.ranges = 0;
  22432. prev.type = 'text';
  22433. continue;
  22434. }
  22435. block.ranges++;
  22436. block.args = [];
  22437. continue;
  22438. }
  22439. if (prev.type === 'range') {
  22440. siblings.pop();
  22441. let before = siblings[siblings.length - 1];
  22442. before.value += prev.value + value;
  22443. prev = before;
  22444. block.ranges--;
  22445. continue;
  22446. }
  22447. push({ type: 'dot', value });
  22448. continue;
  22449. }
  22450. /**
  22451. * Text
  22452. */
  22453. push({ type: 'text', value });
  22454. }
  22455. // Mark imbalanced braces and brackets as invalid
  22456. do {
  22457. block = stack.pop();
  22458. if (block.type !== 'root') {
  22459. block.nodes.forEach(node => {
  22460. if (!node.nodes) {
  22461. if (node.type === 'open') node.isOpen = true;
  22462. if (node.type === 'close') node.isClose = true;
  22463. if (!node.nodes) node.type = 'text';
  22464. node.invalid = true;
  22465. }
  22466. });
  22467. // get the location of the block on parent.nodes (block's siblings)
  22468. let parent = stack[stack.length - 1];
  22469. let index = parent.nodes.indexOf(block);
  22470. // replace the (invalid) block with it's nodes
  22471. parent.nodes.splice(index, 1, ...block.nodes);
  22472. }
  22473. } while (stack.length > 0);
  22474. push({ type: 'eos' });
  22475. return ast;
  22476. };
  22477. var parse_1$2 = parse$c;
  22478. const stringify$3 = stringify$7;
  22479. const compile = compile_1;
  22480. const expand$1 = expand_1$1;
  22481. const parse$b = parse_1$2;
  22482. /**
  22483. * Expand the given pattern or create a regex-compatible string.
  22484. *
  22485. * ```js
  22486. * const braces = require('braces');
  22487. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  22488. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  22489. * ```
  22490. * @param {String} `str`
  22491. * @param {Object} `options`
  22492. * @return {String}
  22493. * @api public
  22494. */
  22495. const braces$2 = (input, options = {}) => {
  22496. let output = [];
  22497. if (Array.isArray(input)) {
  22498. for (let pattern of input) {
  22499. let result = braces$2.create(pattern, options);
  22500. if (Array.isArray(result)) {
  22501. output.push(...result);
  22502. } else {
  22503. output.push(result);
  22504. }
  22505. }
  22506. } else {
  22507. output = [].concat(braces$2.create(input, options));
  22508. }
  22509. if (options && options.expand === true && options.nodupes === true) {
  22510. output = [...new Set(output)];
  22511. }
  22512. return output;
  22513. };
  22514. /**
  22515. * Parse the given `str` with the given `options`.
  22516. *
  22517. * ```js
  22518. * // braces.parse(pattern, [, options]);
  22519. * const ast = braces.parse('a/{b,c}/d');
  22520. * console.log(ast);
  22521. * ```
  22522. * @param {String} pattern Brace pattern to parse
  22523. * @param {Object} options
  22524. * @return {Object} Returns an AST
  22525. * @api public
  22526. */
  22527. braces$2.parse = (input, options = {}) => parse$b(input, options);
  22528. /**
  22529. * Creates a braces string from an AST, or an AST node.
  22530. *
  22531. * ```js
  22532. * const braces = require('braces');
  22533. * let ast = braces.parse('foo/{a,b}/bar');
  22534. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  22535. * ```
  22536. * @param {String} `input` Brace pattern or AST.
  22537. * @param {Object} `options`
  22538. * @return {Array} Returns an array of expanded values.
  22539. * @api public
  22540. */
  22541. braces$2.stringify = (input, options = {}) => {
  22542. if (typeof input === 'string') {
  22543. return stringify$3(braces$2.parse(input, options), options);
  22544. }
  22545. return stringify$3(input, options);
  22546. };
  22547. /**
  22548. * Compiles a brace pattern into a regex-compatible, optimized string.
  22549. * This method is called by the main [braces](#braces) function by default.
  22550. *
  22551. * ```js
  22552. * const braces = require('braces');
  22553. * console.log(braces.compile('a/{b,c}/d'));
  22554. * //=> ['a/(b|c)/d']
  22555. * ```
  22556. * @param {String} `input` Brace pattern or AST.
  22557. * @param {Object} `options`
  22558. * @return {Array} Returns an array of expanded values.
  22559. * @api public
  22560. */
  22561. braces$2.compile = (input, options = {}) => {
  22562. if (typeof input === 'string') {
  22563. input = braces$2.parse(input, options);
  22564. }
  22565. return compile(input, options);
  22566. };
  22567. /**
  22568. * Expands a brace pattern into an array. This method is called by the
  22569. * main [braces](#braces) function when `options.expand` is true. Before
  22570. * using this method it's recommended that you read the [performance notes](#performance))
  22571. * and advantages of using [.compile](#compile) instead.
  22572. *
  22573. * ```js
  22574. * const braces = require('braces');
  22575. * console.log(braces.expand('a/{b,c}/d'));
  22576. * //=> ['a/b/d', 'a/c/d'];
  22577. * ```
  22578. * @param {String} `pattern` Brace pattern
  22579. * @param {Object} `options`
  22580. * @return {Array} Returns an array of expanded values.
  22581. * @api public
  22582. */
  22583. braces$2.expand = (input, options = {}) => {
  22584. if (typeof input === 'string') {
  22585. input = braces$2.parse(input, options);
  22586. }
  22587. let result = expand$1(input, options);
  22588. // filter out empty strings if specified
  22589. if (options.noempty === true) {
  22590. result = result.filter(Boolean);
  22591. }
  22592. // filter out duplicates if specified
  22593. if (options.nodupes === true) {
  22594. result = [...new Set(result)];
  22595. }
  22596. return result;
  22597. };
  22598. /**
  22599. * Processes a brace pattern and returns either an expanded array
  22600. * (if `options.expand` is true), a highly optimized regex-compatible string.
  22601. * This method is called by the main [braces](#braces) function.
  22602. *
  22603. * ```js
  22604. * const braces = require('braces');
  22605. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  22606. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  22607. * ```
  22608. * @param {String} `pattern` Brace pattern
  22609. * @param {Object} `options`
  22610. * @return {Array} Returns an array of expanded values.
  22611. * @api public
  22612. */
  22613. braces$2.create = (input, options = {}) => {
  22614. if (input === '' || input.length < 3) {
  22615. return [input];
  22616. }
  22617. return options.expand !== true
  22618. ? braces$2.compile(input, options)
  22619. : braces$2.expand(input, options);
  22620. };
  22621. /**
  22622. * Expose "braces"
  22623. */
  22624. var braces_1 = braces$2;
  22625. const util = require$$0$6;
  22626. const braces$1 = braces_1;
  22627. const picomatch$2 = picomatch$3;
  22628. const utils$b = utils$k;
  22629. const isEmptyString = val => val === '' || val === './';
  22630. /**
  22631. * Returns an array of strings that match one or more glob patterns.
  22632. *
  22633. * ```js
  22634. * const mm = require('micromatch');
  22635. * // mm(list, patterns[, options]);
  22636. *
  22637. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  22638. * //=> [ 'a.js' ]
  22639. * ```
  22640. * @param {String|Array<string>} `list` List of strings to match.
  22641. * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
  22642. * @param {Object} `options` See available [options](#options)
  22643. * @return {Array} Returns an array of matches
  22644. * @summary false
  22645. * @api public
  22646. */
  22647. const micromatch$1 = (list, patterns, options) => {
  22648. patterns = [].concat(patterns);
  22649. list = [].concat(list);
  22650. let omit = new Set();
  22651. let keep = new Set();
  22652. let items = new Set();
  22653. let negatives = 0;
  22654. let onResult = state => {
  22655. items.add(state.output);
  22656. if (options && options.onResult) {
  22657. options.onResult(state);
  22658. }
  22659. };
  22660. for (let i = 0; i < patterns.length; i++) {
  22661. let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true);
  22662. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  22663. if (negated) negatives++;
  22664. for (let item of list) {
  22665. let matched = isMatch(item, true);
  22666. let match = negated ? !matched.isMatch : matched.isMatch;
  22667. if (!match) continue;
  22668. if (negated) {
  22669. omit.add(matched.output);
  22670. } else {
  22671. omit.delete(matched.output);
  22672. keep.add(matched.output);
  22673. }
  22674. }
  22675. }
  22676. let result = negatives === patterns.length ? [...items] : [...keep];
  22677. let matches = result.filter(item => !omit.has(item));
  22678. if (options && matches.length === 0) {
  22679. if (options.failglob === true) {
  22680. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  22681. }
  22682. if (options.nonull === true || options.nullglob === true) {
  22683. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  22684. }
  22685. }
  22686. return matches;
  22687. };
  22688. /**
  22689. * Backwards compatibility
  22690. */
  22691. micromatch$1.match = micromatch$1;
  22692. /**
  22693. * Returns a matcher function from the given glob `pattern` and `options`.
  22694. * The returned function takes a string to match as its only argument and returns
  22695. * true if the string is a match.
  22696. *
  22697. * ```js
  22698. * const mm = require('micromatch');
  22699. * // mm.matcher(pattern[, options]);
  22700. *
  22701. * const isMatch = mm.matcher('*.!(*a)');
  22702. * console.log(isMatch('a.a')); //=> false
  22703. * console.log(isMatch('a.b')); //=> true
  22704. * ```
  22705. * @param {String} `pattern` Glob pattern
  22706. * @param {Object} `options`
  22707. * @return {Function} Returns a matcher function.
  22708. * @api public
  22709. */
  22710. micromatch$1.matcher = (pattern, options) => picomatch$2(pattern, options);
  22711. /**
  22712. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  22713. *
  22714. * ```js
  22715. * const mm = require('micromatch');
  22716. * // mm.isMatch(string, patterns[, options]);
  22717. *
  22718. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  22719. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  22720. * ```
  22721. * @param {String} `str` The string to test.
  22722. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  22723. * @param {Object} `[options]` See available [options](#options).
  22724. * @return {Boolean} Returns true if any patterns match `str`
  22725. * @api public
  22726. */
  22727. micromatch$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
  22728. /**
  22729. * Backwards compatibility
  22730. */
  22731. micromatch$1.any = micromatch$1.isMatch;
  22732. /**
  22733. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  22734. *
  22735. * ```js
  22736. * const mm = require('micromatch');
  22737. * // mm.not(list, patterns[, options]);
  22738. *
  22739. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  22740. * //=> ['b.b', 'c.c']
  22741. * ```
  22742. * @param {Array} `list` Array of strings to match.
  22743. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  22744. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  22745. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  22746. * @api public
  22747. */
  22748. micromatch$1.not = (list, patterns, options = {}) => {
  22749. patterns = [].concat(patterns).map(String);
  22750. let result = new Set();
  22751. let items = [];
  22752. let onResult = state => {
  22753. if (options.onResult) options.onResult(state);
  22754. items.push(state.output);
  22755. };
  22756. let matches = new Set(micromatch$1(list, patterns, { ...options, onResult }));
  22757. for (let item of items) {
  22758. if (!matches.has(item)) {
  22759. result.add(item);
  22760. }
  22761. }
  22762. return [...result];
  22763. };
  22764. /**
  22765. * Returns true if the given `string` contains the given pattern. Similar
  22766. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  22767. *
  22768. * ```js
  22769. * var mm = require('micromatch');
  22770. * // mm.contains(string, pattern[, options]);
  22771. *
  22772. * console.log(mm.contains('aa/bb/cc', '*b'));
  22773. * //=> true
  22774. * console.log(mm.contains('aa/bb/cc', '*d'));
  22775. * //=> false
  22776. * ```
  22777. * @param {String} `str` The string to match.
  22778. * @param {String|Array} `patterns` Glob pattern to use for matching.
  22779. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  22780. * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
  22781. * @api public
  22782. */
  22783. micromatch$1.contains = (str, pattern, options) => {
  22784. if (typeof str !== 'string') {
  22785. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  22786. }
  22787. if (Array.isArray(pattern)) {
  22788. return pattern.some(p => micromatch$1.contains(str, p, options));
  22789. }
  22790. if (typeof pattern === 'string') {
  22791. if (isEmptyString(str) || isEmptyString(pattern)) {
  22792. return false;
  22793. }
  22794. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  22795. return true;
  22796. }
  22797. }
  22798. return micromatch$1.isMatch(str, pattern, { ...options, contains: true });
  22799. };
  22800. /**
  22801. * Filter the keys of the given object with the given `glob` pattern
  22802. * and `options`. Does not attempt to match nested keys. If you need this feature,
  22803. * use [glob-object][] instead.
  22804. *
  22805. * ```js
  22806. * const mm = require('micromatch');
  22807. * // mm.matchKeys(object, patterns[, options]);
  22808. *
  22809. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  22810. * console.log(mm.matchKeys(obj, '*b'));
  22811. * //=> { ab: 'b' }
  22812. * ```
  22813. * @param {Object} `object` The object with keys to filter.
  22814. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  22815. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  22816. * @return {Object} Returns an object with only keys that match the given patterns.
  22817. * @api public
  22818. */
  22819. micromatch$1.matchKeys = (obj, patterns, options) => {
  22820. if (!utils$b.isObject(obj)) {
  22821. throw new TypeError('Expected the first argument to be an object');
  22822. }
  22823. let keys = micromatch$1(Object.keys(obj), patterns, options);
  22824. let res = {};
  22825. for (let key of keys) res[key] = obj[key];
  22826. return res;
  22827. };
  22828. /**
  22829. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  22830. *
  22831. * ```js
  22832. * const mm = require('micromatch');
  22833. * // mm.some(list, patterns[, options]);
  22834. *
  22835. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  22836. * // true
  22837. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  22838. * // false
  22839. * ```
  22840. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  22841. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  22842. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  22843. * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
  22844. * @api public
  22845. */
  22846. micromatch$1.some = (list, patterns, options) => {
  22847. let items = [].concat(list);
  22848. for (let pattern of [].concat(patterns)) {
  22849. let isMatch = picomatch$2(String(pattern), options);
  22850. if (items.some(item => isMatch(item))) {
  22851. return true;
  22852. }
  22853. }
  22854. return false;
  22855. };
  22856. /**
  22857. * Returns true if every string in the given `list` matches
  22858. * any of the given glob `patterns`.
  22859. *
  22860. * ```js
  22861. * const mm = require('micromatch');
  22862. * // mm.every(list, patterns[, options]);
  22863. *
  22864. * console.log(mm.every('foo.js', ['foo.js']));
  22865. * // true
  22866. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  22867. * // true
  22868. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  22869. * // false
  22870. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  22871. * // false
  22872. * ```
  22873. * @param {String|Array} `list` The string or array of strings to test.
  22874. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  22875. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  22876. * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
  22877. * @api public
  22878. */
  22879. micromatch$1.every = (list, patterns, options) => {
  22880. let items = [].concat(list);
  22881. for (let pattern of [].concat(patterns)) {
  22882. let isMatch = picomatch$2(String(pattern), options);
  22883. if (!items.every(item => isMatch(item))) {
  22884. return false;
  22885. }
  22886. }
  22887. return true;
  22888. };
  22889. /**
  22890. * Returns true if **all** of the given `patterns` match
  22891. * the specified string.
  22892. *
  22893. * ```js
  22894. * const mm = require('micromatch');
  22895. * // mm.all(string, patterns[, options]);
  22896. *
  22897. * console.log(mm.all('foo.js', ['foo.js']));
  22898. * // true
  22899. *
  22900. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  22901. * // false
  22902. *
  22903. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  22904. * // true
  22905. *
  22906. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  22907. * // true
  22908. * ```
  22909. * @param {String|Array} `str` The string to test.
  22910. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  22911. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  22912. * @return {Boolean} Returns true if any patterns match `str`
  22913. * @api public
  22914. */
  22915. micromatch$1.all = (str, patterns, options) => {
  22916. if (typeof str !== 'string') {
  22917. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  22918. }
  22919. return [].concat(patterns).every(p => picomatch$2(p, options)(str));
  22920. };
  22921. /**
  22922. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  22923. *
  22924. * ```js
  22925. * const mm = require('micromatch');
  22926. * // mm.capture(pattern, string[, options]);
  22927. *
  22928. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  22929. * //=> ['foo']
  22930. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  22931. * //=> null
  22932. * ```
  22933. * @param {String} `glob` Glob pattern to use for matching.
  22934. * @param {String} `input` String to match
  22935. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  22936. * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  22937. * @api public
  22938. */
  22939. micromatch$1.capture = (glob, input, options) => {
  22940. let posix = utils$b.isWindows(options);
  22941. let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true });
  22942. let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input);
  22943. if (match) {
  22944. return match.slice(1).map(v => v === void 0 ? '' : v);
  22945. }
  22946. };
  22947. /**
  22948. * Create a regular expression from the given glob `pattern`.
  22949. *
  22950. * ```js
  22951. * const mm = require('micromatch');
  22952. * // mm.makeRe(pattern[, options]);
  22953. *
  22954. * console.log(mm.makeRe('*.js'));
  22955. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  22956. * ```
  22957. * @param {String} `pattern` A glob pattern to convert to regex.
  22958. * @param {Object} `options`
  22959. * @return {RegExp} Returns a regex created from the given pattern.
  22960. * @api public
  22961. */
  22962. micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args);
  22963. /**
  22964. * Scan a glob pattern to separate the pattern into segments. Used
  22965. * by the [split](#split) method.
  22966. *
  22967. * ```js
  22968. * const mm = require('micromatch');
  22969. * const state = mm.scan(pattern[, options]);
  22970. * ```
  22971. * @param {String} `pattern`
  22972. * @param {Object} `options`
  22973. * @return {Object} Returns an object with
  22974. * @api public
  22975. */
  22976. micromatch$1.scan = (...args) => picomatch$2.scan(...args);
  22977. /**
  22978. * Parse a glob pattern to create the source string for a regular
  22979. * expression.
  22980. *
  22981. * ```js
  22982. * const mm = require('micromatch');
  22983. * const state = mm.parse(pattern[, options]);
  22984. * ```
  22985. * @param {String} `glob`
  22986. * @param {Object} `options`
  22987. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  22988. * @api public
  22989. */
  22990. micromatch$1.parse = (patterns, options) => {
  22991. let res = [];
  22992. for (let pattern of [].concat(patterns || [])) {
  22993. for (let str of braces$1(String(pattern), options)) {
  22994. res.push(picomatch$2.parse(str, options));
  22995. }
  22996. }
  22997. return res;
  22998. };
  22999. /**
  23000. * Process the given brace `pattern`.
  23001. *
  23002. * ```js
  23003. * const { braces } = require('micromatch');
  23004. * console.log(braces('foo/{a,b,c}/bar'));
  23005. * //=> [ 'foo/(a|b|c)/bar' ]
  23006. *
  23007. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  23008. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  23009. * ```
  23010. * @param {String} `pattern` String with brace pattern to process.
  23011. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  23012. * @return {Array}
  23013. * @api public
  23014. */
  23015. micromatch$1.braces = (pattern, options) => {
  23016. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  23017. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  23018. return [pattern];
  23019. }
  23020. return braces$1(pattern, options);
  23021. };
  23022. /**
  23023. * Expand braces
  23024. */
  23025. micromatch$1.braceExpand = (pattern, options) => {
  23026. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  23027. return micromatch$1.braces(pattern, { ...options, expand: true });
  23028. };
  23029. /**
  23030. * Expose micromatch
  23031. */
  23032. var micromatch_1 = micromatch$1;
  23033. var micromatch$2 = /*@__PURE__*/getDefaultExportFromCjs(micromatch_1);
  23034. Object.defineProperty(pattern$1, "__esModule", { value: true });
  23035. pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
  23036. const path$f = require$$0$4;
  23037. const globParent$1 = globParent$2;
  23038. const micromatch = micromatch_1;
  23039. const GLOBSTAR$1 = '**';
  23040. const ESCAPE_SYMBOL = '\\';
  23041. const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
  23042. const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/;
  23043. const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/;
  23044. const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/;
  23045. const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
  23046. function isStaticPattern(pattern, options = {}) {
  23047. return !isDynamicPattern(pattern, options);
  23048. }
  23049. pattern$1.isStaticPattern = isStaticPattern;
  23050. function isDynamicPattern(pattern, options = {}) {
  23051. /**
  23052. * A special case with an empty string is necessary for matching patterns that start with a forward slash.
  23053. * An empty string cannot be a dynamic pattern.
  23054. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
  23055. */
  23056. if (pattern === '') {
  23057. return false;
  23058. }
  23059. /**
  23060. * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
  23061. * filepath directly (without read directory).
  23062. */
  23063. if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
  23064. return true;
  23065. }
  23066. if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
  23067. return true;
  23068. }
  23069. if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
  23070. return true;
  23071. }
  23072. if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
  23073. return true;
  23074. }
  23075. return false;
  23076. }
  23077. pattern$1.isDynamicPattern = isDynamicPattern;
  23078. function hasBraceExpansion(pattern) {
  23079. const openingBraceIndex = pattern.indexOf('{');
  23080. if (openingBraceIndex === -1) {
  23081. return false;
  23082. }
  23083. const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1);
  23084. if (closingBraceIndex === -1) {
  23085. return false;
  23086. }
  23087. const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex);
  23088. return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
  23089. }
  23090. function convertToPositivePattern(pattern) {
  23091. return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
  23092. }
  23093. pattern$1.convertToPositivePattern = convertToPositivePattern;
  23094. function convertToNegativePattern(pattern) {
  23095. return '!' + pattern;
  23096. }
  23097. pattern$1.convertToNegativePattern = convertToNegativePattern;
  23098. function isNegativePattern(pattern) {
  23099. return pattern.startsWith('!') && pattern[1] !== '(';
  23100. }
  23101. pattern$1.isNegativePattern = isNegativePattern;
  23102. function isPositivePattern(pattern) {
  23103. return !isNegativePattern(pattern);
  23104. }
  23105. pattern$1.isPositivePattern = isPositivePattern;
  23106. function getNegativePatterns(patterns) {
  23107. return patterns.filter(isNegativePattern);
  23108. }
  23109. pattern$1.getNegativePatterns = getNegativePatterns;
  23110. function getPositivePatterns$1(patterns) {
  23111. return patterns.filter(isPositivePattern);
  23112. }
  23113. pattern$1.getPositivePatterns = getPositivePatterns$1;
  23114. /**
  23115. * Returns patterns that can be applied inside the current directory.
  23116. *
  23117. * @example
  23118. * // ['./*', '*', 'a/*']
  23119. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  23120. */
  23121. function getPatternsInsideCurrentDirectory(patterns) {
  23122. return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
  23123. }
  23124. pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
  23125. /**
  23126. * Returns patterns to be expanded relative to (outside) the current directory.
  23127. *
  23128. * @example
  23129. * // ['../*', './../*']
  23130. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  23131. */
  23132. function getPatternsOutsideCurrentDirectory(patterns) {
  23133. return patterns.filter(isPatternRelatedToParentDirectory);
  23134. }
  23135. pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
  23136. function isPatternRelatedToParentDirectory(pattern) {
  23137. return pattern.startsWith('..') || pattern.startsWith('./..');
  23138. }
  23139. pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
  23140. function getBaseDirectory(pattern) {
  23141. return globParent$1(pattern, { flipBackslashes: false });
  23142. }
  23143. pattern$1.getBaseDirectory = getBaseDirectory;
  23144. function hasGlobStar(pattern) {
  23145. return pattern.includes(GLOBSTAR$1);
  23146. }
  23147. pattern$1.hasGlobStar = hasGlobStar;
  23148. function endsWithSlashGlobStar(pattern) {
  23149. return pattern.endsWith('/' + GLOBSTAR$1);
  23150. }
  23151. pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
  23152. function isAffectDepthOfReadingPattern(pattern) {
  23153. const basename = path$f.basename(pattern);
  23154. return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
  23155. }
  23156. pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
  23157. function expandPatternsWithBraceExpansion(patterns) {
  23158. return patterns.reduce((collection, pattern) => {
  23159. return collection.concat(expandBraceExpansion(pattern));
  23160. }, []);
  23161. }
  23162. pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
  23163. function expandBraceExpansion(pattern) {
  23164. return micromatch.braces(pattern, {
  23165. expand: true,
  23166. nodupes: true
  23167. });
  23168. }
  23169. pattern$1.expandBraceExpansion = expandBraceExpansion;
  23170. function getPatternParts(pattern, options) {
  23171. let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
  23172. /**
  23173. * The scan method returns an empty array in some cases.
  23174. * See micromatch/picomatch#58 for more details.
  23175. */
  23176. if (parts.length === 0) {
  23177. parts = [pattern];
  23178. }
  23179. /**
  23180. * The scan method does not return an empty part for the pattern with a forward slash.
  23181. * This is another part of micromatch/picomatch#58.
  23182. */
  23183. if (parts[0].startsWith('/')) {
  23184. parts[0] = parts[0].slice(1);
  23185. parts.unshift('');
  23186. }
  23187. return parts;
  23188. }
  23189. pattern$1.getPatternParts = getPatternParts;
  23190. function makeRe(pattern, options) {
  23191. return micromatch.makeRe(pattern, options);
  23192. }
  23193. pattern$1.makeRe = makeRe;
  23194. function convertPatternsToRe(patterns, options) {
  23195. return patterns.map((pattern) => makeRe(pattern, options));
  23196. }
  23197. pattern$1.convertPatternsToRe = convertPatternsToRe;
  23198. function matchAny(entry, patternsRe) {
  23199. return patternsRe.some((patternRe) => patternRe.test(entry));
  23200. }
  23201. pattern$1.matchAny = matchAny;
  23202. var stream$4 = {};
  23203. /*
  23204. * merge2
  23205. * https://github.com/teambition/merge2
  23206. *
  23207. * Copyright (c) 2014-2020 Teambition
  23208. * Licensed under the MIT license.
  23209. */
  23210. const Stream = require$$0$7;
  23211. const PassThrough = Stream.PassThrough;
  23212. const slice = Array.prototype.slice;
  23213. var merge2_1 = merge2$1;
  23214. function merge2$1 () {
  23215. const streamsQueue = [];
  23216. const args = slice.call(arguments);
  23217. let merging = false;
  23218. let options = args[args.length - 1];
  23219. if (options && !Array.isArray(options) && options.pipe == null) {
  23220. args.pop();
  23221. } else {
  23222. options = {};
  23223. }
  23224. const doEnd = options.end !== false;
  23225. const doPipeError = options.pipeError === true;
  23226. if (options.objectMode == null) {
  23227. options.objectMode = true;
  23228. }
  23229. if (options.highWaterMark == null) {
  23230. options.highWaterMark = 64 * 1024;
  23231. }
  23232. const mergedStream = PassThrough(options);
  23233. function addStream () {
  23234. for (let i = 0, len = arguments.length; i < len; i++) {
  23235. streamsQueue.push(pauseStreams(arguments[i], options));
  23236. }
  23237. mergeStream();
  23238. return this
  23239. }
  23240. function mergeStream () {
  23241. if (merging) {
  23242. return
  23243. }
  23244. merging = true;
  23245. let streams = streamsQueue.shift();
  23246. if (!streams) {
  23247. process.nextTick(endStream);
  23248. return
  23249. }
  23250. if (!Array.isArray(streams)) {
  23251. streams = [streams];
  23252. }
  23253. let pipesCount = streams.length + 1;
  23254. function next () {
  23255. if (--pipesCount > 0) {
  23256. return
  23257. }
  23258. merging = false;
  23259. mergeStream();
  23260. }
  23261. function pipe (stream) {
  23262. function onend () {
  23263. stream.removeListener('merge2UnpipeEnd', onend);
  23264. stream.removeListener('end', onend);
  23265. if (doPipeError) {
  23266. stream.removeListener('error', onerror);
  23267. }
  23268. next();
  23269. }
  23270. function onerror (err) {
  23271. mergedStream.emit('error', err);
  23272. }
  23273. // skip ended stream
  23274. if (stream._readableState.endEmitted) {
  23275. return next()
  23276. }
  23277. stream.on('merge2UnpipeEnd', onend);
  23278. stream.on('end', onend);
  23279. if (doPipeError) {
  23280. stream.on('error', onerror);
  23281. }
  23282. stream.pipe(mergedStream, { end: false });
  23283. // compatible for old stream
  23284. stream.resume();
  23285. }
  23286. for (let i = 0; i < streams.length; i++) {
  23287. pipe(streams[i]);
  23288. }
  23289. next();
  23290. }
  23291. function endStream () {
  23292. merging = false;
  23293. // emit 'queueDrain' when all streams merged.
  23294. mergedStream.emit('queueDrain');
  23295. if (doEnd) {
  23296. mergedStream.end();
  23297. }
  23298. }
  23299. mergedStream.setMaxListeners(0);
  23300. mergedStream.add = addStream;
  23301. mergedStream.on('unpipe', function (stream) {
  23302. stream.emit('merge2UnpipeEnd');
  23303. });
  23304. if (args.length) {
  23305. addStream.apply(null, args);
  23306. }
  23307. return mergedStream
  23308. }
  23309. // check and pause streams for pipe.
  23310. function pauseStreams (streams, options) {
  23311. if (!Array.isArray(streams)) {
  23312. // Backwards-compat with old-style streams
  23313. if (!streams._readableState && streams.pipe) {
  23314. streams = streams.pipe(PassThrough(options));
  23315. }
  23316. if (!streams._readableState || !streams.pause || !streams.pipe) {
  23317. throw new Error('Only readable stream can be merged.')
  23318. }
  23319. streams.pause();
  23320. } else {
  23321. for (let i = 0, len = streams.length; i < len; i++) {
  23322. streams[i] = pauseStreams(streams[i], options);
  23323. }
  23324. }
  23325. return streams
  23326. }
  23327. Object.defineProperty(stream$4, "__esModule", { value: true });
  23328. stream$4.merge = void 0;
  23329. const merge2 = merge2_1;
  23330. function merge$1(streams) {
  23331. const mergedStream = merge2(streams);
  23332. streams.forEach((stream) => {
  23333. stream.once('error', (error) => mergedStream.emit('error', error));
  23334. });
  23335. mergedStream.once('close', () => propagateCloseEventToSources(streams));
  23336. mergedStream.once('end', () => propagateCloseEventToSources(streams));
  23337. return mergedStream;
  23338. }
  23339. stream$4.merge = merge$1;
  23340. function propagateCloseEventToSources(streams) {
  23341. streams.forEach((stream) => stream.emit('close'));
  23342. }
  23343. var string$2 = {};
  23344. Object.defineProperty(string$2, "__esModule", { value: true });
  23345. string$2.isEmpty = string$2.isString = void 0;
  23346. function isString(input) {
  23347. return typeof input === 'string';
  23348. }
  23349. string$2.isString = isString;
  23350. function isEmpty$1(input) {
  23351. return input === '';
  23352. }
  23353. string$2.isEmpty = isEmpty$1;
  23354. Object.defineProperty(utils$g, "__esModule", { value: true });
  23355. utils$g.string = utils$g.stream = utils$g.pattern = utils$g.path = utils$g.fs = utils$g.errno = utils$g.array = void 0;
  23356. const array = array$1;
  23357. utils$g.array = array;
  23358. const errno = errno$1;
  23359. utils$g.errno = errno;
  23360. const fs$g = fs$h;
  23361. utils$g.fs = fs$g;
  23362. const path$e = path$h;
  23363. utils$g.path = path$e;
  23364. const pattern = pattern$1;
  23365. utils$g.pattern = pattern;
  23366. const stream$3 = stream$4;
  23367. utils$g.stream = stream$3;
  23368. const string$1 = string$2;
  23369. utils$g.string = string$1;
  23370. Object.defineProperty(tasks, "__esModule", { value: true });
  23371. tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
  23372. const utils$a = utils$g;
  23373. function generate(patterns, settings) {
  23374. const positivePatterns = getPositivePatterns(patterns);
  23375. const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
  23376. const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings));
  23377. const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings));
  23378. const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
  23379. const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
  23380. return staticTasks.concat(dynamicTasks);
  23381. }
  23382. tasks.generate = generate;
  23383. /**
  23384. * Returns tasks grouped by basic pattern directories.
  23385. *
  23386. * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
  23387. * This is necessary because directory traversal starts at the base directory and goes deeper.
  23388. */
  23389. function convertPatternsToTasks(positive, negative, dynamic) {
  23390. const tasks = [];
  23391. const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive);
  23392. const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive);
  23393. const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
  23394. const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
  23395. tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
  23396. /*
  23397. * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
  23398. * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
  23399. */
  23400. if ('.' in insideCurrentDirectoryGroup) {
  23401. tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
  23402. }
  23403. else {
  23404. tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
  23405. }
  23406. return tasks;
  23407. }
  23408. tasks.convertPatternsToTasks = convertPatternsToTasks;
  23409. function getPositivePatterns(patterns) {
  23410. return utils$a.pattern.getPositivePatterns(patterns);
  23411. }
  23412. tasks.getPositivePatterns = getPositivePatterns;
  23413. function getNegativePatternsAsPositive(patterns, ignore) {
  23414. const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore);
  23415. const positive = negative.map(utils$a.pattern.convertToPositivePattern);
  23416. return positive;
  23417. }
  23418. tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
  23419. function groupPatternsByBaseDirectory(patterns) {
  23420. const group = {};
  23421. return patterns.reduce((collection, pattern) => {
  23422. const base = utils$a.pattern.getBaseDirectory(pattern);
  23423. if (base in collection) {
  23424. collection[base].push(pattern);
  23425. }
  23426. else {
  23427. collection[base] = [pattern];
  23428. }
  23429. return collection;
  23430. }, group);
  23431. }
  23432. tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
  23433. function convertPatternGroupsToTasks(positive, negative, dynamic) {
  23434. return Object.keys(positive).map((base) => {
  23435. return convertPatternGroupToTask(base, positive[base], negative, dynamic);
  23436. });
  23437. }
  23438. tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
  23439. function convertPatternGroupToTask(base, positive, negative, dynamic) {
  23440. return {
  23441. dynamic,
  23442. positive,
  23443. negative,
  23444. base,
  23445. patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern))
  23446. };
  23447. }
  23448. tasks.convertPatternGroupToTask = convertPatternGroupToTask;
  23449. var patterns = {};
  23450. Object.defineProperty(patterns, "__esModule", { value: true });
  23451. patterns.removeDuplicateSlashes = patterns.transform = void 0;
  23452. /**
  23453. * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string.
  23454. * The latter is due to the presence of the device path at the beginning of the UNC path.
  23455. * @todo rewrite to negative lookbehind with the next major release.
  23456. */
  23457. const DOUBLE_SLASH_RE$1 = /(?!^)\/{2,}/g;
  23458. function transform(patterns) {
  23459. return patterns.map((pattern) => removeDuplicateSlashes(pattern));
  23460. }
  23461. patterns.transform = transform;
  23462. /**
  23463. * This package only works with forward slashes as a path separator.
  23464. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes.
  23465. */
  23466. function removeDuplicateSlashes(pattern) {
  23467. return pattern.replace(DOUBLE_SLASH_RE$1, '/');
  23468. }
  23469. patterns.removeDuplicateSlashes = removeDuplicateSlashes;
  23470. var async$7 = {};
  23471. var async$6 = {};
  23472. var out$3 = {};
  23473. var async$5 = {};
  23474. var async$4 = {};
  23475. var out$2 = {};
  23476. var async$3 = {};
  23477. var out$1 = {};
  23478. var async$2 = {};
  23479. Object.defineProperty(async$2, "__esModule", { value: true });
  23480. async$2.read = void 0;
  23481. function read$3(path, settings, callback) {
  23482. settings.fs.lstat(path, (lstatError, lstat) => {
  23483. if (lstatError !== null) {
  23484. callFailureCallback$2(callback, lstatError);
  23485. return;
  23486. }
  23487. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  23488. callSuccessCallback$2(callback, lstat);
  23489. return;
  23490. }
  23491. settings.fs.stat(path, (statError, stat) => {
  23492. if (statError !== null) {
  23493. if (settings.throwErrorOnBrokenSymbolicLink) {
  23494. callFailureCallback$2(callback, statError);
  23495. return;
  23496. }
  23497. callSuccessCallback$2(callback, lstat);
  23498. return;
  23499. }
  23500. if (settings.markSymbolicLink) {
  23501. stat.isSymbolicLink = () => true;
  23502. }
  23503. callSuccessCallback$2(callback, stat);
  23504. });
  23505. });
  23506. }
  23507. async$2.read = read$3;
  23508. function callFailureCallback$2(callback, error) {
  23509. callback(error);
  23510. }
  23511. function callSuccessCallback$2(callback, result) {
  23512. callback(null, result);
  23513. }
  23514. var sync$8 = {};
  23515. Object.defineProperty(sync$8, "__esModule", { value: true });
  23516. sync$8.read = void 0;
  23517. function read$2(path, settings) {
  23518. const lstat = settings.fs.lstatSync(path);
  23519. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  23520. return lstat;
  23521. }
  23522. try {
  23523. const stat = settings.fs.statSync(path);
  23524. if (settings.markSymbolicLink) {
  23525. stat.isSymbolicLink = () => true;
  23526. }
  23527. return stat;
  23528. }
  23529. catch (error) {
  23530. if (!settings.throwErrorOnBrokenSymbolicLink) {
  23531. return lstat;
  23532. }
  23533. throw error;
  23534. }
  23535. }
  23536. sync$8.read = read$2;
  23537. var settings$3 = {};
  23538. var fs$f = {};
  23539. (function (exports) {
  23540. Object.defineProperty(exports, "__esModule", { value: true });
  23541. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  23542. const fs = require$$0__default;
  23543. exports.FILE_SYSTEM_ADAPTER = {
  23544. lstat: fs.lstat,
  23545. stat: fs.stat,
  23546. lstatSync: fs.lstatSync,
  23547. statSync: fs.statSync
  23548. };
  23549. function createFileSystemAdapter(fsMethods) {
  23550. if (fsMethods === undefined) {
  23551. return exports.FILE_SYSTEM_ADAPTER;
  23552. }
  23553. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  23554. }
  23555. exports.createFileSystemAdapter = createFileSystemAdapter;
  23556. } (fs$f));
  23557. Object.defineProperty(settings$3, "__esModule", { value: true });
  23558. const fs$e = fs$f;
  23559. let Settings$2 = class Settings {
  23560. constructor(_options = {}) {
  23561. this._options = _options;
  23562. this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
  23563. this.fs = fs$e.createFileSystemAdapter(this._options.fs);
  23564. this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
  23565. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  23566. }
  23567. _getValue(option, value) {
  23568. return option !== null && option !== void 0 ? option : value;
  23569. }
  23570. };
  23571. settings$3.default = Settings$2;
  23572. Object.defineProperty(out$1, "__esModule", { value: true });
  23573. out$1.statSync = out$1.stat = out$1.Settings = void 0;
  23574. const async$1 = async$2;
  23575. const sync$7 = sync$8;
  23576. const settings_1$3 = settings$3;
  23577. out$1.Settings = settings_1$3.default;
  23578. function stat$4(path, optionsOrSettingsOrCallback, callback) {
  23579. if (typeof optionsOrSettingsOrCallback === 'function') {
  23580. async$1.read(path, getSettings$2(), optionsOrSettingsOrCallback);
  23581. return;
  23582. }
  23583. async$1.read(path, getSettings$2(optionsOrSettingsOrCallback), callback);
  23584. }
  23585. out$1.stat = stat$4;
  23586. function statSync(path, optionsOrSettings) {
  23587. const settings = getSettings$2(optionsOrSettings);
  23588. return sync$7.read(path, settings);
  23589. }
  23590. out$1.statSync = statSync;
  23591. function getSettings$2(settingsOrOptions = {}) {
  23592. if (settingsOrOptions instanceof settings_1$3.default) {
  23593. return settingsOrOptions;
  23594. }
  23595. return new settings_1$3.default(settingsOrOptions);
  23596. }
  23597. /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  23598. let promise;
  23599. var queueMicrotask_1 = typeof queueMicrotask === 'function'
  23600. ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
  23601. // reuse resolved promise, and allocate it lazily
  23602. : cb => (promise || (promise = Promise.resolve()))
  23603. .then(cb)
  23604. .catch(err => setTimeout(() => { throw err }, 0));
  23605. /*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  23606. var runParallel_1 = runParallel;
  23607. const queueMicrotask$1 = queueMicrotask_1;
  23608. function runParallel (tasks, cb) {
  23609. let results, pending, keys;
  23610. let isSync = true;
  23611. if (Array.isArray(tasks)) {
  23612. results = [];
  23613. pending = tasks.length;
  23614. } else {
  23615. keys = Object.keys(tasks);
  23616. results = {};
  23617. pending = keys.length;
  23618. }
  23619. function done (err) {
  23620. function end () {
  23621. if (cb) cb(err, results);
  23622. cb = null;
  23623. }
  23624. if (isSync) queueMicrotask$1(end);
  23625. else end();
  23626. }
  23627. function each (i, err, result) {
  23628. results[i] = result;
  23629. if (--pending === 0 || err) {
  23630. done(err);
  23631. }
  23632. }
  23633. if (!pending) {
  23634. // empty
  23635. done(null);
  23636. } else if (keys) {
  23637. // object
  23638. keys.forEach(function (key) {
  23639. tasks[key](function (err, result) { each(key, err, result); });
  23640. });
  23641. } else {
  23642. // array
  23643. tasks.forEach(function (task, i) {
  23644. task(function (err, result) { each(i, err, result); });
  23645. });
  23646. }
  23647. isSync = false;
  23648. }
  23649. var constants$2 = {};
  23650. Object.defineProperty(constants$2, "__esModule", { value: true });
  23651. constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
  23652. const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
  23653. if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
  23654. throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
  23655. }
  23656. const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
  23657. const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
  23658. const SUPPORTED_MAJOR_VERSION = 10;
  23659. const SUPPORTED_MINOR_VERSION = 10;
  23660. const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
  23661. const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
  23662. /**
  23663. * IS `true` for Node.js 10.10 and greater.
  23664. */
  23665. constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
  23666. var utils$9 = {};
  23667. var fs$d = {};
  23668. Object.defineProperty(fs$d, "__esModule", { value: true });
  23669. fs$d.createDirentFromStats = void 0;
  23670. class DirentFromStats {
  23671. constructor(name, stats) {
  23672. this.name = name;
  23673. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  23674. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  23675. this.isDirectory = stats.isDirectory.bind(stats);
  23676. this.isFIFO = stats.isFIFO.bind(stats);
  23677. this.isFile = stats.isFile.bind(stats);
  23678. this.isSocket = stats.isSocket.bind(stats);
  23679. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  23680. }
  23681. }
  23682. function createDirentFromStats(name, stats) {
  23683. return new DirentFromStats(name, stats);
  23684. }
  23685. fs$d.createDirentFromStats = createDirentFromStats;
  23686. Object.defineProperty(utils$9, "__esModule", { value: true });
  23687. utils$9.fs = void 0;
  23688. const fs$c = fs$d;
  23689. utils$9.fs = fs$c;
  23690. var common$a = {};
  23691. Object.defineProperty(common$a, "__esModule", { value: true });
  23692. common$a.joinPathSegments = void 0;
  23693. function joinPathSegments$1(a, b, separator) {
  23694. /**
  23695. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  23696. */
  23697. if (a.endsWith(separator)) {
  23698. return a + b;
  23699. }
  23700. return a + separator + b;
  23701. }
  23702. common$a.joinPathSegments = joinPathSegments$1;
  23703. Object.defineProperty(async$3, "__esModule", { value: true });
  23704. async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0;
  23705. const fsStat$5 = out$1;
  23706. const rpl = runParallel_1;
  23707. const constants_1$1 = constants$2;
  23708. const utils$8 = utils$9;
  23709. const common$9 = common$a;
  23710. function read$1(directory, settings, callback) {
  23711. if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  23712. readdirWithFileTypes$1(directory, settings, callback);
  23713. return;
  23714. }
  23715. readdir$3(directory, settings, callback);
  23716. }
  23717. async$3.read = read$1;
  23718. function readdirWithFileTypes$1(directory, settings, callback) {
  23719. settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
  23720. if (readdirError !== null) {
  23721. callFailureCallback$1(callback, readdirError);
  23722. return;
  23723. }
  23724. const entries = dirents.map((dirent) => ({
  23725. dirent,
  23726. name: dirent.name,
  23727. path: common$9.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  23728. }));
  23729. if (!settings.followSymbolicLinks) {
  23730. callSuccessCallback$1(callback, entries);
  23731. return;
  23732. }
  23733. const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
  23734. rpl(tasks, (rplError, rplEntries) => {
  23735. if (rplError !== null) {
  23736. callFailureCallback$1(callback, rplError);
  23737. return;
  23738. }
  23739. callSuccessCallback$1(callback, rplEntries);
  23740. });
  23741. });
  23742. }
  23743. async$3.readdirWithFileTypes = readdirWithFileTypes$1;
  23744. function makeRplTaskEntry(entry, settings) {
  23745. return (done) => {
  23746. if (!entry.dirent.isSymbolicLink()) {
  23747. done(null, entry);
  23748. return;
  23749. }
  23750. settings.fs.stat(entry.path, (statError, stats) => {
  23751. if (statError !== null) {
  23752. if (settings.throwErrorOnBrokenSymbolicLink) {
  23753. done(statError);
  23754. return;
  23755. }
  23756. done(null, entry);
  23757. return;
  23758. }
  23759. entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats);
  23760. done(null, entry);
  23761. });
  23762. };
  23763. }
  23764. function readdir$3(directory, settings, callback) {
  23765. settings.fs.readdir(directory, (readdirError, names) => {
  23766. if (readdirError !== null) {
  23767. callFailureCallback$1(callback, readdirError);
  23768. return;
  23769. }
  23770. const tasks = names.map((name) => {
  23771. const path = common$9.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  23772. return (done) => {
  23773. fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => {
  23774. if (error !== null) {
  23775. done(error);
  23776. return;
  23777. }
  23778. const entry = {
  23779. name,
  23780. path,
  23781. dirent: utils$8.fs.createDirentFromStats(name, stats)
  23782. };
  23783. if (settings.stats) {
  23784. entry.stats = stats;
  23785. }
  23786. done(null, entry);
  23787. });
  23788. };
  23789. });
  23790. rpl(tasks, (rplError, entries) => {
  23791. if (rplError !== null) {
  23792. callFailureCallback$1(callback, rplError);
  23793. return;
  23794. }
  23795. callSuccessCallback$1(callback, entries);
  23796. });
  23797. });
  23798. }
  23799. async$3.readdir = readdir$3;
  23800. function callFailureCallback$1(callback, error) {
  23801. callback(error);
  23802. }
  23803. function callSuccessCallback$1(callback, result) {
  23804. callback(null, result);
  23805. }
  23806. var sync$6 = {};
  23807. Object.defineProperty(sync$6, "__esModule", { value: true });
  23808. sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0;
  23809. const fsStat$4 = out$1;
  23810. const constants_1 = constants$2;
  23811. const utils$7 = utils$9;
  23812. const common$8 = common$a;
  23813. function read(directory, settings) {
  23814. if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  23815. return readdirWithFileTypes(directory, settings);
  23816. }
  23817. return readdir$2(directory, settings);
  23818. }
  23819. sync$6.read = read;
  23820. function readdirWithFileTypes(directory, settings) {
  23821. const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
  23822. return dirents.map((dirent) => {
  23823. const entry = {
  23824. dirent,
  23825. name: dirent.name,
  23826. path: common$8.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  23827. };
  23828. if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
  23829. try {
  23830. const stats = settings.fs.statSync(entry.path);
  23831. entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats);
  23832. }
  23833. catch (error) {
  23834. if (settings.throwErrorOnBrokenSymbolicLink) {
  23835. throw error;
  23836. }
  23837. }
  23838. }
  23839. return entry;
  23840. });
  23841. }
  23842. sync$6.readdirWithFileTypes = readdirWithFileTypes;
  23843. function readdir$2(directory, settings) {
  23844. const names = settings.fs.readdirSync(directory);
  23845. return names.map((name) => {
  23846. const entryPath = common$8.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  23847. const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings);
  23848. const entry = {
  23849. name,
  23850. path: entryPath,
  23851. dirent: utils$7.fs.createDirentFromStats(name, stats)
  23852. };
  23853. if (settings.stats) {
  23854. entry.stats = stats;
  23855. }
  23856. return entry;
  23857. });
  23858. }
  23859. sync$6.readdir = readdir$2;
  23860. var settings$2 = {};
  23861. var fs$b = {};
  23862. (function (exports) {
  23863. Object.defineProperty(exports, "__esModule", { value: true });
  23864. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  23865. const fs = require$$0__default;
  23866. exports.FILE_SYSTEM_ADAPTER = {
  23867. lstat: fs.lstat,
  23868. stat: fs.stat,
  23869. lstatSync: fs.lstatSync,
  23870. statSync: fs.statSync,
  23871. readdir: fs.readdir,
  23872. readdirSync: fs.readdirSync
  23873. };
  23874. function createFileSystemAdapter(fsMethods) {
  23875. if (fsMethods === undefined) {
  23876. return exports.FILE_SYSTEM_ADAPTER;
  23877. }
  23878. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  23879. }
  23880. exports.createFileSystemAdapter = createFileSystemAdapter;
  23881. } (fs$b));
  23882. Object.defineProperty(settings$2, "__esModule", { value: true });
  23883. const path$d = require$$0$4;
  23884. const fsStat$3 = out$1;
  23885. const fs$a = fs$b;
  23886. let Settings$1 = class Settings {
  23887. constructor(_options = {}) {
  23888. this._options = _options;
  23889. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
  23890. this.fs = fs$a.createFileSystemAdapter(this._options.fs);
  23891. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$d.sep);
  23892. this.stats = this._getValue(this._options.stats, false);
  23893. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  23894. this.fsStatSettings = new fsStat$3.Settings({
  23895. followSymbolicLink: this.followSymbolicLinks,
  23896. fs: this.fs,
  23897. throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
  23898. });
  23899. }
  23900. _getValue(option, value) {
  23901. return option !== null && option !== void 0 ? option : value;
  23902. }
  23903. };
  23904. settings$2.default = Settings$1;
  23905. Object.defineProperty(out$2, "__esModule", { value: true });
  23906. out$2.Settings = out$2.scandirSync = out$2.scandir = void 0;
  23907. const async = async$3;
  23908. const sync$5 = sync$6;
  23909. const settings_1$2 = settings$2;
  23910. out$2.Settings = settings_1$2.default;
  23911. function scandir(path, optionsOrSettingsOrCallback, callback) {
  23912. if (typeof optionsOrSettingsOrCallback === 'function') {
  23913. async.read(path, getSettings$1(), optionsOrSettingsOrCallback);
  23914. return;
  23915. }
  23916. async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback);
  23917. }
  23918. out$2.scandir = scandir;
  23919. function scandirSync(path, optionsOrSettings) {
  23920. const settings = getSettings$1(optionsOrSettings);
  23921. return sync$5.read(path, settings);
  23922. }
  23923. out$2.scandirSync = scandirSync;
  23924. function getSettings$1(settingsOrOptions = {}) {
  23925. if (settingsOrOptions instanceof settings_1$2.default) {
  23926. return settingsOrOptions;
  23927. }
  23928. return new settings_1$2.default(settingsOrOptions);
  23929. }
  23930. var queue = {exports: {}};
  23931. function reusify$1 (Constructor) {
  23932. var head = new Constructor();
  23933. var tail = head;
  23934. function get () {
  23935. var current = head;
  23936. if (current.next) {
  23937. head = current.next;
  23938. } else {
  23939. head = new Constructor();
  23940. tail = head;
  23941. }
  23942. current.next = null;
  23943. return current
  23944. }
  23945. function release (obj) {
  23946. tail.next = obj;
  23947. tail = obj;
  23948. }
  23949. return {
  23950. get: get,
  23951. release: release
  23952. }
  23953. }
  23954. var reusify_1 = reusify$1;
  23955. /* eslint-disable no-var */
  23956. var reusify = reusify_1;
  23957. function fastqueue (context, worker, concurrency) {
  23958. if (typeof context === 'function') {
  23959. concurrency = worker;
  23960. worker = context;
  23961. context = null;
  23962. }
  23963. if (concurrency < 1) {
  23964. throw new Error('fastqueue concurrency must be greater than 1')
  23965. }
  23966. var cache = reusify(Task);
  23967. var queueHead = null;
  23968. var queueTail = null;
  23969. var _running = 0;
  23970. var errorHandler = null;
  23971. var self = {
  23972. push: push,
  23973. drain: noop$3,
  23974. saturated: noop$3,
  23975. pause: pause,
  23976. paused: false,
  23977. concurrency: concurrency,
  23978. running: running,
  23979. resume: resume,
  23980. idle: idle,
  23981. length: length,
  23982. getQueue: getQueue,
  23983. unshift: unshift,
  23984. empty: noop$3,
  23985. kill: kill,
  23986. killAndDrain: killAndDrain,
  23987. error: error
  23988. };
  23989. return self
  23990. function running () {
  23991. return _running
  23992. }
  23993. function pause () {
  23994. self.paused = true;
  23995. }
  23996. function length () {
  23997. var current = queueHead;
  23998. var counter = 0;
  23999. while (current) {
  24000. current = current.next;
  24001. counter++;
  24002. }
  24003. return counter
  24004. }
  24005. function getQueue () {
  24006. var current = queueHead;
  24007. var tasks = [];
  24008. while (current) {
  24009. tasks.push(current.value);
  24010. current = current.next;
  24011. }
  24012. return tasks
  24013. }
  24014. function resume () {
  24015. if (!self.paused) return
  24016. self.paused = false;
  24017. for (var i = 0; i < self.concurrency; i++) {
  24018. _running++;
  24019. release();
  24020. }
  24021. }
  24022. function idle () {
  24023. return _running === 0 && self.length() === 0
  24024. }
  24025. function push (value, done) {
  24026. var current = cache.get();
  24027. current.context = context;
  24028. current.release = release;
  24029. current.value = value;
  24030. current.callback = done || noop$3;
  24031. current.errorHandler = errorHandler;
  24032. if (_running === self.concurrency || self.paused) {
  24033. if (queueTail) {
  24034. queueTail.next = current;
  24035. queueTail = current;
  24036. } else {
  24037. queueHead = current;
  24038. queueTail = current;
  24039. self.saturated();
  24040. }
  24041. } else {
  24042. _running++;
  24043. worker.call(context, current.value, current.worked);
  24044. }
  24045. }
  24046. function unshift (value, done) {
  24047. var current = cache.get();
  24048. current.context = context;
  24049. current.release = release;
  24050. current.value = value;
  24051. current.callback = done || noop$3;
  24052. if (_running === self.concurrency || self.paused) {
  24053. if (queueHead) {
  24054. current.next = queueHead;
  24055. queueHead = current;
  24056. } else {
  24057. queueHead = current;
  24058. queueTail = current;
  24059. self.saturated();
  24060. }
  24061. } else {
  24062. _running++;
  24063. worker.call(context, current.value, current.worked);
  24064. }
  24065. }
  24066. function release (holder) {
  24067. if (holder) {
  24068. cache.release(holder);
  24069. }
  24070. var next = queueHead;
  24071. if (next) {
  24072. if (!self.paused) {
  24073. if (queueTail === queueHead) {
  24074. queueTail = null;
  24075. }
  24076. queueHead = next.next;
  24077. next.next = null;
  24078. worker.call(context, next.value, next.worked);
  24079. if (queueTail === null) {
  24080. self.empty();
  24081. }
  24082. } else {
  24083. _running--;
  24084. }
  24085. } else if (--_running === 0) {
  24086. self.drain();
  24087. }
  24088. }
  24089. function kill () {
  24090. queueHead = null;
  24091. queueTail = null;
  24092. self.drain = noop$3;
  24093. }
  24094. function killAndDrain () {
  24095. queueHead = null;
  24096. queueTail = null;
  24097. self.drain();
  24098. self.drain = noop$3;
  24099. }
  24100. function error (handler) {
  24101. errorHandler = handler;
  24102. }
  24103. }
  24104. function noop$3 () {}
  24105. function Task () {
  24106. this.value = null;
  24107. this.callback = noop$3;
  24108. this.next = null;
  24109. this.release = noop$3;
  24110. this.context = null;
  24111. this.errorHandler = null;
  24112. var self = this;
  24113. this.worked = function worked (err, result) {
  24114. var callback = self.callback;
  24115. var errorHandler = self.errorHandler;
  24116. var val = self.value;
  24117. self.value = null;
  24118. self.callback = noop$3;
  24119. if (self.errorHandler) {
  24120. errorHandler(err, val);
  24121. }
  24122. callback.call(self.context, err, result);
  24123. self.release(self);
  24124. };
  24125. }
  24126. function queueAsPromised (context, worker, concurrency) {
  24127. if (typeof context === 'function') {
  24128. concurrency = worker;
  24129. worker = context;
  24130. context = null;
  24131. }
  24132. function asyncWrapper (arg, cb) {
  24133. worker.call(this, arg)
  24134. .then(function (res) {
  24135. cb(null, res);
  24136. }, cb);
  24137. }
  24138. var queue = fastqueue(context, asyncWrapper, concurrency);
  24139. var pushCb = queue.push;
  24140. var unshiftCb = queue.unshift;
  24141. queue.push = push;
  24142. queue.unshift = unshift;
  24143. queue.drained = drained;
  24144. return queue
  24145. function push (value) {
  24146. var p = new Promise(function (resolve, reject) {
  24147. pushCb(value, function (err, result) {
  24148. if (err) {
  24149. reject(err);
  24150. return
  24151. }
  24152. resolve(result);
  24153. });
  24154. });
  24155. // Let's fork the promise chain to
  24156. // make the error bubble up to the user but
  24157. // not lead to a unhandledRejection
  24158. p.catch(noop$3);
  24159. return p
  24160. }
  24161. function unshift (value) {
  24162. var p = new Promise(function (resolve, reject) {
  24163. unshiftCb(value, function (err, result) {
  24164. if (err) {
  24165. reject(err);
  24166. return
  24167. }
  24168. resolve(result);
  24169. });
  24170. });
  24171. // Let's fork the promise chain to
  24172. // make the error bubble up to the user but
  24173. // not lead to a unhandledRejection
  24174. p.catch(noop$3);
  24175. return p
  24176. }
  24177. function drained () {
  24178. var previousDrain = queue.drain;
  24179. var p = new Promise(function (resolve) {
  24180. queue.drain = function () {
  24181. previousDrain();
  24182. resolve();
  24183. };
  24184. });
  24185. return p
  24186. }
  24187. }
  24188. queue.exports = fastqueue;
  24189. queue.exports.promise = queueAsPromised;
  24190. var queueExports = queue.exports;
  24191. var common$7 = {};
  24192. Object.defineProperty(common$7, "__esModule", { value: true });
  24193. common$7.joinPathSegments = common$7.replacePathSegmentSeparator = common$7.isAppliedFilter = common$7.isFatalError = void 0;
  24194. function isFatalError(settings, error) {
  24195. if (settings.errorFilter === null) {
  24196. return true;
  24197. }
  24198. return !settings.errorFilter(error);
  24199. }
  24200. common$7.isFatalError = isFatalError;
  24201. function isAppliedFilter(filter, value) {
  24202. return filter === null || filter(value);
  24203. }
  24204. common$7.isAppliedFilter = isAppliedFilter;
  24205. function replacePathSegmentSeparator(filepath, separator) {
  24206. return filepath.split(/[/\\]/).join(separator);
  24207. }
  24208. common$7.replacePathSegmentSeparator = replacePathSegmentSeparator;
  24209. function joinPathSegments(a, b, separator) {
  24210. if (a === '') {
  24211. return b;
  24212. }
  24213. /**
  24214. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  24215. */
  24216. if (a.endsWith(separator)) {
  24217. return a + b;
  24218. }
  24219. return a + separator + b;
  24220. }
  24221. common$7.joinPathSegments = joinPathSegments;
  24222. var reader$1 = {};
  24223. Object.defineProperty(reader$1, "__esModule", { value: true });
  24224. const common$6 = common$7;
  24225. let Reader$1 = class Reader {
  24226. constructor(_root, _settings) {
  24227. this._root = _root;
  24228. this._settings = _settings;
  24229. this._root = common$6.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
  24230. }
  24231. };
  24232. reader$1.default = Reader$1;
  24233. Object.defineProperty(async$4, "__esModule", { value: true });
  24234. const events_1 = require$$0$5;
  24235. const fsScandir$2 = out$2;
  24236. const fastq = queueExports;
  24237. const common$5 = common$7;
  24238. const reader_1$4 = reader$1;
  24239. class AsyncReader extends reader_1$4.default {
  24240. constructor(_root, _settings) {
  24241. super(_root, _settings);
  24242. this._settings = _settings;
  24243. this._scandir = fsScandir$2.scandir;
  24244. this._emitter = new events_1.EventEmitter();
  24245. this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
  24246. this._isFatalError = false;
  24247. this._isDestroyed = false;
  24248. this._queue.drain = () => {
  24249. if (!this._isFatalError) {
  24250. this._emitter.emit('end');
  24251. }
  24252. };
  24253. }
  24254. read() {
  24255. this._isFatalError = false;
  24256. this._isDestroyed = false;
  24257. setImmediate(() => {
  24258. this._pushToQueue(this._root, this._settings.basePath);
  24259. });
  24260. return this._emitter;
  24261. }
  24262. get isDestroyed() {
  24263. return this._isDestroyed;
  24264. }
  24265. destroy() {
  24266. if (this._isDestroyed) {
  24267. throw new Error('The reader is already destroyed');
  24268. }
  24269. this._isDestroyed = true;
  24270. this._queue.killAndDrain();
  24271. }
  24272. onEntry(callback) {
  24273. this._emitter.on('entry', callback);
  24274. }
  24275. onError(callback) {
  24276. this._emitter.once('error', callback);
  24277. }
  24278. onEnd(callback) {
  24279. this._emitter.once('end', callback);
  24280. }
  24281. _pushToQueue(directory, base) {
  24282. const queueItem = { directory, base };
  24283. this._queue.push(queueItem, (error) => {
  24284. if (error !== null) {
  24285. this._handleError(error);
  24286. }
  24287. });
  24288. }
  24289. _worker(item, done) {
  24290. this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
  24291. if (error !== null) {
  24292. done(error, undefined);
  24293. return;
  24294. }
  24295. for (const entry of entries) {
  24296. this._handleEntry(entry, item.base);
  24297. }
  24298. done(null, undefined);
  24299. });
  24300. }
  24301. _handleError(error) {
  24302. if (this._isDestroyed || !common$5.isFatalError(this._settings, error)) {
  24303. return;
  24304. }
  24305. this._isFatalError = true;
  24306. this._isDestroyed = true;
  24307. this._emitter.emit('error', error);
  24308. }
  24309. _handleEntry(entry, base) {
  24310. if (this._isDestroyed || this._isFatalError) {
  24311. return;
  24312. }
  24313. const fullpath = entry.path;
  24314. if (base !== undefined) {
  24315. entry.path = common$5.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  24316. }
  24317. if (common$5.isAppliedFilter(this._settings.entryFilter, entry)) {
  24318. this._emitEntry(entry);
  24319. }
  24320. if (entry.dirent.isDirectory() && common$5.isAppliedFilter(this._settings.deepFilter, entry)) {
  24321. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  24322. }
  24323. }
  24324. _emitEntry(entry) {
  24325. this._emitter.emit('entry', entry);
  24326. }
  24327. }
  24328. async$4.default = AsyncReader;
  24329. Object.defineProperty(async$5, "__esModule", { value: true });
  24330. const async_1$4 = async$4;
  24331. class AsyncProvider {
  24332. constructor(_root, _settings) {
  24333. this._root = _root;
  24334. this._settings = _settings;
  24335. this._reader = new async_1$4.default(this._root, this._settings);
  24336. this._storage = [];
  24337. }
  24338. read(callback) {
  24339. this._reader.onError((error) => {
  24340. callFailureCallback(callback, error);
  24341. });
  24342. this._reader.onEntry((entry) => {
  24343. this._storage.push(entry);
  24344. });
  24345. this._reader.onEnd(() => {
  24346. callSuccessCallback(callback, this._storage);
  24347. });
  24348. this._reader.read();
  24349. }
  24350. }
  24351. async$5.default = AsyncProvider;
  24352. function callFailureCallback(callback, error) {
  24353. callback(error);
  24354. }
  24355. function callSuccessCallback(callback, entries) {
  24356. callback(null, entries);
  24357. }
  24358. var stream$2 = {};
  24359. Object.defineProperty(stream$2, "__esModule", { value: true });
  24360. const stream_1$5 = require$$0$7;
  24361. const async_1$3 = async$4;
  24362. class StreamProvider {
  24363. constructor(_root, _settings) {
  24364. this._root = _root;
  24365. this._settings = _settings;
  24366. this._reader = new async_1$3.default(this._root, this._settings);
  24367. this._stream = new stream_1$5.Readable({
  24368. objectMode: true,
  24369. read: () => { },
  24370. destroy: () => {
  24371. if (!this._reader.isDestroyed) {
  24372. this._reader.destroy();
  24373. }
  24374. }
  24375. });
  24376. }
  24377. read() {
  24378. this._reader.onError((error) => {
  24379. this._stream.emit('error', error);
  24380. });
  24381. this._reader.onEntry((entry) => {
  24382. this._stream.push(entry);
  24383. });
  24384. this._reader.onEnd(() => {
  24385. this._stream.push(null);
  24386. });
  24387. this._reader.read();
  24388. return this._stream;
  24389. }
  24390. }
  24391. stream$2.default = StreamProvider;
  24392. var sync$4 = {};
  24393. var sync$3 = {};
  24394. Object.defineProperty(sync$3, "__esModule", { value: true });
  24395. const fsScandir$1 = out$2;
  24396. const common$4 = common$7;
  24397. const reader_1$3 = reader$1;
  24398. class SyncReader extends reader_1$3.default {
  24399. constructor() {
  24400. super(...arguments);
  24401. this._scandir = fsScandir$1.scandirSync;
  24402. this._storage = [];
  24403. this._queue = new Set();
  24404. }
  24405. read() {
  24406. this._pushToQueue(this._root, this._settings.basePath);
  24407. this._handleQueue();
  24408. return this._storage;
  24409. }
  24410. _pushToQueue(directory, base) {
  24411. this._queue.add({ directory, base });
  24412. }
  24413. _handleQueue() {
  24414. for (const item of this._queue.values()) {
  24415. this._handleDirectory(item.directory, item.base);
  24416. }
  24417. }
  24418. _handleDirectory(directory, base) {
  24419. try {
  24420. const entries = this._scandir(directory, this._settings.fsScandirSettings);
  24421. for (const entry of entries) {
  24422. this._handleEntry(entry, base);
  24423. }
  24424. }
  24425. catch (error) {
  24426. this._handleError(error);
  24427. }
  24428. }
  24429. _handleError(error) {
  24430. if (!common$4.isFatalError(this._settings, error)) {
  24431. return;
  24432. }
  24433. throw error;
  24434. }
  24435. _handleEntry(entry, base) {
  24436. const fullpath = entry.path;
  24437. if (base !== undefined) {
  24438. entry.path = common$4.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  24439. }
  24440. if (common$4.isAppliedFilter(this._settings.entryFilter, entry)) {
  24441. this._pushToStorage(entry);
  24442. }
  24443. if (entry.dirent.isDirectory() && common$4.isAppliedFilter(this._settings.deepFilter, entry)) {
  24444. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  24445. }
  24446. }
  24447. _pushToStorage(entry) {
  24448. this._storage.push(entry);
  24449. }
  24450. }
  24451. sync$3.default = SyncReader;
  24452. Object.defineProperty(sync$4, "__esModule", { value: true });
  24453. const sync_1$3 = sync$3;
  24454. class SyncProvider {
  24455. constructor(_root, _settings) {
  24456. this._root = _root;
  24457. this._settings = _settings;
  24458. this._reader = new sync_1$3.default(this._root, this._settings);
  24459. }
  24460. read() {
  24461. return this._reader.read();
  24462. }
  24463. }
  24464. sync$4.default = SyncProvider;
  24465. var settings$1 = {};
  24466. Object.defineProperty(settings$1, "__esModule", { value: true });
  24467. const path$c = require$$0$4;
  24468. const fsScandir = out$2;
  24469. class Settings {
  24470. constructor(_options = {}) {
  24471. this._options = _options;
  24472. this.basePath = this._getValue(this._options.basePath, undefined);
  24473. this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
  24474. this.deepFilter = this._getValue(this._options.deepFilter, null);
  24475. this.entryFilter = this._getValue(this._options.entryFilter, null);
  24476. this.errorFilter = this._getValue(this._options.errorFilter, null);
  24477. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$c.sep);
  24478. this.fsScandirSettings = new fsScandir.Settings({
  24479. followSymbolicLinks: this._options.followSymbolicLinks,
  24480. fs: this._options.fs,
  24481. pathSegmentSeparator: this._options.pathSegmentSeparator,
  24482. stats: this._options.stats,
  24483. throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
  24484. });
  24485. }
  24486. _getValue(option, value) {
  24487. return option !== null && option !== void 0 ? option : value;
  24488. }
  24489. }
  24490. settings$1.default = Settings;
  24491. Object.defineProperty(out$3, "__esModule", { value: true });
  24492. out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0;
  24493. const async_1$2 = async$5;
  24494. const stream_1$4 = stream$2;
  24495. const sync_1$2 = sync$4;
  24496. const settings_1$1 = settings$1;
  24497. out$3.Settings = settings_1$1.default;
  24498. function walk$2(directory, optionsOrSettingsOrCallback, callback) {
  24499. if (typeof optionsOrSettingsOrCallback === 'function') {
  24500. new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
  24501. return;
  24502. }
  24503. new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
  24504. }
  24505. out$3.walk = walk$2;
  24506. function walkSync(directory, optionsOrSettings) {
  24507. const settings = getSettings(optionsOrSettings);
  24508. const provider = new sync_1$2.default(directory, settings);
  24509. return provider.read();
  24510. }
  24511. out$3.walkSync = walkSync;
  24512. function walkStream(directory, optionsOrSettings) {
  24513. const settings = getSettings(optionsOrSettings);
  24514. const provider = new stream_1$4.default(directory, settings);
  24515. return provider.read();
  24516. }
  24517. out$3.walkStream = walkStream;
  24518. function getSettings(settingsOrOptions = {}) {
  24519. if (settingsOrOptions instanceof settings_1$1.default) {
  24520. return settingsOrOptions;
  24521. }
  24522. return new settings_1$1.default(settingsOrOptions);
  24523. }
  24524. var reader = {};
  24525. Object.defineProperty(reader, "__esModule", { value: true });
  24526. const path$b = require$$0$4;
  24527. const fsStat$2 = out$1;
  24528. const utils$6 = utils$g;
  24529. class Reader {
  24530. constructor(_settings) {
  24531. this._settings = _settings;
  24532. this._fsStatSettings = new fsStat$2.Settings({
  24533. followSymbolicLink: this._settings.followSymbolicLinks,
  24534. fs: this._settings.fs,
  24535. throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
  24536. });
  24537. }
  24538. _getFullEntryPath(filepath) {
  24539. return path$b.resolve(this._settings.cwd, filepath);
  24540. }
  24541. _makeEntry(stats, pattern) {
  24542. const entry = {
  24543. name: pattern,
  24544. path: pattern,
  24545. dirent: utils$6.fs.createDirentFromStats(pattern, stats)
  24546. };
  24547. if (this._settings.stats) {
  24548. entry.stats = stats;
  24549. }
  24550. return entry;
  24551. }
  24552. _isFatalError(error) {
  24553. return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
  24554. }
  24555. }
  24556. reader.default = Reader;
  24557. var stream$1 = {};
  24558. Object.defineProperty(stream$1, "__esModule", { value: true });
  24559. const stream_1$3 = require$$0$7;
  24560. const fsStat$1 = out$1;
  24561. const fsWalk$2 = out$3;
  24562. const reader_1$2 = reader;
  24563. class ReaderStream extends reader_1$2.default {
  24564. constructor() {
  24565. super(...arguments);
  24566. this._walkStream = fsWalk$2.walkStream;
  24567. this._stat = fsStat$1.stat;
  24568. }
  24569. dynamic(root, options) {
  24570. return this._walkStream(root, options);
  24571. }
  24572. static(patterns, options) {
  24573. const filepaths = patterns.map(this._getFullEntryPath, this);
  24574. const stream = new stream_1$3.PassThrough({ objectMode: true });
  24575. stream._write = (index, _enc, done) => {
  24576. return this._getEntry(filepaths[index], patterns[index], options)
  24577. .then((entry) => {
  24578. if (entry !== null && options.entryFilter(entry)) {
  24579. stream.push(entry);
  24580. }
  24581. if (index === filepaths.length - 1) {
  24582. stream.end();
  24583. }
  24584. done();
  24585. })
  24586. .catch(done);
  24587. };
  24588. for (let i = 0; i < filepaths.length; i++) {
  24589. stream.write(i);
  24590. }
  24591. return stream;
  24592. }
  24593. _getEntry(filepath, pattern, options) {
  24594. return this._getStat(filepath)
  24595. .then((stats) => this._makeEntry(stats, pattern))
  24596. .catch((error) => {
  24597. if (options.errorFilter(error)) {
  24598. return null;
  24599. }
  24600. throw error;
  24601. });
  24602. }
  24603. _getStat(filepath) {
  24604. return new Promise((resolve, reject) => {
  24605. this._stat(filepath, this._fsStatSettings, (error, stats) => {
  24606. return error === null ? resolve(stats) : reject(error);
  24607. });
  24608. });
  24609. }
  24610. }
  24611. stream$1.default = ReaderStream;
  24612. Object.defineProperty(async$6, "__esModule", { value: true });
  24613. const fsWalk$1 = out$3;
  24614. const reader_1$1 = reader;
  24615. const stream_1$2 = stream$1;
  24616. class ReaderAsync extends reader_1$1.default {
  24617. constructor() {
  24618. super(...arguments);
  24619. this._walkAsync = fsWalk$1.walk;
  24620. this._readerStream = new stream_1$2.default(this._settings);
  24621. }
  24622. dynamic(root, options) {
  24623. return new Promise((resolve, reject) => {
  24624. this._walkAsync(root, options, (error, entries) => {
  24625. if (error === null) {
  24626. resolve(entries);
  24627. }
  24628. else {
  24629. reject(error);
  24630. }
  24631. });
  24632. });
  24633. }
  24634. async static(patterns, options) {
  24635. const entries = [];
  24636. const stream = this._readerStream.static(patterns, options);
  24637. // After #235, replace it with an asynchronous iterator.
  24638. return new Promise((resolve, reject) => {
  24639. stream.once('error', reject);
  24640. stream.on('data', (entry) => entries.push(entry));
  24641. stream.once('end', () => resolve(entries));
  24642. });
  24643. }
  24644. }
  24645. async$6.default = ReaderAsync;
  24646. var provider = {};
  24647. var deep = {};
  24648. var partial = {};
  24649. var matcher = {};
  24650. Object.defineProperty(matcher, "__esModule", { value: true });
  24651. const utils$5 = utils$g;
  24652. class Matcher {
  24653. constructor(_patterns, _settings, _micromatchOptions) {
  24654. this._patterns = _patterns;
  24655. this._settings = _settings;
  24656. this._micromatchOptions = _micromatchOptions;
  24657. this._storage = [];
  24658. this._fillStorage();
  24659. }
  24660. _fillStorage() {
  24661. /**
  24662. * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
  24663. * So, before expand patterns with brace expansion into separated patterns.
  24664. */
  24665. const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns);
  24666. for (const pattern of patterns) {
  24667. const segments = this._getPatternSegments(pattern);
  24668. const sections = this._splitSegmentsIntoSections(segments);
  24669. this._storage.push({
  24670. complete: sections.length <= 1,
  24671. pattern,
  24672. segments,
  24673. sections
  24674. });
  24675. }
  24676. }
  24677. _getPatternSegments(pattern) {
  24678. const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions);
  24679. return parts.map((part) => {
  24680. const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings);
  24681. if (!dynamic) {
  24682. return {
  24683. dynamic: false,
  24684. pattern: part
  24685. };
  24686. }
  24687. return {
  24688. dynamic: true,
  24689. pattern: part,
  24690. patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions)
  24691. };
  24692. });
  24693. }
  24694. _splitSegmentsIntoSections(segments) {
  24695. return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern));
  24696. }
  24697. }
  24698. matcher.default = Matcher;
  24699. Object.defineProperty(partial, "__esModule", { value: true });
  24700. const matcher_1 = matcher;
  24701. class PartialMatcher extends matcher_1.default {
  24702. match(filepath) {
  24703. const parts = filepath.split('/');
  24704. const levels = parts.length;
  24705. const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
  24706. for (const pattern of patterns) {
  24707. const section = pattern.sections[0];
  24708. /**
  24709. * In this case, the pattern has a globstar and we must read all directories unconditionally,
  24710. * but only if the level has reached the end of the first group.
  24711. *
  24712. * fixtures/{a,b}/**
  24713. * ^ true/false ^ always true
  24714. */
  24715. if (!pattern.complete && levels > section.length) {
  24716. return true;
  24717. }
  24718. const match = parts.every((part, index) => {
  24719. const segment = pattern.segments[index];
  24720. if (segment.dynamic && segment.patternRe.test(part)) {
  24721. return true;
  24722. }
  24723. if (!segment.dynamic && segment.pattern === part) {
  24724. return true;
  24725. }
  24726. return false;
  24727. });
  24728. if (match) {
  24729. return true;
  24730. }
  24731. }
  24732. return false;
  24733. }
  24734. }
  24735. partial.default = PartialMatcher;
  24736. Object.defineProperty(deep, "__esModule", { value: true });
  24737. const utils$4 = utils$g;
  24738. const partial_1 = partial;
  24739. class DeepFilter {
  24740. constructor(_settings, _micromatchOptions) {
  24741. this._settings = _settings;
  24742. this._micromatchOptions = _micromatchOptions;
  24743. }
  24744. getFilter(basePath, positive, negative) {
  24745. const matcher = this._getMatcher(positive);
  24746. const negativeRe = this._getNegativePatternsRe(negative);
  24747. return (entry) => this._filter(basePath, entry, matcher, negativeRe);
  24748. }
  24749. _getMatcher(patterns) {
  24750. return new partial_1.default(patterns, this._settings, this._micromatchOptions);
  24751. }
  24752. _getNegativePatternsRe(patterns) {
  24753. const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
  24754. return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
  24755. }
  24756. _filter(basePath, entry, matcher, negativeRe) {
  24757. if (this._isSkippedByDeep(basePath, entry.path)) {
  24758. return false;
  24759. }
  24760. if (this._isSkippedSymbolicLink(entry)) {
  24761. return false;
  24762. }
  24763. const filepath = utils$4.path.removeLeadingDotSegment(entry.path);
  24764. if (this._isSkippedByPositivePatterns(filepath, matcher)) {
  24765. return false;
  24766. }
  24767. return this._isSkippedByNegativePatterns(filepath, negativeRe);
  24768. }
  24769. _isSkippedByDeep(basePath, entryPath) {
  24770. /**
  24771. * Avoid unnecessary depth calculations when it doesn't matter.
  24772. */
  24773. if (this._settings.deep === Infinity) {
  24774. return false;
  24775. }
  24776. return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
  24777. }
  24778. _getEntryLevel(basePath, entryPath) {
  24779. const entryPathDepth = entryPath.split('/').length;
  24780. if (basePath === '') {
  24781. return entryPathDepth;
  24782. }
  24783. const basePathDepth = basePath.split('/').length;
  24784. return entryPathDepth - basePathDepth;
  24785. }
  24786. _isSkippedSymbolicLink(entry) {
  24787. return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
  24788. }
  24789. _isSkippedByPositivePatterns(entryPath, matcher) {
  24790. return !this._settings.baseNameMatch && !matcher.match(entryPath);
  24791. }
  24792. _isSkippedByNegativePatterns(entryPath, patternsRe) {
  24793. return !utils$4.pattern.matchAny(entryPath, patternsRe);
  24794. }
  24795. }
  24796. deep.default = DeepFilter;
  24797. var entry$1 = {};
  24798. Object.defineProperty(entry$1, "__esModule", { value: true });
  24799. const utils$3 = utils$g;
  24800. class EntryFilter {
  24801. constructor(_settings, _micromatchOptions) {
  24802. this._settings = _settings;
  24803. this._micromatchOptions = _micromatchOptions;
  24804. this.index = new Map();
  24805. }
  24806. getFilter(positive, negative) {
  24807. const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
  24808. const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions);
  24809. return (entry) => this._filter(entry, positiveRe, negativeRe);
  24810. }
  24811. _filter(entry, positiveRe, negativeRe) {
  24812. if (this._settings.unique && this._isDuplicateEntry(entry)) {
  24813. return false;
  24814. }
  24815. if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
  24816. return false;
  24817. }
  24818. if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
  24819. return false;
  24820. }
  24821. const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
  24822. const isDirectory = entry.dirent.isDirectory();
  24823. const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(entry.path, negativeRe, isDirectory);
  24824. if (this._settings.unique && isMatched) {
  24825. this._createIndexRecord(entry);
  24826. }
  24827. return isMatched;
  24828. }
  24829. _isDuplicateEntry(entry) {
  24830. return this.index.has(entry.path);
  24831. }
  24832. _createIndexRecord(entry) {
  24833. this.index.set(entry.path, undefined);
  24834. }
  24835. _onlyFileFilter(entry) {
  24836. return this._settings.onlyFiles && !entry.dirent.isFile();
  24837. }
  24838. _onlyDirectoryFilter(entry) {
  24839. return this._settings.onlyDirectories && !entry.dirent.isDirectory();
  24840. }
  24841. _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
  24842. if (!this._settings.absolute) {
  24843. return false;
  24844. }
  24845. const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
  24846. return utils$3.pattern.matchAny(fullpath, patternsRe);
  24847. }
  24848. _isMatchToPatterns(entryPath, patternsRe, isDirectory) {
  24849. const filepath = utils$3.path.removeLeadingDotSegment(entryPath);
  24850. // Trying to match files and directories by patterns.
  24851. const isMatched = utils$3.pattern.matchAny(filepath, patternsRe);
  24852. // A pattern with a trailling slash can be used for directory matching.
  24853. // To apply such pattern, we need to add a tralling slash to the path.
  24854. if (!isMatched && isDirectory) {
  24855. return utils$3.pattern.matchAny(filepath + '/', patternsRe);
  24856. }
  24857. return isMatched;
  24858. }
  24859. }
  24860. entry$1.default = EntryFilter;
  24861. var error$2 = {};
  24862. Object.defineProperty(error$2, "__esModule", { value: true });
  24863. const utils$2 = utils$g;
  24864. class ErrorFilter {
  24865. constructor(_settings) {
  24866. this._settings = _settings;
  24867. }
  24868. getFilter() {
  24869. return (error) => this._isNonFatalError(error);
  24870. }
  24871. _isNonFatalError(error) {
  24872. return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
  24873. }
  24874. }
  24875. error$2.default = ErrorFilter;
  24876. var entry = {};
  24877. Object.defineProperty(entry, "__esModule", { value: true });
  24878. const utils$1 = utils$g;
  24879. class EntryTransformer {
  24880. constructor(_settings) {
  24881. this._settings = _settings;
  24882. }
  24883. getTransformer() {
  24884. return (entry) => this._transform(entry);
  24885. }
  24886. _transform(entry) {
  24887. let filepath = entry.path;
  24888. if (this._settings.absolute) {
  24889. filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath);
  24890. filepath = utils$1.path.unixify(filepath);
  24891. }
  24892. if (this._settings.markDirectories && entry.dirent.isDirectory()) {
  24893. filepath += '/';
  24894. }
  24895. if (!this._settings.objectMode) {
  24896. return filepath;
  24897. }
  24898. return Object.assign(Object.assign({}, entry), { path: filepath });
  24899. }
  24900. }
  24901. entry.default = EntryTransformer;
  24902. Object.defineProperty(provider, "__esModule", { value: true });
  24903. const path$a = require$$0$4;
  24904. const deep_1 = deep;
  24905. const entry_1 = entry$1;
  24906. const error_1 = error$2;
  24907. const entry_2 = entry;
  24908. class Provider {
  24909. constructor(_settings) {
  24910. this._settings = _settings;
  24911. this.errorFilter = new error_1.default(this._settings);
  24912. this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
  24913. this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
  24914. this.entryTransformer = new entry_2.default(this._settings);
  24915. }
  24916. _getRootDirectory(task) {
  24917. return path$a.resolve(this._settings.cwd, task.base);
  24918. }
  24919. _getReaderOptions(task) {
  24920. const basePath = task.base === '.' ? '' : task.base;
  24921. return {
  24922. basePath,
  24923. pathSegmentSeparator: '/',
  24924. concurrency: this._settings.concurrency,
  24925. deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
  24926. entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
  24927. errorFilter: this.errorFilter.getFilter(),
  24928. followSymbolicLinks: this._settings.followSymbolicLinks,
  24929. fs: this._settings.fs,
  24930. stats: this._settings.stats,
  24931. throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
  24932. transform: this.entryTransformer.getTransformer()
  24933. };
  24934. }
  24935. _getMicromatchOptions() {
  24936. return {
  24937. dot: this._settings.dot,
  24938. matchBase: this._settings.baseNameMatch,
  24939. nobrace: !this._settings.braceExpansion,
  24940. nocase: !this._settings.caseSensitiveMatch,
  24941. noext: !this._settings.extglob,
  24942. noglobstar: !this._settings.globstar,
  24943. posix: true,
  24944. strictSlashes: false
  24945. };
  24946. }
  24947. }
  24948. provider.default = Provider;
  24949. Object.defineProperty(async$7, "__esModule", { value: true });
  24950. const async_1$1 = async$6;
  24951. const provider_1$2 = provider;
  24952. class ProviderAsync extends provider_1$2.default {
  24953. constructor() {
  24954. super(...arguments);
  24955. this._reader = new async_1$1.default(this._settings);
  24956. }
  24957. async read(task) {
  24958. const root = this._getRootDirectory(task);
  24959. const options = this._getReaderOptions(task);
  24960. const entries = await this.api(root, task, options);
  24961. return entries.map((entry) => options.transform(entry));
  24962. }
  24963. api(root, task, options) {
  24964. if (task.dynamic) {
  24965. return this._reader.dynamic(root, options);
  24966. }
  24967. return this._reader.static(task.patterns, options);
  24968. }
  24969. }
  24970. async$7.default = ProviderAsync;
  24971. var stream = {};
  24972. Object.defineProperty(stream, "__esModule", { value: true });
  24973. const stream_1$1 = require$$0$7;
  24974. const stream_2 = stream$1;
  24975. const provider_1$1 = provider;
  24976. class ProviderStream extends provider_1$1.default {
  24977. constructor() {
  24978. super(...arguments);
  24979. this._reader = new stream_2.default(this._settings);
  24980. }
  24981. read(task) {
  24982. const root = this._getRootDirectory(task);
  24983. const options = this._getReaderOptions(task);
  24984. const source = this.api(root, task, options);
  24985. const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } });
  24986. source
  24987. .once('error', (error) => destination.emit('error', error))
  24988. .on('data', (entry) => destination.emit('data', options.transform(entry)))
  24989. .once('end', () => destination.emit('end'));
  24990. destination
  24991. .once('close', () => source.destroy());
  24992. return destination;
  24993. }
  24994. api(root, task, options) {
  24995. if (task.dynamic) {
  24996. return this._reader.dynamic(root, options);
  24997. }
  24998. return this._reader.static(task.patterns, options);
  24999. }
  25000. }
  25001. stream.default = ProviderStream;
  25002. var sync$2 = {};
  25003. var sync$1 = {};
  25004. Object.defineProperty(sync$1, "__esModule", { value: true });
  25005. const fsStat = out$1;
  25006. const fsWalk = out$3;
  25007. const reader_1 = reader;
  25008. class ReaderSync extends reader_1.default {
  25009. constructor() {
  25010. super(...arguments);
  25011. this._walkSync = fsWalk.walkSync;
  25012. this._statSync = fsStat.statSync;
  25013. }
  25014. dynamic(root, options) {
  25015. return this._walkSync(root, options);
  25016. }
  25017. static(patterns, options) {
  25018. const entries = [];
  25019. for (const pattern of patterns) {
  25020. const filepath = this._getFullEntryPath(pattern);
  25021. const entry = this._getEntry(filepath, pattern, options);
  25022. if (entry === null || !options.entryFilter(entry)) {
  25023. continue;
  25024. }
  25025. entries.push(entry);
  25026. }
  25027. return entries;
  25028. }
  25029. _getEntry(filepath, pattern, options) {
  25030. try {
  25031. const stats = this._getStat(filepath);
  25032. return this._makeEntry(stats, pattern);
  25033. }
  25034. catch (error) {
  25035. if (options.errorFilter(error)) {
  25036. return null;
  25037. }
  25038. throw error;
  25039. }
  25040. }
  25041. _getStat(filepath) {
  25042. return this._statSync(filepath, this._fsStatSettings);
  25043. }
  25044. }
  25045. sync$1.default = ReaderSync;
  25046. Object.defineProperty(sync$2, "__esModule", { value: true });
  25047. const sync_1$1 = sync$1;
  25048. const provider_1 = provider;
  25049. class ProviderSync extends provider_1.default {
  25050. constructor() {
  25051. super(...arguments);
  25052. this._reader = new sync_1$1.default(this._settings);
  25053. }
  25054. read(task) {
  25055. const root = this._getRootDirectory(task);
  25056. const options = this._getReaderOptions(task);
  25057. const entries = this.api(root, task, options);
  25058. return entries.map(options.transform);
  25059. }
  25060. api(root, task, options) {
  25061. if (task.dynamic) {
  25062. return this._reader.dynamic(root, options);
  25063. }
  25064. return this._reader.static(task.patterns, options);
  25065. }
  25066. }
  25067. sync$2.default = ProviderSync;
  25068. var settings = {};
  25069. (function (exports) {
  25070. Object.defineProperty(exports, "__esModule", { value: true });
  25071. exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
  25072. const fs = require$$0__default;
  25073. const os = require$$2;
  25074. /**
  25075. * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
  25076. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
  25077. */
  25078. const CPU_COUNT = Math.max(os.cpus().length, 1);
  25079. exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
  25080. lstat: fs.lstat,
  25081. lstatSync: fs.lstatSync,
  25082. stat: fs.stat,
  25083. statSync: fs.statSync,
  25084. readdir: fs.readdir,
  25085. readdirSync: fs.readdirSync
  25086. };
  25087. class Settings {
  25088. constructor(_options = {}) {
  25089. this._options = _options;
  25090. this.absolute = this._getValue(this._options.absolute, false);
  25091. this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
  25092. this.braceExpansion = this._getValue(this._options.braceExpansion, true);
  25093. this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
  25094. this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
  25095. this.cwd = this._getValue(this._options.cwd, process.cwd());
  25096. this.deep = this._getValue(this._options.deep, Infinity);
  25097. this.dot = this._getValue(this._options.dot, false);
  25098. this.extglob = this._getValue(this._options.extglob, true);
  25099. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
  25100. this.fs = this._getFileSystemMethods(this._options.fs);
  25101. this.globstar = this._getValue(this._options.globstar, true);
  25102. this.ignore = this._getValue(this._options.ignore, []);
  25103. this.markDirectories = this._getValue(this._options.markDirectories, false);
  25104. this.objectMode = this._getValue(this._options.objectMode, false);
  25105. this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
  25106. this.onlyFiles = this._getValue(this._options.onlyFiles, true);
  25107. this.stats = this._getValue(this._options.stats, false);
  25108. this.suppressErrors = this._getValue(this._options.suppressErrors, false);
  25109. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
  25110. this.unique = this._getValue(this._options.unique, true);
  25111. if (this.onlyDirectories) {
  25112. this.onlyFiles = false;
  25113. }
  25114. if (this.stats) {
  25115. this.objectMode = true;
  25116. }
  25117. }
  25118. _getValue(option, value) {
  25119. return option === undefined ? value : option;
  25120. }
  25121. _getFileSystemMethods(methods = {}) {
  25122. return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
  25123. }
  25124. }
  25125. exports.default = Settings;
  25126. } (settings));
  25127. const taskManager = tasks;
  25128. const patternManager = patterns;
  25129. const async_1 = async$7;
  25130. const stream_1 = stream;
  25131. const sync_1 = sync$2;
  25132. const settings_1 = settings;
  25133. const utils = utils$g;
  25134. async function FastGlob(source, options) {
  25135. assertPatternsInput(source);
  25136. const works = getWorks(source, async_1.default, options);
  25137. const result = await Promise.all(works);
  25138. return utils.array.flatten(result);
  25139. }
  25140. // https://github.com/typescript-eslint/typescript-eslint/issues/60
  25141. // eslint-disable-next-line no-redeclare
  25142. (function (FastGlob) {
  25143. function sync(source, options) {
  25144. assertPatternsInput(source);
  25145. const works = getWorks(source, sync_1.default, options);
  25146. return utils.array.flatten(works);
  25147. }
  25148. FastGlob.sync = sync;
  25149. function stream(source, options) {
  25150. assertPatternsInput(source);
  25151. const works = getWorks(source, stream_1.default, options);
  25152. /**
  25153. * The stream returned by the provider cannot work with an asynchronous iterator.
  25154. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
  25155. * This affects performance (+25%). I don't see best solution right now.
  25156. */
  25157. return utils.stream.merge(works);
  25158. }
  25159. FastGlob.stream = stream;
  25160. function generateTasks(source, options) {
  25161. assertPatternsInput(source);
  25162. const patterns = patternManager.transform([].concat(source));
  25163. const settings = new settings_1.default(options);
  25164. return taskManager.generate(patterns, settings);
  25165. }
  25166. FastGlob.generateTasks = generateTasks;
  25167. function isDynamicPattern(source, options) {
  25168. assertPatternsInput(source);
  25169. const settings = new settings_1.default(options);
  25170. return utils.pattern.isDynamicPattern(source, settings);
  25171. }
  25172. FastGlob.isDynamicPattern = isDynamicPattern;
  25173. function escapePath(source) {
  25174. assertPatternsInput(source);
  25175. return utils.path.escape(source);
  25176. }
  25177. FastGlob.escapePath = escapePath;
  25178. })(FastGlob || (FastGlob = {}));
  25179. function getWorks(source, _Provider, options) {
  25180. const patterns = patternManager.transform([].concat(source));
  25181. const settings = new settings_1.default(options);
  25182. const tasks = taskManager.generate(patterns, settings);
  25183. const provider = new _Provider(settings);
  25184. return tasks.map(provider.read, provider);
  25185. }
  25186. function assertPatternsInput(input) {
  25187. const source = [].concat(input);
  25188. const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
  25189. if (!isValidSource) {
  25190. throw new TypeError('Patterns must be a string (non empty) or an array of strings');
  25191. }
  25192. }
  25193. var out = FastGlob;
  25194. var glob = /*@__PURE__*/getDefaultExportFromCjs(out);
  25195. const debug$c = createDebugger('vite:ssr-external');
  25196. /**
  25197. * Converts "parent > child" syntax to just "child"
  25198. */
  25199. function stripNesting(packages) {
  25200. return packages.map((s) => {
  25201. const arr = s.split('>');
  25202. return arr[arr.length - 1].trim();
  25203. });
  25204. }
  25205. /**
  25206. * Heuristics for determining whether a dependency should be externalized for
  25207. * server-side rendering.
  25208. */
  25209. function cjsSsrResolveExternals(config, knownImports) {
  25210. // strip nesting since knownImports may be passed in from optimizeDeps which
  25211. // supports a "parent > child" syntax
  25212. knownImports = stripNesting(knownImports);
  25213. const ssrConfig = config.ssr;
  25214. if (ssrConfig?.noExternal === true) {
  25215. return [];
  25216. }
  25217. const ssrExternals = new Set();
  25218. const seen = new Set();
  25219. ssrConfig?.external?.forEach((id) => {
  25220. ssrExternals.add(id);
  25221. seen.add(id);
  25222. });
  25223. cjsSsrCollectExternals(config.root, config.resolve, ssrExternals, seen, config.logger);
  25224. const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined);
  25225. for (const dep of importedDeps) {
  25226. // Assume external if not yet seen
  25227. // At this point, the project root and any linked packages have had their dependencies checked,
  25228. // so we can safely mark any knownImports not yet seen as external. They are guaranteed to be
  25229. // dependencies of packages in node_modules.
  25230. if (!seen.has(dep)) {
  25231. ssrExternals.add(dep);
  25232. }
  25233. }
  25234. // ensure `vite/dynamic-import-polyfill` is bundled (issue #1865)
  25235. ssrExternals.delete('vite');
  25236. let externals = [...ssrExternals];
  25237. if (ssrConfig?.noExternal) {
  25238. externals = externals.filter(createFilter(undefined, ssrConfig.noExternal, { resolve: false }));
  25239. }
  25240. return externals;
  25241. }
  25242. const CJS_CONTENT_RE = /\bmodule\.exports\b|\bexports[.[]|\brequire\s*\(|\bObject\.(?:defineProperty|defineProperties|assign)\s*\(\s*exports\b/;
  25243. // TODO: use import()
  25244. const _require$2 = createRequire$1(import.meta.url);
  25245. const isSsrExternalCache = new WeakMap();
  25246. function shouldExternalizeForSSR(id, config) {
  25247. let isSsrExternal = isSsrExternalCache.get(config);
  25248. if (!isSsrExternal) {
  25249. isSsrExternal = createIsSsrExternal(config);
  25250. isSsrExternalCache.set(config, isSsrExternal);
  25251. }
  25252. return isSsrExternal(id);
  25253. }
  25254. function createIsConfiguredAsSsrExternal(config) {
  25255. const { ssr, root } = config;
  25256. const noExternal = ssr?.noExternal;
  25257. const noExternalFilter = noExternal !== 'undefined' &&
  25258. typeof noExternal !== 'boolean' &&
  25259. createFilter(undefined, noExternal, { resolve: false });
  25260. const resolveOptions = {
  25261. ...config.resolve,
  25262. root,
  25263. isProduction: false,
  25264. isBuild: true,
  25265. };
  25266. const isExternalizable = (id, configuredAsExternal) => {
  25267. if (!bareImportRE.test(id) || id.includes('\0')) {
  25268. return false;
  25269. }
  25270. try {
  25271. return !!tryNodeResolve(id, undefined, resolveOptions, ssr?.target === 'webworker', undefined, true,
  25272. // try to externalize, will return undefined or an object without
  25273. // a external flag if it isn't externalizable
  25274. true,
  25275. // Allow linked packages to be externalized if they are explicitly
  25276. // configured as external
  25277. !!configuredAsExternal)?.external;
  25278. }
  25279. catch (e) {
  25280. debug$c?.(`Failed to node resolve "${id}". Skipping externalizing it by default.`);
  25281. // may be an invalid import that's resolved by a plugin
  25282. return false;
  25283. }
  25284. };
  25285. // Returns true if it is configured as external, false if it is filtered
  25286. // by noExternal and undefined if it isn't affected by the explicit config
  25287. return (id) => {
  25288. const { ssr } = config;
  25289. if (ssr) {
  25290. if (
  25291. // If this id is defined as external, force it as external
  25292. // Note that individual package entries are allowed in ssr.external
  25293. ssr.external?.includes(id)) {
  25294. return true;
  25295. }
  25296. const pkgName = getNpmPackageName(id);
  25297. if (!pkgName) {
  25298. return isExternalizable(id);
  25299. }
  25300. if (
  25301. // A package name in ssr.external externalizes every
  25302. // externalizable package entry
  25303. ssr.external?.includes(pkgName)) {
  25304. return isExternalizable(id, true);
  25305. }
  25306. if (typeof noExternal === 'boolean') {
  25307. return !noExternal;
  25308. }
  25309. if (noExternalFilter && !noExternalFilter(pkgName)) {
  25310. return false;
  25311. }
  25312. }
  25313. return isExternalizable(id);
  25314. };
  25315. }
  25316. function createIsSsrExternal(config) {
  25317. const processedIds = new Map();
  25318. const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config);
  25319. return (id) => {
  25320. if (processedIds.has(id)) {
  25321. return processedIds.get(id);
  25322. }
  25323. let external = false;
  25324. if (id[0] !== '.' && !path$o.isAbsolute(id)) {
  25325. external = isBuiltin(id) || isConfiguredAsExternal(id);
  25326. }
  25327. processedIds.set(id, external);
  25328. return external;
  25329. };
  25330. }
  25331. // When config.experimental.buildSsrCjsExternalHeuristics is enabled, this function
  25332. // is used reverting to the Vite 2.9 SSR externalization heuristics
  25333. function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger) {
  25334. const rootPkgPath = lookupFile(root, ['package.json']);
  25335. if (!rootPkgPath) {
  25336. return;
  25337. }
  25338. const rootPkgContent = fs$l.readFileSync(rootPkgPath, 'utf-8');
  25339. if (!rootPkgContent) {
  25340. return;
  25341. }
  25342. const rootPkg = JSON.parse(rootPkgContent);
  25343. const deps = {
  25344. ...rootPkg.devDependencies,
  25345. ...rootPkg.dependencies,
  25346. };
  25347. const internalResolveOptions = {
  25348. ...resolveOptions,
  25349. root,
  25350. isProduction: false,
  25351. isBuild: true,
  25352. };
  25353. const depsToTrace = new Set();
  25354. for (const id in deps) {
  25355. if (seen.has(id))
  25356. continue;
  25357. seen.add(id);
  25358. let esmEntry;
  25359. let requireEntry;
  25360. try {
  25361. esmEntry = tryNodeResolve(id, undefined, internalResolveOptions, true, // we set `targetWeb` to `true` to get the ESM entry
  25362. undefined, true)?.id;
  25363. // normalizePath required for windows. tryNodeResolve uses normalizePath
  25364. // which returns with '/', require.resolve returns with '\\'
  25365. requireEntry = normalizePath$3(_require$2.resolve(id, { paths: [root] }));
  25366. }
  25367. catch (e) {
  25368. // no main entry, but deep imports may be allowed
  25369. const pkgDir = resolvePackageData(id, root)?.dir;
  25370. if (pkgDir) {
  25371. if (isInNodeModules(pkgDir)) {
  25372. ssrExternals.add(id);
  25373. }
  25374. else {
  25375. depsToTrace.add(path$o.dirname(pkgDir));
  25376. }
  25377. continue;
  25378. }
  25379. // resolve failed, assume include
  25380. debug$c?.(`Failed to resolve entries for package "${id}"\n`, e);
  25381. continue;
  25382. }
  25383. // no esm entry but has require entry
  25384. if (!esmEntry) {
  25385. ssrExternals.add(id);
  25386. }
  25387. // trace the dependencies of linked packages
  25388. else if (!isInNodeModules(esmEntry)) {
  25389. const pkgDir = resolvePackageData(id, root)?.dir;
  25390. if (pkgDir) {
  25391. depsToTrace.add(pkgDir);
  25392. }
  25393. }
  25394. // has separate esm/require entry, assume require entry is cjs
  25395. else if (esmEntry !== requireEntry) {
  25396. ssrExternals.add(id);
  25397. }
  25398. // if we're externalizing ESM and CJS should basically just always do it?
  25399. // or are there others like SystemJS / AMD that we'd need to handle?
  25400. // for now, we'll just leave this as is
  25401. else if (/\.m?js$/.test(esmEntry)) {
  25402. const pkg = resolvePackageData(id, root)?.data;
  25403. if (!pkg) {
  25404. continue;
  25405. }
  25406. if (pkg.type === 'module' || esmEntry.endsWith('.mjs')) {
  25407. ssrExternals.add(id);
  25408. continue;
  25409. }
  25410. // check if the entry is cjs
  25411. const content = fs$l.readFileSync(esmEntry, 'utf-8');
  25412. if (CJS_CONTENT_RE.test(content)) {
  25413. ssrExternals.add(id);
  25414. continue;
  25415. }
  25416. logger.warn(`${id} doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.`);
  25417. }
  25418. }
  25419. for (const depRoot of depsToTrace) {
  25420. cjsSsrCollectExternals(depRoot, resolveOptions, ssrExternals, seen, logger);
  25421. }
  25422. }
  25423. function cjsShouldExternalizeForSSR(id, externals) {
  25424. if (!externals) {
  25425. return false;
  25426. }
  25427. const should = externals.some((e) => {
  25428. if (id === e) {
  25429. return true;
  25430. }
  25431. // deep imports, check ext before externalizing - only externalize
  25432. // extension-less imports and explicit .js imports
  25433. if (id.startsWith(e + '/') && (!path$o.extname(id) || id.endsWith('.js'))) {
  25434. return true;
  25435. }
  25436. });
  25437. return should;
  25438. }
  25439. function getNpmPackageName(importPath) {
  25440. const parts = importPath.split('/');
  25441. if (parts[0][0] === '@') {
  25442. if (!parts[1])
  25443. return null;
  25444. return `${parts[0]}/${parts[1]}`;
  25445. }
  25446. else {
  25447. return parts[0];
  25448. }
  25449. }
  25450. /**
  25451. * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js
  25452. *
  25453. * This source code is licensed under the MIT license found in the
  25454. * LICENSE file at
  25455. * https://github.com/rollup/plugins/blob/master/LICENSE
  25456. */
  25457. // Custom json filter for vite
  25458. const jsonExtRE = /\.json(?:$|\?)(?!commonjs-(?:proxy|external))/;
  25459. const jsonLangs = `\\.(?:json|json5)(?:$|\\?)`;
  25460. const jsonLangRE = new RegExp(jsonLangs);
  25461. const isJSONRequest = (request) => jsonLangRE.test(request);
  25462. function jsonPlugin(options = {}, isBuild) {
  25463. return {
  25464. name: 'vite:json',
  25465. transform(json, id) {
  25466. if (!jsonExtRE.test(id))
  25467. return null;
  25468. if (SPECIAL_QUERY_RE.test(id))
  25469. return null;
  25470. json = stripBomTag(json);
  25471. try {
  25472. if (options.stringify) {
  25473. if (isBuild) {
  25474. return {
  25475. // during build, parse then double-stringify to remove all
  25476. // unnecessary whitespaces to reduce bundle size.
  25477. code: `export default JSON.parse(${JSON.stringify(JSON.stringify(JSON.parse(json)))})`,
  25478. map: { mappings: '' },
  25479. };
  25480. }
  25481. else {
  25482. return `export default JSON.parse(${JSON.stringify(json)})`;
  25483. }
  25484. }
  25485. const parsed = JSON.parse(json);
  25486. return {
  25487. code: dataToEsm(parsed, {
  25488. preferConst: true,
  25489. namedExports: options.namedExports,
  25490. }),
  25491. map: { mappings: '' },
  25492. };
  25493. }
  25494. catch (e) {
  25495. const errorMessageList = /\d+/.exec(e.message);
  25496. const position = errorMessageList && parseInt(errorMessageList[0], 10);
  25497. const msg = position
  25498. ? `, invalid JSON syntax found at line ${position}`
  25499. : `.`;
  25500. this.error(`Failed to parse JSON file` + msg, e.idx);
  25501. }
  25502. },
  25503. };
  25504. }
  25505. const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = 'ERR_OPTIMIZE_DEPS_PROCESSING_ERROR';
  25506. const ERR_OUTDATED_OPTIMIZED_DEP = 'ERR_OUTDATED_OPTIMIZED_DEP';
  25507. const debug$b = createDebugger('vite:optimize-deps');
  25508. function optimizedDepsPlugin(config) {
  25509. return {
  25510. name: 'vite:optimized-deps',
  25511. resolveId(id, source, { ssr }) {
  25512. if (getDepsOptimizer(config, ssr)?.isOptimizedDepFile(id)) {
  25513. return id;
  25514. }
  25515. },
  25516. // this.load({ id }) isn't implemented in PluginContainer
  25517. // The logic to register an id to wait until it is processed
  25518. // is in importAnalysis, see call to delayDepsOptimizerUntil
  25519. async load(id, options) {
  25520. const ssr = options?.ssr === true;
  25521. const depsOptimizer = getDepsOptimizer(config, ssr);
  25522. if (depsOptimizer?.isOptimizedDepFile(id)) {
  25523. const metadata = depsOptimizer.metadata;
  25524. const file = cleanUrl(id);
  25525. const versionMatch = id.match(DEP_VERSION_RE);
  25526. const browserHash = versionMatch
  25527. ? versionMatch[1].split('=')[1]
  25528. : undefined;
  25529. // Search in both the currently optimized and newly discovered deps
  25530. const info = optimizedDepInfoFromFile(metadata, file);
  25531. if (info) {
  25532. if (browserHash && info.browserHash !== browserHash) {
  25533. throwOutdatedRequest(id);
  25534. }
  25535. try {
  25536. // This is an entry point, it may still not be bundled
  25537. await info.processing;
  25538. }
  25539. catch {
  25540. // If the refresh has not happened after timeout, Vite considers
  25541. // something unexpected has happened. In this case, Vite
  25542. // returns an empty response that will error.
  25543. throwProcessingError(id);
  25544. return;
  25545. }
  25546. const newMetadata = depsOptimizer.metadata;
  25547. if (metadata !== newMetadata) {
  25548. const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
  25549. if (info.browserHash !== currentInfo?.browserHash) {
  25550. throwOutdatedRequest(id);
  25551. }
  25552. }
  25553. }
  25554. debug$b?.(`load ${colors$1.cyan(file)}`);
  25555. // Load the file from the cache instead of waiting for other plugin
  25556. // load hooks to avoid race conditions, once processing is resolved,
  25557. // we are sure that the file has been properly save to disk
  25558. try {
  25559. return await fsp.readFile(file, 'utf-8');
  25560. }
  25561. catch (e) {
  25562. // Outdated non-entry points (CHUNK), loaded after a rerun
  25563. throwOutdatedRequest(id);
  25564. }
  25565. }
  25566. },
  25567. };
  25568. }
  25569. function optimizedDepsBuildPlugin(config) {
  25570. let buildStartCalled = false;
  25571. return {
  25572. name: 'vite:optimized-deps-build',
  25573. buildStart() {
  25574. // Only reset the registered ids after a rebuild during build --watch
  25575. if (!config.isWorker && buildStartCalled) {
  25576. getDepsOptimizer(config)?.resetRegisteredIds();
  25577. }
  25578. buildStartCalled = true;
  25579. },
  25580. async resolveId(id, importer, options) {
  25581. const depsOptimizer = getDepsOptimizer(config);
  25582. if (!depsOptimizer)
  25583. return;
  25584. if (depsOptimizer.isOptimizedDepFile(id)) {
  25585. return id;
  25586. }
  25587. else {
  25588. if (options?.custom?.['vite:pre-alias']) {
  25589. // Skip registering the id if it is being resolved from the pre-alias plugin
  25590. // When a optimized dep is aliased, we need to avoid waiting for it before optimizing
  25591. return;
  25592. }
  25593. const resolved = await this.resolve(id, importer, {
  25594. ...options,
  25595. skipSelf: true,
  25596. });
  25597. if (resolved) {
  25598. depsOptimizer.delayDepsOptimizerUntil(resolved.id, async () => {
  25599. await this.load(resolved);
  25600. });
  25601. return resolved;
  25602. }
  25603. }
  25604. },
  25605. async load(id) {
  25606. const depsOptimizer = getDepsOptimizer(config);
  25607. if (!depsOptimizer?.isOptimizedDepFile(id)) {
  25608. return;
  25609. }
  25610. depsOptimizer?.ensureFirstRun();
  25611. const file = cleanUrl(id);
  25612. // Search in both the currently optimized and newly discovered deps
  25613. // If all the inputs are dependencies, we aren't going to get any
  25614. const info = optimizedDepInfoFromFile(depsOptimizer.metadata, file);
  25615. if (info) {
  25616. await info.processing;
  25617. debug$b?.(`load ${colors$1.cyan(file)}`);
  25618. }
  25619. else {
  25620. throw new Error(`Something unexpected happened while optimizing "${id}".`);
  25621. }
  25622. // Load the file from the cache instead of waiting for other plugin
  25623. // load hooks to avoid race conditions, once processing is resolved,
  25624. // we are sure that the file has been properly save to disk
  25625. return fsp.readFile(file, 'utf-8');
  25626. },
  25627. };
  25628. }
  25629. function throwProcessingError(id) {
  25630. const err = new Error(`Something unexpected happened while optimizing "${id}". ` +
  25631. `The current page should have reloaded by now`);
  25632. err.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
  25633. // This error will be caught by the transform middleware that will
  25634. // send a 504 status code request timeout
  25635. throw err;
  25636. }
  25637. function throwOutdatedRequest(id) {
  25638. const err = new Error(`There is a new version of the pre-bundle for "${id}", ` +
  25639. `a page reload is going to ask for it.`);
  25640. err.code = ERR_OUTDATED_OPTIMIZED_DEP;
  25641. // This error will be caught by the transform middleware that will
  25642. // send a 504 status code request timeout
  25643. throw err;
  25644. }
  25645. var dist = {};
  25646. (function (exports) {
  25647. Object.defineProperty(exports, "__esModule", { value: true });
  25648. exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0;
  25649. const path = require$$0$4;
  25650. const fs = require$$0__default;
  25651. const os = require$$2;
  25652. const fsReadFileAsync = fs.promises.readFile;
  25653. function getDefaultSearchPlaces(name) {
  25654. return [
  25655. 'package.json',
  25656. `.${name}rc.json`,
  25657. `.${name}rc.js`,
  25658. `${name}.config.js`,
  25659. `.${name}rc.cjs`,
  25660. `${name}.config.cjs`,
  25661. ];
  25662. }
  25663. function getSearchPaths(startDir, stopDir) {
  25664. return startDir
  25665. .split(path.sep)
  25666. .reduceRight((acc, _, ind, arr) => {
  25667. const currentPath = arr.slice(0, ind + 1).join(path.sep);
  25668. if (!acc.passedStopDir)
  25669. acc.searchPlaces.push(currentPath || path.sep);
  25670. if (currentPath === stopDir)
  25671. acc.passedStopDir = true;
  25672. return acc;
  25673. }, { searchPlaces: [], passedStopDir: false }).searchPlaces;
  25674. }
  25675. exports.defaultLoaders = Object.freeze({
  25676. '.js': __require,
  25677. '.json': __require,
  25678. '.cjs': __require,
  25679. noExt(_, content) {
  25680. return JSON.parse(content);
  25681. },
  25682. });
  25683. function getExtDesc(ext) {
  25684. return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`;
  25685. }
  25686. function getOptions(name, options = {}) {
  25687. const conf = {
  25688. stopDir: os.homedir(),
  25689. searchPlaces: getDefaultSearchPlaces(name),
  25690. ignoreEmptySearchPlaces: true,
  25691. transform: (x) => x,
  25692. packageProp: [name],
  25693. ...options,
  25694. loaders: { ...exports.defaultLoaders, ...options.loaders },
  25695. };
  25696. conf.searchPlaces.forEach(place => {
  25697. const key = path.extname(place) || 'noExt';
  25698. const loader = conf.loaders[key];
  25699. if (!loader) {
  25700. throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`);
  25701. }
  25702. if (typeof loader !== 'function') {
  25703. throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
  25704. }
  25705. });
  25706. return conf;
  25707. }
  25708. function getPackageProp(props, obj) {
  25709. if (typeof props === 'string' && props in obj)
  25710. return obj[props];
  25711. return ((Array.isArray(props) ? props : props.split('.')).reduce((acc, prop) => (acc === undefined ? acc : acc[prop]), obj) || null);
  25712. }
  25713. function getSearchItems(searchPlaces, searchPaths) {
  25714. return searchPaths.reduce((acc, searchPath) => {
  25715. searchPlaces.forEach(fileName => acc.push({
  25716. fileName,
  25717. filepath: path.join(searchPath, fileName),
  25718. loaderKey: path.extname(fileName) || 'noExt',
  25719. }));
  25720. return acc;
  25721. }, []);
  25722. }
  25723. function validateFilePath(filepath) {
  25724. if (!filepath)
  25725. throw new Error('load must pass a non-empty string');
  25726. }
  25727. function validateLoader(loader, ext) {
  25728. if (!loader)
  25729. throw new Error(`No loader specified for extension "${ext}"`);
  25730. if (typeof loader !== 'function')
  25731. throw new Error('loader is not a function');
  25732. }
  25733. function lilconfig(name, options) {
  25734. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
  25735. return {
  25736. async search(searchFrom = process.cwd()) {
  25737. const searchPaths = getSearchPaths(searchFrom, stopDir);
  25738. const result = {
  25739. config: null,
  25740. filepath: '',
  25741. };
  25742. const searchItems = getSearchItems(searchPlaces, searchPaths);
  25743. for (const { fileName, filepath, loaderKey } of searchItems) {
  25744. try {
  25745. await fs.promises.access(filepath);
  25746. }
  25747. catch (_a) {
  25748. continue;
  25749. }
  25750. const content = String(await fsReadFileAsync(filepath));
  25751. const loader = loaders[loaderKey];
  25752. if (fileName === 'package.json') {
  25753. const pkg = await loader(filepath, content);
  25754. const maybeConfig = getPackageProp(packageProp, pkg);
  25755. if (maybeConfig != null) {
  25756. result.config = maybeConfig;
  25757. result.filepath = filepath;
  25758. break;
  25759. }
  25760. continue;
  25761. }
  25762. const isEmpty = content.trim() === '';
  25763. if (isEmpty && ignoreEmptySearchPlaces)
  25764. continue;
  25765. if (isEmpty) {
  25766. result.isEmpty = true;
  25767. result.config = undefined;
  25768. }
  25769. else {
  25770. validateLoader(loader, loaderKey);
  25771. result.config = await loader(filepath, content);
  25772. }
  25773. result.filepath = filepath;
  25774. break;
  25775. }
  25776. if (result.filepath === '' && result.config === null)
  25777. return transform(null);
  25778. return transform(result);
  25779. },
  25780. async load(filepath) {
  25781. validateFilePath(filepath);
  25782. const absPath = path.resolve(process.cwd(), filepath);
  25783. const { base, ext } = path.parse(absPath);
  25784. const loaderKey = ext || 'noExt';
  25785. const loader = loaders[loaderKey];
  25786. validateLoader(loader, loaderKey);
  25787. const content = String(await fsReadFileAsync(absPath));
  25788. if (base === 'package.json') {
  25789. const pkg = await loader(absPath, content);
  25790. return transform({
  25791. config: getPackageProp(packageProp, pkg),
  25792. filepath: absPath,
  25793. });
  25794. }
  25795. const result = {
  25796. config: null,
  25797. filepath: absPath,
  25798. };
  25799. const isEmpty = content.trim() === '';
  25800. if (isEmpty && ignoreEmptySearchPlaces)
  25801. return transform({
  25802. config: undefined,
  25803. filepath: absPath,
  25804. isEmpty: true,
  25805. });
  25806. result.config = isEmpty
  25807. ? undefined
  25808. : await loader(absPath, content);
  25809. return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
  25810. },
  25811. };
  25812. }
  25813. exports.lilconfig = lilconfig;
  25814. function lilconfigSync(name, options) {
  25815. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
  25816. return {
  25817. search(searchFrom = process.cwd()) {
  25818. const searchPaths = getSearchPaths(searchFrom, stopDir);
  25819. const result = {
  25820. config: null,
  25821. filepath: '',
  25822. };
  25823. const searchItems = getSearchItems(searchPlaces, searchPaths);
  25824. for (const { fileName, filepath, loaderKey } of searchItems) {
  25825. try {
  25826. fs.accessSync(filepath);
  25827. }
  25828. catch (_a) {
  25829. continue;
  25830. }
  25831. const loader = loaders[loaderKey];
  25832. const content = String(fs.readFileSync(filepath));
  25833. if (fileName === 'package.json') {
  25834. const pkg = loader(filepath, content);
  25835. const maybeConfig = getPackageProp(packageProp, pkg);
  25836. if (maybeConfig != null) {
  25837. result.config = maybeConfig;
  25838. result.filepath = filepath;
  25839. break;
  25840. }
  25841. continue;
  25842. }
  25843. const isEmpty = content.trim() === '';
  25844. if (isEmpty && ignoreEmptySearchPlaces)
  25845. continue;
  25846. if (isEmpty) {
  25847. result.isEmpty = true;
  25848. result.config = undefined;
  25849. }
  25850. else {
  25851. validateLoader(loader, loaderKey);
  25852. result.config = loader(filepath, content);
  25853. }
  25854. result.filepath = filepath;
  25855. break;
  25856. }
  25857. if (result.filepath === '' && result.config === null)
  25858. return transform(null);
  25859. return transform(result);
  25860. },
  25861. load(filepath) {
  25862. validateFilePath(filepath);
  25863. const absPath = path.resolve(process.cwd(), filepath);
  25864. const { base, ext } = path.parse(absPath);
  25865. const loaderKey = ext || 'noExt';
  25866. const loader = loaders[loaderKey];
  25867. validateLoader(loader, loaderKey);
  25868. const content = String(fs.readFileSync(absPath));
  25869. if (base === 'package.json') {
  25870. const pkg = loader(absPath, content);
  25871. return transform({
  25872. config: getPackageProp(packageProp, pkg),
  25873. filepath: absPath,
  25874. });
  25875. }
  25876. const result = {
  25877. config: null,
  25878. filepath: absPath,
  25879. };
  25880. const isEmpty = content.trim() === '';
  25881. if (isEmpty && ignoreEmptySearchPlaces)
  25882. return transform({
  25883. filepath: absPath,
  25884. config: undefined,
  25885. isEmpty: true,
  25886. });
  25887. result.config = isEmpty ? undefined : loader(absPath, content);
  25888. return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
  25889. },
  25890. };
  25891. }
  25892. exports.lilconfigSync = lilconfigSync;
  25893. } (dist));
  25894. const ALIAS = Symbol.for('yaml.alias');
  25895. const DOC = Symbol.for('yaml.document');
  25896. const MAP = Symbol.for('yaml.map');
  25897. const PAIR = Symbol.for('yaml.pair');
  25898. const SCALAR$1 = Symbol.for('yaml.scalar');
  25899. const SEQ = Symbol.for('yaml.seq');
  25900. const NODE_TYPE = Symbol.for('yaml.node.type');
  25901. const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
  25902. const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
  25903. const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
  25904. const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
  25905. const isScalar$1 = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR$1;
  25906. const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
  25907. function isCollection$1(node) {
  25908. if (node && typeof node === 'object')
  25909. switch (node[NODE_TYPE]) {
  25910. case MAP:
  25911. case SEQ:
  25912. return true;
  25913. }
  25914. return false;
  25915. }
  25916. function isNode$1(node) {
  25917. if (node && typeof node === 'object')
  25918. switch (node[NODE_TYPE]) {
  25919. case ALIAS:
  25920. case MAP:
  25921. case SCALAR$1:
  25922. case SEQ:
  25923. return true;
  25924. }
  25925. return false;
  25926. }
  25927. const hasAnchor = (node) => (isScalar$1(node) || isCollection$1(node)) && !!node.anchor;
  25928. class NodeBase {
  25929. constructor(type) {
  25930. Object.defineProperty(this, NODE_TYPE, { value: type });
  25931. }
  25932. /** Create a copy of this node. */
  25933. clone() {
  25934. const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
  25935. if (this.range)
  25936. copy.range = this.range.slice();
  25937. return copy;
  25938. }
  25939. }
  25940. const BREAK$1 = Symbol('break visit');
  25941. const SKIP$1 = Symbol('skip children');
  25942. const REMOVE$1 = Symbol('remove node');
  25943. /**
  25944. * Apply a visitor to an AST node or document.
  25945. *
  25946. * Walks through the tree (depth-first) starting from `node`, calling a
  25947. * `visitor` function with three arguments:
  25948. * - `key`: For sequence values and map `Pair`, the node's index in the
  25949. * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
  25950. * `null` for the root node.
  25951. * - `node`: The current node.
  25952. * - `path`: The ancestry of the current node.
  25953. *
  25954. * The return value of the visitor may be used to control the traversal:
  25955. * - `undefined` (default): Do nothing and continue
  25956. * - `visit.SKIP`: Do not visit the children of this node, continue with next
  25957. * sibling
  25958. * - `visit.BREAK`: Terminate traversal completely
  25959. * - `visit.REMOVE`: Remove the current node, then continue with the next one
  25960. * - `Node`: Replace the current node, then continue by visiting it
  25961. * - `number`: While iterating the items of a sequence or map, set the index
  25962. * of the next step. This is useful especially if the index of the current
  25963. * node has changed.
  25964. *
  25965. * If `visitor` is a single function, it will be called with all values
  25966. * encountered in the tree, including e.g. `null` values. Alternatively,
  25967. * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
  25968. * `Alias` and `Scalar` node. To define the same visitor function for more than
  25969. * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
  25970. * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
  25971. * specific defined one will be used for each node.
  25972. */
  25973. function visit$1(node, visitor) {
  25974. const visitor_ = initVisitor(visitor);
  25975. if (isDocument(node)) {
  25976. const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
  25977. if (cd === REMOVE$1)
  25978. node.contents = null;
  25979. }
  25980. else
  25981. visit_(null, node, visitor_, Object.freeze([]));
  25982. }
  25983. // Without the `as symbol` casts, TS declares these in the `visit`
  25984. // namespace using `var`, but then complains about that because
  25985. // `unique symbol` must be `const`.
  25986. /** Terminate visit traversal completely */
  25987. visit$1.BREAK = BREAK$1;
  25988. /** Do not visit the children of the current node */
  25989. visit$1.SKIP = SKIP$1;
  25990. /** Remove the current node */
  25991. visit$1.REMOVE = REMOVE$1;
  25992. function visit_(key, node, visitor, path) {
  25993. const ctrl = callVisitor(key, node, visitor, path);
  25994. if (isNode$1(ctrl) || isPair(ctrl)) {
  25995. replaceNode(key, path, ctrl);
  25996. return visit_(key, ctrl, visitor, path);
  25997. }
  25998. if (typeof ctrl !== 'symbol') {
  25999. if (isCollection$1(node)) {
  26000. path = Object.freeze(path.concat(node));
  26001. for (let i = 0; i < node.items.length; ++i) {
  26002. const ci = visit_(i, node.items[i], visitor, path);
  26003. if (typeof ci === 'number')
  26004. i = ci - 1;
  26005. else if (ci === BREAK$1)
  26006. return BREAK$1;
  26007. else if (ci === REMOVE$1) {
  26008. node.items.splice(i, 1);
  26009. i -= 1;
  26010. }
  26011. }
  26012. }
  26013. else if (isPair(node)) {
  26014. path = Object.freeze(path.concat(node));
  26015. const ck = visit_('key', node.key, visitor, path);
  26016. if (ck === BREAK$1)
  26017. return BREAK$1;
  26018. else if (ck === REMOVE$1)
  26019. node.key = null;
  26020. const cv = visit_('value', node.value, visitor, path);
  26021. if (cv === BREAK$1)
  26022. return BREAK$1;
  26023. else if (cv === REMOVE$1)
  26024. node.value = null;
  26025. }
  26026. }
  26027. return ctrl;
  26028. }
  26029. /**
  26030. * Apply an async visitor to an AST node or document.
  26031. *
  26032. * Walks through the tree (depth-first) starting from `node`, calling a
  26033. * `visitor` function with three arguments:
  26034. * - `key`: For sequence values and map `Pair`, the node's index in the
  26035. * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
  26036. * `null` for the root node.
  26037. * - `node`: The current node.
  26038. * - `path`: The ancestry of the current node.
  26039. *
  26040. * The return value of the visitor may be used to control the traversal:
  26041. * - `Promise`: Must resolve to one of the following values
  26042. * - `undefined` (default): Do nothing and continue
  26043. * - `visit.SKIP`: Do not visit the children of this node, continue with next
  26044. * sibling
  26045. * - `visit.BREAK`: Terminate traversal completely
  26046. * - `visit.REMOVE`: Remove the current node, then continue with the next one
  26047. * - `Node`: Replace the current node, then continue by visiting it
  26048. * - `number`: While iterating the items of a sequence or map, set the index
  26049. * of the next step. This is useful especially if the index of the current
  26050. * node has changed.
  26051. *
  26052. * If `visitor` is a single function, it will be called with all values
  26053. * encountered in the tree, including e.g. `null` values. Alternatively,
  26054. * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
  26055. * `Alias` and `Scalar` node. To define the same visitor function for more than
  26056. * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
  26057. * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
  26058. * specific defined one will be used for each node.
  26059. */
  26060. async function visitAsync(node, visitor) {
  26061. const visitor_ = initVisitor(visitor);
  26062. if (isDocument(node)) {
  26063. const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
  26064. if (cd === REMOVE$1)
  26065. node.contents = null;
  26066. }
  26067. else
  26068. await visitAsync_(null, node, visitor_, Object.freeze([]));
  26069. }
  26070. // Without the `as symbol` casts, TS declares these in the `visit`
  26071. // namespace using `var`, but then complains about that because
  26072. // `unique symbol` must be `const`.
  26073. /** Terminate visit traversal completely */
  26074. visitAsync.BREAK = BREAK$1;
  26075. /** Do not visit the children of the current node */
  26076. visitAsync.SKIP = SKIP$1;
  26077. /** Remove the current node */
  26078. visitAsync.REMOVE = REMOVE$1;
  26079. async function visitAsync_(key, node, visitor, path) {
  26080. const ctrl = await callVisitor(key, node, visitor, path);
  26081. if (isNode$1(ctrl) || isPair(ctrl)) {
  26082. replaceNode(key, path, ctrl);
  26083. return visitAsync_(key, ctrl, visitor, path);
  26084. }
  26085. if (typeof ctrl !== 'symbol') {
  26086. if (isCollection$1(node)) {
  26087. path = Object.freeze(path.concat(node));
  26088. for (let i = 0; i < node.items.length; ++i) {
  26089. const ci = await visitAsync_(i, node.items[i], visitor, path);
  26090. if (typeof ci === 'number')
  26091. i = ci - 1;
  26092. else if (ci === BREAK$1)
  26093. return BREAK$1;
  26094. else if (ci === REMOVE$1) {
  26095. node.items.splice(i, 1);
  26096. i -= 1;
  26097. }
  26098. }
  26099. }
  26100. else if (isPair(node)) {
  26101. path = Object.freeze(path.concat(node));
  26102. const ck = await visitAsync_('key', node.key, visitor, path);
  26103. if (ck === BREAK$1)
  26104. return BREAK$1;
  26105. else if (ck === REMOVE$1)
  26106. node.key = null;
  26107. const cv = await visitAsync_('value', node.value, visitor, path);
  26108. if (cv === BREAK$1)
  26109. return BREAK$1;
  26110. else if (cv === REMOVE$1)
  26111. node.value = null;
  26112. }
  26113. }
  26114. return ctrl;
  26115. }
  26116. function initVisitor(visitor) {
  26117. if (typeof visitor === 'object' &&
  26118. (visitor.Collection || visitor.Node || visitor.Value)) {
  26119. return Object.assign({
  26120. Alias: visitor.Node,
  26121. Map: visitor.Node,
  26122. Scalar: visitor.Node,
  26123. Seq: visitor.Node
  26124. }, visitor.Value && {
  26125. Map: visitor.Value,
  26126. Scalar: visitor.Value,
  26127. Seq: visitor.Value
  26128. }, visitor.Collection && {
  26129. Map: visitor.Collection,
  26130. Seq: visitor.Collection
  26131. }, visitor);
  26132. }
  26133. return visitor;
  26134. }
  26135. function callVisitor(key, node, visitor, path) {
  26136. if (typeof visitor === 'function')
  26137. return visitor(key, node, path);
  26138. if (isMap(node))
  26139. return visitor.Map?.(key, node, path);
  26140. if (isSeq(node))
  26141. return visitor.Seq?.(key, node, path);
  26142. if (isPair(node))
  26143. return visitor.Pair?.(key, node, path);
  26144. if (isScalar$1(node))
  26145. return visitor.Scalar?.(key, node, path);
  26146. if (isAlias(node))
  26147. return visitor.Alias?.(key, node, path);
  26148. return undefined;
  26149. }
  26150. function replaceNode(key, path, node) {
  26151. const parent = path[path.length - 1];
  26152. if (isCollection$1(parent)) {
  26153. parent.items[key] = node;
  26154. }
  26155. else if (isPair(parent)) {
  26156. if (key === 'key')
  26157. parent.key = node;
  26158. else
  26159. parent.value = node;
  26160. }
  26161. else if (isDocument(parent)) {
  26162. parent.contents = node;
  26163. }
  26164. else {
  26165. const pt = isAlias(parent) ? 'alias' : 'scalar';
  26166. throw new Error(`Cannot replace node with ${pt} parent`);
  26167. }
  26168. }
  26169. const escapeChars = {
  26170. '!': '%21',
  26171. ',': '%2C',
  26172. '[': '%5B',
  26173. ']': '%5D',
  26174. '{': '%7B',
  26175. '}': '%7D'
  26176. };
  26177. const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]);
  26178. class Directives {
  26179. constructor(yaml, tags) {
  26180. /**
  26181. * The directives-end/doc-start marker `---`. If `null`, a marker may still be
  26182. * included in the document's stringified representation.
  26183. */
  26184. this.docStart = null;
  26185. /** The doc-end marker `...`. */
  26186. this.docEnd = false;
  26187. this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
  26188. this.tags = Object.assign({}, Directives.defaultTags, tags);
  26189. }
  26190. clone() {
  26191. const copy = new Directives(this.yaml, this.tags);
  26192. copy.docStart = this.docStart;
  26193. return copy;
  26194. }
  26195. /**
  26196. * During parsing, get a Directives instance for the current document and
  26197. * update the stream state according to the current version's spec.
  26198. */
  26199. atDocument() {
  26200. const res = new Directives(this.yaml, this.tags);
  26201. switch (this.yaml.version) {
  26202. case '1.1':
  26203. this.atNextDocument = true;
  26204. break;
  26205. case '1.2':
  26206. this.atNextDocument = false;
  26207. this.yaml = {
  26208. explicit: Directives.defaultYaml.explicit,
  26209. version: '1.2'
  26210. };
  26211. this.tags = Object.assign({}, Directives.defaultTags);
  26212. break;
  26213. }
  26214. return res;
  26215. }
  26216. /**
  26217. * @param onError - May be called even if the action was successful
  26218. * @returns `true` on success
  26219. */
  26220. add(line, onError) {
  26221. if (this.atNextDocument) {
  26222. this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };
  26223. this.tags = Object.assign({}, Directives.defaultTags);
  26224. this.atNextDocument = false;
  26225. }
  26226. const parts = line.trim().split(/[ \t]+/);
  26227. const name = parts.shift();
  26228. switch (name) {
  26229. case '%TAG': {
  26230. if (parts.length !== 2) {
  26231. onError(0, '%TAG directive should contain exactly two parts');
  26232. if (parts.length < 2)
  26233. return false;
  26234. }
  26235. const [handle, prefix] = parts;
  26236. this.tags[handle] = prefix;
  26237. return true;
  26238. }
  26239. case '%YAML': {
  26240. this.yaml.explicit = true;
  26241. if (parts.length !== 1) {
  26242. onError(0, '%YAML directive should contain exactly one part');
  26243. return false;
  26244. }
  26245. const [version] = parts;
  26246. if (version === '1.1' || version === '1.2') {
  26247. this.yaml.version = version;
  26248. return true;
  26249. }
  26250. else {
  26251. const isValid = /^\d+\.\d+$/.test(version);
  26252. onError(6, `Unsupported YAML version ${version}`, isValid);
  26253. return false;
  26254. }
  26255. }
  26256. default:
  26257. onError(0, `Unknown directive ${name}`, true);
  26258. return false;
  26259. }
  26260. }
  26261. /**
  26262. * Resolves a tag, matching handles to those defined in %TAG directives.
  26263. *
  26264. * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
  26265. * `'!local'` tag, or `null` if unresolvable.
  26266. */
  26267. tagName(source, onError) {
  26268. if (source === '!')
  26269. return '!'; // non-specific tag
  26270. if (source[0] !== '!') {
  26271. onError(`Not a valid tag: ${source}`);
  26272. return null;
  26273. }
  26274. if (source[1] === '<') {
  26275. const verbatim = source.slice(2, -1);
  26276. if (verbatim === '!' || verbatim === '!!') {
  26277. onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
  26278. return null;
  26279. }
  26280. if (source[source.length - 1] !== '>')
  26281. onError('Verbatim tags must end with a >');
  26282. return verbatim;
  26283. }
  26284. const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/);
  26285. if (!suffix)
  26286. onError(`The ${source} tag has no suffix`);
  26287. const prefix = this.tags[handle];
  26288. if (prefix)
  26289. return prefix + decodeURIComponent(suffix);
  26290. if (handle === '!')
  26291. return source; // local tag
  26292. onError(`Could not resolve tag: ${source}`);
  26293. return null;
  26294. }
  26295. /**
  26296. * Given a fully resolved tag, returns its printable string form,
  26297. * taking into account current tag prefixes and defaults.
  26298. */
  26299. tagString(tag) {
  26300. for (const [handle, prefix] of Object.entries(this.tags)) {
  26301. if (tag.startsWith(prefix))
  26302. return handle + escapeTagName(tag.substring(prefix.length));
  26303. }
  26304. return tag[0] === '!' ? tag : `!<${tag}>`;
  26305. }
  26306. toString(doc) {
  26307. const lines = this.yaml.explicit
  26308. ? [`%YAML ${this.yaml.version || '1.2'}`]
  26309. : [];
  26310. const tagEntries = Object.entries(this.tags);
  26311. let tagNames;
  26312. if (doc && tagEntries.length > 0 && isNode$1(doc.contents)) {
  26313. const tags = {};
  26314. visit$1(doc.contents, (_key, node) => {
  26315. if (isNode$1(node) && node.tag)
  26316. tags[node.tag] = true;
  26317. });
  26318. tagNames = Object.keys(tags);
  26319. }
  26320. else
  26321. tagNames = [];
  26322. for (const [handle, prefix] of tagEntries) {
  26323. if (handle === '!!' && prefix === 'tag:yaml.org,2002:')
  26324. continue;
  26325. if (!doc || tagNames.some(tn => tn.startsWith(prefix)))
  26326. lines.push(`%TAG ${handle} ${prefix}`);
  26327. }
  26328. return lines.join('\n');
  26329. }
  26330. }
  26331. Directives.defaultYaml = { explicit: false, version: '1.2' };
  26332. Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' };
  26333. /**
  26334. * Verify that the input string is a valid anchor.
  26335. *
  26336. * Will throw on errors.
  26337. */
  26338. function anchorIsValid(anchor) {
  26339. if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
  26340. const sa = JSON.stringify(anchor);
  26341. const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
  26342. throw new Error(msg);
  26343. }
  26344. return true;
  26345. }
  26346. function anchorNames(root) {
  26347. const anchors = new Set();
  26348. visit$1(root, {
  26349. Value(_key, node) {
  26350. if (node.anchor)
  26351. anchors.add(node.anchor);
  26352. }
  26353. });
  26354. return anchors;
  26355. }
  26356. /** Find a new anchor name with the given `prefix` and a one-indexed suffix. */
  26357. function findNewAnchor(prefix, exclude) {
  26358. for (let i = 1; true; ++i) {
  26359. const name = `${prefix}${i}`;
  26360. if (!exclude.has(name))
  26361. return name;
  26362. }
  26363. }
  26364. function createNodeAnchors(doc, prefix) {
  26365. const aliasObjects = [];
  26366. const sourceObjects = new Map();
  26367. let prevAnchors = null;
  26368. return {
  26369. onAnchor: (source) => {
  26370. aliasObjects.push(source);
  26371. if (!prevAnchors)
  26372. prevAnchors = anchorNames(doc);
  26373. const anchor = findNewAnchor(prefix, prevAnchors);
  26374. prevAnchors.add(anchor);
  26375. return anchor;
  26376. },
  26377. /**
  26378. * With circular references, the source node is only resolved after all
  26379. * of its child nodes are. This is why anchors are set only after all of
  26380. * the nodes have been created.
  26381. */
  26382. setAnchors: () => {
  26383. for (const source of aliasObjects) {
  26384. const ref = sourceObjects.get(source);
  26385. if (typeof ref === 'object' &&
  26386. ref.anchor &&
  26387. (isScalar$1(ref.node) || isCollection$1(ref.node))) {
  26388. ref.node.anchor = ref.anchor;
  26389. }
  26390. else {
  26391. const error = new Error('Failed to resolve repeated object (this should not happen)');
  26392. error.source = source;
  26393. throw error;
  26394. }
  26395. }
  26396. },
  26397. sourceObjects
  26398. };
  26399. }
  26400. class Alias extends NodeBase {
  26401. constructor(source) {
  26402. super(ALIAS);
  26403. this.source = source;
  26404. Object.defineProperty(this, 'tag', {
  26405. set() {
  26406. throw new Error('Alias nodes cannot have tags');
  26407. }
  26408. });
  26409. }
  26410. /**
  26411. * Resolve the value of this alias within `doc`, finding the last
  26412. * instance of the `source` anchor before this node.
  26413. */
  26414. resolve(doc) {
  26415. let found = undefined;
  26416. visit$1(doc, {
  26417. Node: (_key, node) => {
  26418. if (node === this)
  26419. return visit$1.BREAK;
  26420. if (node.anchor === this.source)
  26421. found = node;
  26422. }
  26423. });
  26424. return found;
  26425. }
  26426. toJSON(_arg, ctx) {
  26427. if (!ctx)
  26428. return { source: this.source };
  26429. const { anchors, doc, maxAliasCount } = ctx;
  26430. const source = this.resolve(doc);
  26431. if (!source) {
  26432. const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
  26433. throw new ReferenceError(msg);
  26434. }
  26435. const data = anchors.get(source);
  26436. /* istanbul ignore if */
  26437. if (!data || data.res === undefined) {
  26438. const msg = 'This should not happen: Alias anchor was not resolved?';
  26439. throw new ReferenceError(msg);
  26440. }
  26441. if (maxAliasCount >= 0) {
  26442. data.count += 1;
  26443. if (data.aliasCount === 0)
  26444. data.aliasCount = getAliasCount(doc, source, anchors);
  26445. if (data.count * data.aliasCount > maxAliasCount) {
  26446. const msg = 'Excessive alias count indicates a resource exhaustion attack';
  26447. throw new ReferenceError(msg);
  26448. }
  26449. }
  26450. return data.res;
  26451. }
  26452. toString(ctx, _onComment, _onChompKeep) {
  26453. const src = `*${this.source}`;
  26454. if (ctx) {
  26455. anchorIsValid(this.source);
  26456. if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
  26457. const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
  26458. throw new Error(msg);
  26459. }
  26460. if (ctx.implicitKey)
  26461. return `${src} `;
  26462. }
  26463. return src;
  26464. }
  26465. }
  26466. function getAliasCount(doc, node, anchors) {
  26467. if (isAlias(node)) {
  26468. const source = node.resolve(doc);
  26469. const anchor = anchors && source && anchors.get(source);
  26470. return anchor ? anchor.count * anchor.aliasCount : 0;
  26471. }
  26472. else if (isCollection$1(node)) {
  26473. let count = 0;
  26474. for (const item of node.items) {
  26475. const c = getAliasCount(doc, item, anchors);
  26476. if (c > count)
  26477. count = c;
  26478. }
  26479. return count;
  26480. }
  26481. else if (isPair(node)) {
  26482. const kc = getAliasCount(doc, node.key, anchors);
  26483. const vc = getAliasCount(doc, node.value, anchors);
  26484. return Math.max(kc, vc);
  26485. }
  26486. return 1;
  26487. }
  26488. /**
  26489. * Recursively convert any node or its contents to native JavaScript
  26490. *
  26491. * @param value - The input value
  26492. * @param arg - If `value` defines a `toJSON()` method, use this
  26493. * as its first argument
  26494. * @param ctx - Conversion context, originally set in Document#toJS(). If
  26495. * `{ keep: true }` is not set, output should be suitable for JSON
  26496. * stringification.
  26497. */
  26498. function toJS(value, arg, ctx) {
  26499. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  26500. if (Array.isArray(value))
  26501. return value.map((v, i) => toJS(v, String(i), ctx));
  26502. if (value && typeof value.toJSON === 'function') {
  26503. // eslint-disable-next-line @typescript-eslint/no-unsafe-call
  26504. if (!ctx || !hasAnchor(value))
  26505. return value.toJSON(arg, ctx);
  26506. const data = { aliasCount: 0, count: 1, res: undefined };
  26507. ctx.anchors.set(value, data);
  26508. ctx.onCreate = res => {
  26509. data.res = res;
  26510. delete ctx.onCreate;
  26511. };
  26512. const res = value.toJSON(arg, ctx);
  26513. if (ctx.onCreate)
  26514. ctx.onCreate(res);
  26515. return res;
  26516. }
  26517. if (typeof value === 'bigint' && !ctx?.keep)
  26518. return Number(value);
  26519. return value;
  26520. }
  26521. const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
  26522. class Scalar extends NodeBase {
  26523. constructor(value) {
  26524. super(SCALAR$1);
  26525. this.value = value;
  26526. }
  26527. toJSON(arg, ctx) {
  26528. return ctx?.keep ? this.value : toJS(this.value, arg, ctx);
  26529. }
  26530. toString() {
  26531. return String(this.value);
  26532. }
  26533. }
  26534. Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED';
  26535. Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL';
  26536. Scalar.PLAIN = 'PLAIN';
  26537. Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';
  26538. Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE';
  26539. const defaultTagPrefix = 'tag:yaml.org,2002:';
  26540. function findTagObject(value, tagName, tags) {
  26541. if (tagName) {
  26542. const match = tags.filter(t => t.tag === tagName);
  26543. const tagObj = match.find(t => !t.format) ?? match[0];
  26544. if (!tagObj)
  26545. throw new Error(`Tag ${tagName} not found`);
  26546. return tagObj;
  26547. }
  26548. return tags.find(t => t.identify?.(value) && !t.format);
  26549. }
  26550. function createNode(value, tagName, ctx) {
  26551. if (isDocument(value))
  26552. value = value.contents;
  26553. if (isNode$1(value))
  26554. return value;
  26555. if (isPair(value)) {
  26556. const map = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);
  26557. map.items.push(value);
  26558. return map;
  26559. }
  26560. if (value instanceof String ||
  26561. value instanceof Number ||
  26562. value instanceof Boolean ||
  26563. (typeof BigInt === 'function' && value instanceof BigInt) // not supported everywhere
  26564. ) {
  26565. // https://tc39.es/ecma262/#sec-serializejsonproperty
  26566. value = value.valueOf();
  26567. }
  26568. const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
  26569. // Detect duplicate references to the same object & use Alias nodes for all
  26570. // after first. The `ref` wrapper allows for circular references to resolve.
  26571. let ref = undefined;
  26572. if (aliasDuplicateObjects && value && typeof value === 'object') {
  26573. ref = sourceObjects.get(value);
  26574. if (ref) {
  26575. if (!ref.anchor)
  26576. ref.anchor = onAnchor(value);
  26577. return new Alias(ref.anchor);
  26578. }
  26579. else {
  26580. ref = { anchor: null, node: null };
  26581. sourceObjects.set(value, ref);
  26582. }
  26583. }
  26584. if (tagName?.startsWith('!!'))
  26585. tagName = defaultTagPrefix + tagName.slice(2);
  26586. let tagObj = findTagObject(value, tagName, schema.tags);
  26587. if (!tagObj) {
  26588. if (value && typeof value.toJSON === 'function') {
  26589. // eslint-disable-next-line @typescript-eslint/no-unsafe-call
  26590. value = value.toJSON();
  26591. }
  26592. if (!value || typeof value !== 'object') {
  26593. const node = new Scalar(value);
  26594. if (ref)
  26595. ref.node = node;
  26596. return node;
  26597. }
  26598. tagObj =
  26599. value instanceof Map
  26600. ? schema[MAP]
  26601. : Symbol.iterator in Object(value)
  26602. ? schema[SEQ]
  26603. : schema[MAP];
  26604. }
  26605. if (onTagObj) {
  26606. onTagObj(tagObj);
  26607. delete ctx.onTagObj;
  26608. }
  26609. const node = tagObj?.createNode
  26610. ? tagObj.createNode(ctx.schema, value, ctx)
  26611. : new Scalar(value);
  26612. if (tagName)
  26613. node.tag = tagName;
  26614. if (ref)
  26615. ref.node = node;
  26616. return node;
  26617. }
  26618. function collectionFromPath(schema, path, value) {
  26619. let v = value;
  26620. for (let i = path.length - 1; i >= 0; --i) {
  26621. const k = path[i];
  26622. if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {
  26623. const a = [];
  26624. a[k] = v;
  26625. v = a;
  26626. }
  26627. else {
  26628. v = new Map([[k, v]]);
  26629. }
  26630. }
  26631. return createNode(v, undefined, {
  26632. aliasDuplicateObjects: false,
  26633. keepUndefined: false,
  26634. onAnchor: () => {
  26635. throw new Error('This should not happen, please report a bug.');
  26636. },
  26637. schema,
  26638. sourceObjects: new Map()
  26639. });
  26640. }
  26641. // Type guard is intentionally a little wrong so as to be more useful,
  26642. // as it does not cover untypable empty non-string iterables (e.g. []).
  26643. const isEmptyPath = (path) => path == null ||
  26644. (typeof path === 'object' && !!path[Symbol.iterator]().next().done);
  26645. class Collection extends NodeBase {
  26646. constructor(type, schema) {
  26647. super(type);
  26648. Object.defineProperty(this, 'schema', {
  26649. value: schema,
  26650. configurable: true,
  26651. enumerable: false,
  26652. writable: true
  26653. });
  26654. }
  26655. /**
  26656. * Create a copy of this collection.
  26657. *
  26658. * @param schema - If defined, overwrites the original's schema
  26659. */
  26660. clone(schema) {
  26661. const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
  26662. if (schema)
  26663. copy.schema = schema;
  26664. copy.items = copy.items.map(it => isNode$1(it) || isPair(it) ? it.clone(schema) : it);
  26665. if (this.range)
  26666. copy.range = this.range.slice();
  26667. return copy;
  26668. }
  26669. /**
  26670. * Adds a value to the collection. For `!!map` and `!!omap` the value must
  26671. * be a Pair instance or a `{ key, value }` object, which may not have a key
  26672. * that already exists in the map.
  26673. */
  26674. addIn(path, value) {
  26675. if (isEmptyPath(path))
  26676. this.add(value);
  26677. else {
  26678. const [key, ...rest] = path;
  26679. const node = this.get(key, true);
  26680. if (isCollection$1(node))
  26681. node.addIn(rest, value);
  26682. else if (node === undefined && this.schema)
  26683. this.set(key, collectionFromPath(this.schema, rest, value));
  26684. else
  26685. throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  26686. }
  26687. }
  26688. /**
  26689. * Removes a value from the collection.
  26690. * @returns `true` if the item was found and removed.
  26691. */
  26692. deleteIn(path) {
  26693. const [key, ...rest] = path;
  26694. if (rest.length === 0)
  26695. return this.delete(key);
  26696. const node = this.get(key, true);
  26697. if (isCollection$1(node))
  26698. return node.deleteIn(rest);
  26699. else
  26700. throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  26701. }
  26702. /**
  26703. * Returns item at `key`, or `undefined` if not found. By default unwraps
  26704. * scalar values from their surrounding node; to disable set `keepScalar` to
  26705. * `true` (collections are always returned intact).
  26706. */
  26707. getIn(path, keepScalar) {
  26708. const [key, ...rest] = path;
  26709. const node = this.get(key, true);
  26710. if (rest.length === 0)
  26711. return !keepScalar && isScalar$1(node) ? node.value : node;
  26712. else
  26713. return isCollection$1(node) ? node.getIn(rest, keepScalar) : undefined;
  26714. }
  26715. hasAllNullValues(allowScalar) {
  26716. return this.items.every(node => {
  26717. if (!isPair(node))
  26718. return false;
  26719. const n = node.value;
  26720. return (n == null ||
  26721. (allowScalar &&
  26722. isScalar$1(n) &&
  26723. n.value == null &&
  26724. !n.commentBefore &&
  26725. !n.comment &&
  26726. !n.tag));
  26727. });
  26728. }
  26729. /**
  26730. * Checks if the collection includes a value with the key `key`.
  26731. */
  26732. hasIn(path) {
  26733. const [key, ...rest] = path;
  26734. if (rest.length === 0)
  26735. return this.has(key);
  26736. const node = this.get(key, true);
  26737. return isCollection$1(node) ? node.hasIn(rest) : false;
  26738. }
  26739. /**
  26740. * Sets a value in this collection. For `!!set`, `value` needs to be a
  26741. * boolean to add/remove the item from the set.
  26742. */
  26743. setIn(path, value) {
  26744. const [key, ...rest] = path;
  26745. if (rest.length === 0) {
  26746. this.set(key, value);
  26747. }
  26748. else {
  26749. const node = this.get(key, true);
  26750. if (isCollection$1(node))
  26751. node.setIn(rest, value);
  26752. else if (node === undefined && this.schema)
  26753. this.set(key, collectionFromPath(this.schema, rest, value));
  26754. else
  26755. throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  26756. }
  26757. }
  26758. }
  26759. Collection.maxFlowStringSingleLineLength = 60;
  26760. /**
  26761. * Stringifies a comment.
  26762. *
  26763. * Empty comment lines are left empty,
  26764. * lines consisting of a single space are replaced by `#`,
  26765. * and all other lines are prefixed with a `#`.
  26766. */
  26767. const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');
  26768. function indentComment(comment, indent) {
  26769. if (/^\n+$/.test(comment))
  26770. return comment.substring(1);
  26771. return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
  26772. }
  26773. const lineComment = (str, indent, comment) => str.endsWith('\n')
  26774. ? indentComment(comment, indent)
  26775. : comment.includes('\n')
  26776. ? '\n' + indentComment(comment, indent)
  26777. : (str.endsWith(' ') ? '' : ' ') + comment;
  26778. const FOLD_FLOW = 'flow';
  26779. const FOLD_BLOCK = 'block';
  26780. const FOLD_QUOTED = 'quoted';
  26781. /**
  26782. * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
  26783. * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
  26784. * terminated with `\n` and started with `indent`.
  26785. */
  26786. function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
  26787. if (!lineWidth || lineWidth < 0)
  26788. return text;
  26789. const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
  26790. if (text.length <= endStep)
  26791. return text;
  26792. const folds = [];
  26793. const escapedFolds = {};
  26794. let end = lineWidth - indent.length;
  26795. if (typeof indentAtStart === 'number') {
  26796. if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
  26797. folds.push(0);
  26798. else
  26799. end = lineWidth - indentAtStart;
  26800. }
  26801. let split = undefined;
  26802. let prev = undefined;
  26803. let overflow = false;
  26804. let i = -1;
  26805. let escStart = -1;
  26806. let escEnd = -1;
  26807. if (mode === FOLD_BLOCK) {
  26808. i = consumeMoreIndentedLines(text, i);
  26809. if (i !== -1)
  26810. end = i + endStep;
  26811. }
  26812. for (let ch; (ch = text[(i += 1)]);) {
  26813. if (mode === FOLD_QUOTED && ch === '\\') {
  26814. escStart = i;
  26815. switch (text[i + 1]) {
  26816. case 'x':
  26817. i += 3;
  26818. break;
  26819. case 'u':
  26820. i += 5;
  26821. break;
  26822. case 'U':
  26823. i += 9;
  26824. break;
  26825. default:
  26826. i += 1;
  26827. }
  26828. escEnd = i;
  26829. }
  26830. if (ch === '\n') {
  26831. if (mode === FOLD_BLOCK)
  26832. i = consumeMoreIndentedLines(text, i);
  26833. end = i + endStep;
  26834. split = undefined;
  26835. }
  26836. else {
  26837. if (ch === ' ' &&
  26838. prev &&
  26839. prev !== ' ' &&
  26840. prev !== '\n' &&
  26841. prev !== '\t') {
  26842. // space surrounded by non-space can be replaced with newline + indent
  26843. const next = text[i + 1];
  26844. if (next && next !== ' ' && next !== '\n' && next !== '\t')
  26845. split = i;
  26846. }
  26847. if (i >= end) {
  26848. if (split) {
  26849. folds.push(split);
  26850. end = split + endStep;
  26851. split = undefined;
  26852. }
  26853. else if (mode === FOLD_QUOTED) {
  26854. // white-space collected at end may stretch past lineWidth
  26855. while (prev === ' ' || prev === '\t') {
  26856. prev = ch;
  26857. ch = text[(i += 1)];
  26858. overflow = true;
  26859. }
  26860. // Account for newline escape, but don't break preceding escape
  26861. const j = i > escEnd + 1 ? i - 2 : escStart - 1;
  26862. // Bail out if lineWidth & minContentWidth are shorter than an escape string
  26863. if (escapedFolds[j])
  26864. return text;
  26865. folds.push(j);
  26866. escapedFolds[j] = true;
  26867. end = j + endStep;
  26868. split = undefined;
  26869. }
  26870. else {
  26871. overflow = true;
  26872. }
  26873. }
  26874. }
  26875. prev = ch;
  26876. }
  26877. if (overflow && onOverflow)
  26878. onOverflow();
  26879. if (folds.length === 0)
  26880. return text;
  26881. if (onFold)
  26882. onFold();
  26883. let res = text.slice(0, folds[0]);
  26884. for (let i = 0; i < folds.length; ++i) {
  26885. const fold = folds[i];
  26886. const end = folds[i + 1] || text.length;
  26887. if (fold === 0)
  26888. res = `\n${indent}${text.slice(0, end)}`;
  26889. else {
  26890. if (mode === FOLD_QUOTED && escapedFolds[fold])
  26891. res += `${text[fold]}\\`;
  26892. res += `\n${indent}${text.slice(fold + 1, end)}`;
  26893. }
  26894. }
  26895. return res;
  26896. }
  26897. /**
  26898. * Presumes `i + 1` is at the start of a line
  26899. * @returns index of last newline in more-indented block
  26900. */
  26901. function consumeMoreIndentedLines(text, i) {
  26902. let ch = text[i + 1];
  26903. while (ch === ' ' || ch === '\t') {
  26904. do {
  26905. ch = text[(i += 1)];
  26906. } while (ch && ch !== '\n');
  26907. ch = text[i + 1];
  26908. }
  26909. return i;
  26910. }
  26911. const getFoldOptions = (ctx) => ({
  26912. indentAtStart: ctx.indentAtStart,
  26913. lineWidth: ctx.options.lineWidth,
  26914. minContentWidth: ctx.options.minContentWidth
  26915. });
  26916. // Also checks for lines starting with %, as parsing the output as YAML 1.1 will
  26917. // presume that's starting a new document.
  26918. const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
  26919. function lineLengthOverLimit(str, lineWidth, indentLength) {
  26920. if (!lineWidth || lineWidth < 0)
  26921. return false;
  26922. const limit = lineWidth - indentLength;
  26923. const strLen = str.length;
  26924. if (strLen <= limit)
  26925. return false;
  26926. for (let i = 0, start = 0; i < strLen; ++i) {
  26927. if (str[i] === '\n') {
  26928. if (i - start > limit)
  26929. return true;
  26930. start = i + 1;
  26931. if (strLen - start <= limit)
  26932. return false;
  26933. }
  26934. }
  26935. return true;
  26936. }
  26937. function doubleQuotedString(value, ctx) {
  26938. const json = JSON.stringify(value);
  26939. if (ctx.options.doubleQuotedAsJSON)
  26940. return json;
  26941. const { implicitKey } = ctx;
  26942. const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
  26943. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  26944. let str = '';
  26945. let start = 0;
  26946. for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
  26947. if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
  26948. // space before newline needs to be escaped to not be folded
  26949. str += json.slice(start, i) + '\\ ';
  26950. i += 1;
  26951. start = i;
  26952. ch = '\\';
  26953. }
  26954. if (ch === '\\')
  26955. switch (json[i + 1]) {
  26956. case 'u':
  26957. {
  26958. str += json.slice(start, i);
  26959. const code = json.substr(i + 2, 4);
  26960. switch (code) {
  26961. case '0000':
  26962. str += '\\0';
  26963. break;
  26964. case '0007':
  26965. str += '\\a';
  26966. break;
  26967. case '000b':
  26968. str += '\\v';
  26969. break;
  26970. case '001b':
  26971. str += '\\e';
  26972. break;
  26973. case '0085':
  26974. str += '\\N';
  26975. break;
  26976. case '00a0':
  26977. str += '\\_';
  26978. break;
  26979. case '2028':
  26980. str += '\\L';
  26981. break;
  26982. case '2029':
  26983. str += '\\P';
  26984. break;
  26985. default:
  26986. if (code.substr(0, 2) === '00')
  26987. str += '\\x' + code.substr(2);
  26988. else
  26989. str += json.substr(i, 6);
  26990. }
  26991. i += 5;
  26992. start = i + 1;
  26993. }
  26994. break;
  26995. case 'n':
  26996. if (implicitKey ||
  26997. json[i + 2] === '"' ||
  26998. json.length < minMultiLineLength) {
  26999. i += 1;
  27000. }
  27001. else {
  27002. // folding will eat first newline
  27003. str += json.slice(start, i) + '\n\n';
  27004. while (json[i + 2] === '\\' &&
  27005. json[i + 3] === 'n' &&
  27006. json[i + 4] !== '"') {
  27007. str += '\n';
  27008. i += 2;
  27009. }
  27010. str += indent;
  27011. // space after newline needs to be escaped to not be folded
  27012. if (json[i + 2] === ' ')
  27013. str += '\\';
  27014. i += 1;
  27015. start = i + 1;
  27016. }
  27017. break;
  27018. default:
  27019. i += 1;
  27020. }
  27021. }
  27022. str = start ? str + json.slice(start) : json;
  27023. return implicitKey
  27024. ? str
  27025. : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
  27026. }
  27027. function singleQuotedString(value, ctx) {
  27028. if (ctx.options.singleQuote === false ||
  27029. (ctx.implicitKey && value.includes('\n')) ||
  27030. /[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline
  27031. )
  27032. return doubleQuotedString(value, ctx);
  27033. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  27034. const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
  27035. return ctx.implicitKey
  27036. ? res
  27037. : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
  27038. }
  27039. function quotedString(value, ctx) {
  27040. const { singleQuote } = ctx.options;
  27041. let qs;
  27042. if (singleQuote === false)
  27043. qs = doubleQuotedString;
  27044. else {
  27045. const hasDouble = value.includes('"');
  27046. const hasSingle = value.includes("'");
  27047. if (hasDouble && !hasSingle)
  27048. qs = singleQuotedString;
  27049. else if (hasSingle && !hasDouble)
  27050. qs = doubleQuotedString;
  27051. else
  27052. qs = singleQuote ? singleQuotedString : doubleQuotedString;
  27053. }
  27054. return qs(value, ctx);
  27055. }
  27056. function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
  27057. const { blockQuote, commentString, lineWidth } = ctx.options;
  27058. // 1. Block can't end in whitespace unless the last line is non-empty.
  27059. // 2. Strings consisting of only whitespace are best rendered explicitly.
  27060. if (!blockQuote || /\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
  27061. return quotedString(value, ctx);
  27062. }
  27063. const indent = ctx.indent ||
  27064. (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
  27065. const literal = blockQuote === 'literal'
  27066. ? true
  27067. : blockQuote === 'folded' || type === Scalar.BLOCK_FOLDED
  27068. ? false
  27069. : type === Scalar.BLOCK_LITERAL
  27070. ? true
  27071. : !lineLengthOverLimit(value, lineWidth, indent.length);
  27072. if (!value)
  27073. return literal ? '|\n' : '>\n';
  27074. // determine chomping from whitespace at value end
  27075. let chomp;
  27076. let endStart;
  27077. for (endStart = value.length; endStart > 0; --endStart) {
  27078. const ch = value[endStart - 1];
  27079. if (ch !== '\n' && ch !== '\t' && ch !== ' ')
  27080. break;
  27081. }
  27082. let end = value.substring(endStart);
  27083. const endNlPos = end.indexOf('\n');
  27084. if (endNlPos === -1) {
  27085. chomp = '-'; // strip
  27086. }
  27087. else if (value === end || endNlPos !== end.length - 1) {
  27088. chomp = '+'; // keep
  27089. if (onChompKeep)
  27090. onChompKeep();
  27091. }
  27092. else {
  27093. chomp = ''; // clip
  27094. }
  27095. if (end) {
  27096. value = value.slice(0, -end.length);
  27097. if (end[end.length - 1] === '\n')
  27098. end = end.slice(0, -1);
  27099. end = end.replace(/\n+(?!\n|$)/g, `$&${indent}`);
  27100. }
  27101. // determine indent indicator from whitespace at value start
  27102. let startWithSpace = false;
  27103. let startEnd;
  27104. let startNlPos = -1;
  27105. for (startEnd = 0; startEnd < value.length; ++startEnd) {
  27106. const ch = value[startEnd];
  27107. if (ch === ' ')
  27108. startWithSpace = true;
  27109. else if (ch === '\n')
  27110. startNlPos = startEnd;
  27111. else
  27112. break;
  27113. }
  27114. let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
  27115. if (start) {
  27116. value = value.substring(start.length);
  27117. start = start.replace(/\n+/g, `$&${indent}`);
  27118. }
  27119. const indentSize = indent ? '2' : '1'; // root is at -1
  27120. let header = (literal ? '|' : '>') + (startWithSpace ? indentSize : '') + chomp;
  27121. if (comment) {
  27122. header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' '));
  27123. if (onComment)
  27124. onComment();
  27125. }
  27126. if (literal) {
  27127. value = value.replace(/\n+/g, `$&${indent}`);
  27128. return `${header}\n${indent}${start}${value}${end}`;
  27129. }
  27130. value = value
  27131. .replace(/\n+/g, '\n$&')
  27132. .replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
  27133. // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
  27134. .replace(/\n+/g, `$&${indent}`);
  27135. const body = foldFlowLines(`${start}${value}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx));
  27136. return `${header}\n${indent}${body}`;
  27137. }
  27138. function plainString(item, ctx, onComment, onChompKeep) {
  27139. const { type, value } = item;
  27140. const { actualString, implicitKey, indent, inFlow } = ctx;
  27141. if ((implicitKey && /[\n[\]{},]/.test(value)) ||
  27142. (inFlow && /[[\]{},]/.test(value))) {
  27143. return quotedString(value, ctx);
  27144. }
  27145. if (!value ||
  27146. /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
  27147. // not allowed:
  27148. // - empty string, '-' or '?'
  27149. // - start with an indicator character (except [?:-]) or /[?-] /
  27150. // - '\n ', ': ' or ' \n' anywhere
  27151. // - '#' not preceded by a non-space char
  27152. // - end with ' ' or ':'
  27153. return implicitKey || inFlow || !value.includes('\n')
  27154. ? quotedString(value, ctx)
  27155. : blockString(item, ctx, onComment, onChompKeep);
  27156. }
  27157. if (!implicitKey &&
  27158. !inFlow &&
  27159. type !== Scalar.PLAIN &&
  27160. value.includes('\n')) {
  27161. // Where allowed & type not set explicitly, prefer block style for multiline strings
  27162. return blockString(item, ctx, onComment, onChompKeep);
  27163. }
  27164. if (indent === '' && containsDocumentMarker(value)) {
  27165. ctx.forceBlockIndent = true;
  27166. return blockString(item, ctx, onComment, onChompKeep);
  27167. }
  27168. const str = value.replace(/\n+/g, `$&\n${indent}`);
  27169. // Verify that output will be parsed as a string, as e.g. plain numbers and
  27170. // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
  27171. // and others in v1.1.
  27172. if (actualString) {
  27173. const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);
  27174. const { compat, tags } = ctx.doc.schema;
  27175. if (tags.some(test) || compat?.some(test))
  27176. return quotedString(value, ctx);
  27177. }
  27178. return implicitKey
  27179. ? str
  27180. : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
  27181. }
  27182. function stringifyString(item, ctx, onComment, onChompKeep) {
  27183. const { implicitKey, inFlow } = ctx;
  27184. const ss = typeof item.value === 'string'
  27185. ? item
  27186. : Object.assign({}, item, { value: String(item.value) });
  27187. let { type } = item;
  27188. if (type !== Scalar.QUOTE_DOUBLE) {
  27189. // force double quotes on control characters & unpaired surrogates
  27190. if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
  27191. type = Scalar.QUOTE_DOUBLE;
  27192. }
  27193. const _stringify = (_type) => {
  27194. switch (_type) {
  27195. case Scalar.BLOCK_FOLDED:
  27196. case Scalar.BLOCK_LITERAL:
  27197. return implicitKey || inFlow
  27198. ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers
  27199. : blockString(ss, ctx, onComment, onChompKeep);
  27200. case Scalar.QUOTE_DOUBLE:
  27201. return doubleQuotedString(ss.value, ctx);
  27202. case Scalar.QUOTE_SINGLE:
  27203. return singleQuotedString(ss.value, ctx);
  27204. case Scalar.PLAIN:
  27205. return plainString(ss, ctx, onComment, onChompKeep);
  27206. default:
  27207. return null;
  27208. }
  27209. };
  27210. let res = _stringify(type);
  27211. if (res === null) {
  27212. const { defaultKeyType, defaultStringType } = ctx.options;
  27213. const t = (implicitKey && defaultKeyType) || defaultStringType;
  27214. res = _stringify(t);
  27215. if (res === null)
  27216. throw new Error(`Unsupported default string type ${t}`);
  27217. }
  27218. return res;
  27219. }
  27220. function createStringifyContext(doc, options) {
  27221. const opt = Object.assign({
  27222. blockQuote: true,
  27223. commentString: stringifyComment,
  27224. defaultKeyType: null,
  27225. defaultStringType: 'PLAIN',
  27226. directives: null,
  27227. doubleQuotedAsJSON: false,
  27228. doubleQuotedMinMultiLineLength: 40,
  27229. falseStr: 'false',
  27230. indentSeq: true,
  27231. lineWidth: 80,
  27232. minContentWidth: 20,
  27233. nullStr: 'null',
  27234. simpleKeys: false,
  27235. singleQuote: null,
  27236. trueStr: 'true',
  27237. verifyAliasOrder: true
  27238. }, doc.schema.toStringOptions, options);
  27239. let inFlow;
  27240. switch (opt.collectionStyle) {
  27241. case 'block':
  27242. inFlow = false;
  27243. break;
  27244. case 'flow':
  27245. inFlow = true;
  27246. break;
  27247. default:
  27248. inFlow = null;
  27249. }
  27250. return {
  27251. anchors: new Set(),
  27252. doc,
  27253. indent: '',
  27254. indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',
  27255. inFlow,
  27256. options: opt
  27257. };
  27258. }
  27259. function getTagObject(tags, item) {
  27260. if (item.tag) {
  27261. const match = tags.filter(t => t.tag === item.tag);
  27262. if (match.length > 0)
  27263. return match.find(t => t.format === item.format) ?? match[0];
  27264. }
  27265. let tagObj = undefined;
  27266. let obj;
  27267. if (isScalar$1(item)) {
  27268. obj = item.value;
  27269. const match = tags.filter(t => t.identify?.(obj));
  27270. tagObj =
  27271. match.find(t => t.format === item.format) ?? match.find(t => !t.format);
  27272. }
  27273. else {
  27274. obj = item;
  27275. tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
  27276. }
  27277. if (!tagObj) {
  27278. const name = obj?.constructor?.name ?? typeof obj;
  27279. throw new Error(`Tag not resolved for ${name} value`);
  27280. }
  27281. return tagObj;
  27282. }
  27283. // needs to be called before value stringifier to allow for circular anchor refs
  27284. function stringifyProps(node, tagObj, { anchors, doc }) {
  27285. if (!doc.directives)
  27286. return '';
  27287. const props = [];
  27288. const anchor = (isScalar$1(node) || isCollection$1(node)) && node.anchor;
  27289. if (anchor && anchorIsValid(anchor)) {
  27290. anchors.add(anchor);
  27291. props.push(`&${anchor}`);
  27292. }
  27293. const tag = node.tag ? node.tag : tagObj.default ? null : tagObj.tag;
  27294. if (tag)
  27295. props.push(doc.directives.tagString(tag));
  27296. return props.join(' ');
  27297. }
  27298. function stringify$2(item, ctx, onComment, onChompKeep) {
  27299. if (isPair(item))
  27300. return item.toString(ctx, onComment, onChompKeep);
  27301. if (isAlias(item)) {
  27302. if (ctx.doc.directives)
  27303. return item.toString(ctx);
  27304. if (ctx.resolvedAliases?.has(item)) {
  27305. throw new TypeError(`Cannot stringify circular structure without alias nodes`);
  27306. }
  27307. else {
  27308. if (ctx.resolvedAliases)
  27309. ctx.resolvedAliases.add(item);
  27310. else
  27311. ctx.resolvedAliases = new Set([item]);
  27312. item = item.resolve(ctx.doc);
  27313. }
  27314. }
  27315. let tagObj = undefined;
  27316. const node = isNode$1(item)
  27317. ? item
  27318. : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });
  27319. if (!tagObj)
  27320. tagObj = getTagObject(ctx.doc.schema.tags, node);
  27321. const props = stringifyProps(node, tagObj, ctx);
  27322. if (props.length > 0)
  27323. ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
  27324. const str = typeof tagObj.stringify === 'function'
  27325. ? tagObj.stringify(node, ctx, onComment, onChompKeep)
  27326. : isScalar$1(node)
  27327. ? stringifyString(node, ctx, onComment, onChompKeep)
  27328. : node.toString(ctx, onComment, onChompKeep);
  27329. if (!props)
  27330. return str;
  27331. return isScalar$1(node) || str[0] === '{' || str[0] === '['
  27332. ? `${props} ${str}`
  27333. : `${props}\n${ctx.indent}${str}`;
  27334. }
  27335. function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
  27336. const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
  27337. let keyComment = (isNode$1(key) && key.comment) || null;
  27338. if (simpleKeys) {
  27339. if (keyComment) {
  27340. throw new Error('With simple keys, key nodes cannot have comments');
  27341. }
  27342. if (isCollection$1(key)) {
  27343. const msg = 'With simple keys, collection cannot be used as a key value';
  27344. throw new Error(msg);
  27345. }
  27346. }
  27347. let explicitKey = !simpleKeys &&
  27348. (!key ||
  27349. (keyComment && value == null && !ctx.inFlow) ||
  27350. isCollection$1(key) ||
  27351. (isScalar$1(key)
  27352. ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL
  27353. : typeof key === 'object'));
  27354. ctx = Object.assign({}, ctx, {
  27355. allNullValues: false,
  27356. implicitKey: !explicitKey && (simpleKeys || !allNullValues),
  27357. indent: indent + indentStep
  27358. });
  27359. let keyCommentDone = false;
  27360. let chompKeep = false;
  27361. let str = stringify$2(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));
  27362. if (!explicitKey && !ctx.inFlow && str.length > 1024) {
  27363. if (simpleKeys)
  27364. throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
  27365. explicitKey = true;
  27366. }
  27367. if (ctx.inFlow) {
  27368. if (allNullValues || value == null) {
  27369. if (keyCommentDone && onComment)
  27370. onComment();
  27371. return str === '' ? '?' : explicitKey ? `? ${str}` : str;
  27372. }
  27373. }
  27374. else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {
  27375. str = `? ${str}`;
  27376. if (keyComment && !keyCommentDone) {
  27377. str += lineComment(str, ctx.indent, commentString(keyComment));
  27378. }
  27379. else if (chompKeep && onChompKeep)
  27380. onChompKeep();
  27381. return str;
  27382. }
  27383. if (keyCommentDone)
  27384. keyComment = null;
  27385. if (explicitKey) {
  27386. if (keyComment)
  27387. str += lineComment(str, ctx.indent, commentString(keyComment));
  27388. str = `? ${str}\n${indent}:`;
  27389. }
  27390. else {
  27391. str = `${str}:`;
  27392. if (keyComment)
  27393. str += lineComment(str, ctx.indent, commentString(keyComment));
  27394. }
  27395. let vcb = '';
  27396. let valueComment = null;
  27397. if (isNode$1(value)) {
  27398. if (value.spaceBefore)
  27399. vcb = '\n';
  27400. if (value.commentBefore) {
  27401. const cs = commentString(value.commentBefore);
  27402. vcb += `\n${indentComment(cs, ctx.indent)}`;
  27403. }
  27404. valueComment = value.comment;
  27405. }
  27406. else if (value && typeof value === 'object') {
  27407. value = doc.createNode(value);
  27408. }
  27409. ctx.implicitKey = false;
  27410. if (!explicitKey && !keyComment && isScalar$1(value))
  27411. ctx.indentAtStart = str.length + 1;
  27412. chompKeep = false;
  27413. if (!indentSeq &&
  27414. indentStep.length >= 2 &&
  27415. !ctx.inFlow &&
  27416. !explicitKey &&
  27417. isSeq(value) &&
  27418. !value.flow &&
  27419. !value.tag &&
  27420. !value.anchor) {
  27421. // If indentSeq === false, consider '- ' as part of indentation where possible
  27422. ctx.indent = ctx.indent.substr(2);
  27423. }
  27424. let valueCommentDone = false;
  27425. const valueStr = stringify$2(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));
  27426. let ws = ' ';
  27427. if (vcb || keyComment) {
  27428. if (valueStr === '' && !ctx.inFlow)
  27429. ws = vcb === '\n' ? '\n\n' : vcb;
  27430. else
  27431. ws = `${vcb}\n${ctx.indent}`;
  27432. }
  27433. else if (!explicitKey && isCollection$1(value)) {
  27434. const flow = valueStr[0] === '[' || valueStr[0] === '{';
  27435. if (!flow || valueStr.includes('\n'))
  27436. ws = `\n${ctx.indent}`;
  27437. }
  27438. else if (valueStr === '' || valueStr[0] === '\n')
  27439. ws = '';
  27440. str += ws + valueStr;
  27441. if (ctx.inFlow) {
  27442. if (valueCommentDone && onComment)
  27443. onComment();
  27444. }
  27445. else if (valueComment && !valueCommentDone) {
  27446. str += lineComment(str, ctx.indent, commentString(valueComment));
  27447. }
  27448. else if (chompKeep && onChompKeep) {
  27449. onChompKeep();
  27450. }
  27451. return str;
  27452. }
  27453. function warn(logLevel, warning) {
  27454. if (logLevel === 'debug' || logLevel === 'warn') {
  27455. if (typeof process !== 'undefined' && process.emitWarning)
  27456. process.emitWarning(warning);
  27457. else
  27458. console.warn(warning);
  27459. }
  27460. }
  27461. const MERGE_KEY = '<<';
  27462. function addPairToJSMap(ctx, map, { key, value }) {
  27463. if (ctx?.doc.schema.merge && isMergeKey(key)) {
  27464. value = isAlias(value) ? value.resolve(ctx.doc) : value;
  27465. if (isSeq(value))
  27466. for (const it of value.items)
  27467. mergeToJSMap(ctx, map, it);
  27468. else if (Array.isArray(value))
  27469. for (const it of value)
  27470. mergeToJSMap(ctx, map, it);
  27471. else
  27472. mergeToJSMap(ctx, map, value);
  27473. }
  27474. else {
  27475. const jsKey = toJS(key, '', ctx);
  27476. if (map instanceof Map) {
  27477. map.set(jsKey, toJS(value, jsKey, ctx));
  27478. }
  27479. else if (map instanceof Set) {
  27480. map.add(jsKey);
  27481. }
  27482. else {
  27483. const stringKey = stringifyKey(key, jsKey, ctx);
  27484. const jsValue = toJS(value, stringKey, ctx);
  27485. if (stringKey in map)
  27486. Object.defineProperty(map, stringKey, {
  27487. value: jsValue,
  27488. writable: true,
  27489. enumerable: true,
  27490. configurable: true
  27491. });
  27492. else
  27493. map[stringKey] = jsValue;
  27494. }
  27495. }
  27496. return map;
  27497. }
  27498. const isMergeKey = (key) => key === MERGE_KEY ||
  27499. (isScalar$1(key) &&
  27500. key.value === MERGE_KEY &&
  27501. (!key.type || key.type === Scalar.PLAIN));
  27502. // If the value associated with a merge key is a single mapping node, each of
  27503. // its key/value pairs is inserted into the current mapping, unless the key
  27504. // already exists in it. If the value associated with the merge key is a
  27505. // sequence, then this sequence is expected to contain mapping nodes and each
  27506. // of these nodes is merged in turn according to its order in the sequence.
  27507. // Keys in mapping nodes earlier in the sequence override keys specified in
  27508. // later mapping nodes. -- http://yaml.org/type/merge.html
  27509. function mergeToJSMap(ctx, map, value) {
  27510. const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;
  27511. if (!isMap(source))
  27512. throw new Error('Merge sources must be maps or map aliases');
  27513. const srcMap = source.toJSON(null, ctx, Map);
  27514. for (const [key, value] of srcMap) {
  27515. if (map instanceof Map) {
  27516. if (!map.has(key))
  27517. map.set(key, value);
  27518. }
  27519. else if (map instanceof Set) {
  27520. map.add(key);
  27521. }
  27522. else if (!Object.prototype.hasOwnProperty.call(map, key)) {
  27523. Object.defineProperty(map, key, {
  27524. value,
  27525. writable: true,
  27526. enumerable: true,
  27527. configurable: true
  27528. });
  27529. }
  27530. }
  27531. return map;
  27532. }
  27533. function stringifyKey(key, jsKey, ctx) {
  27534. if (jsKey === null)
  27535. return '';
  27536. if (typeof jsKey !== 'object')
  27537. return String(jsKey);
  27538. if (isNode$1(key) && ctx && ctx.doc) {
  27539. const strCtx = createStringifyContext(ctx.doc, {});
  27540. strCtx.anchors = new Set();
  27541. for (const node of ctx.anchors.keys())
  27542. strCtx.anchors.add(node.anchor);
  27543. strCtx.inFlow = true;
  27544. strCtx.inStringifyKey = true;
  27545. const strKey = key.toString(strCtx);
  27546. if (!ctx.mapKeyWarned) {
  27547. let jsonStr = JSON.stringify(strKey);
  27548. if (jsonStr.length > 40)
  27549. jsonStr = jsonStr.substring(0, 36) + '..."';
  27550. warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
  27551. ctx.mapKeyWarned = true;
  27552. }
  27553. return strKey;
  27554. }
  27555. return JSON.stringify(jsKey);
  27556. }
  27557. function createPair(key, value, ctx) {
  27558. const k = createNode(key, undefined, ctx);
  27559. const v = createNode(value, undefined, ctx);
  27560. return new Pair(k, v);
  27561. }
  27562. class Pair {
  27563. constructor(key, value = null) {
  27564. Object.defineProperty(this, NODE_TYPE, { value: PAIR });
  27565. this.key = key;
  27566. this.value = value;
  27567. }
  27568. clone(schema) {
  27569. let { key, value } = this;
  27570. if (isNode$1(key))
  27571. key = key.clone(schema);
  27572. if (isNode$1(value))
  27573. value = value.clone(schema);
  27574. return new Pair(key, value);
  27575. }
  27576. toJSON(_, ctx) {
  27577. const pair = ctx?.mapAsMap ? new Map() : {};
  27578. return addPairToJSMap(ctx, pair, this);
  27579. }
  27580. toString(ctx, onComment, onChompKeep) {
  27581. return ctx?.doc
  27582. ? stringifyPair(this, ctx, onComment, onChompKeep)
  27583. : JSON.stringify(this);
  27584. }
  27585. }
  27586. function stringifyCollection(collection, ctx, options) {
  27587. const flow = ctx.inFlow ?? collection.flow;
  27588. const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
  27589. return stringify(collection, ctx, options);
  27590. }
  27591. function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
  27592. const { indent, options: { commentString } } = ctx;
  27593. const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
  27594. let chompKeep = false; // flag for the preceding node's status
  27595. const lines = [];
  27596. for (let i = 0; i < items.length; ++i) {
  27597. const item = items[i];
  27598. let comment = null;
  27599. if (isNode$1(item)) {
  27600. if (!chompKeep && item.spaceBefore)
  27601. lines.push('');
  27602. addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
  27603. if (item.comment)
  27604. comment = item.comment;
  27605. }
  27606. else if (isPair(item)) {
  27607. const ik = isNode$1(item.key) ? item.key : null;
  27608. if (ik) {
  27609. if (!chompKeep && ik.spaceBefore)
  27610. lines.push('');
  27611. addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
  27612. }
  27613. }
  27614. chompKeep = false;
  27615. let str = stringify$2(item, itemCtx, () => (comment = null), () => (chompKeep = true));
  27616. if (comment)
  27617. str += lineComment(str, itemIndent, commentString(comment));
  27618. if (chompKeep && comment)
  27619. chompKeep = false;
  27620. lines.push(blockItemPrefix + str);
  27621. }
  27622. let str;
  27623. if (lines.length === 0) {
  27624. str = flowChars.start + flowChars.end;
  27625. }
  27626. else {
  27627. str = lines[0];
  27628. for (let i = 1; i < lines.length; ++i) {
  27629. const line = lines[i];
  27630. str += line ? `\n${indent}${line}` : '\n';
  27631. }
  27632. }
  27633. if (comment) {
  27634. str += '\n' + indentComment(commentString(comment), indent);
  27635. if (onComment)
  27636. onComment();
  27637. }
  27638. else if (chompKeep && onChompKeep)
  27639. onChompKeep();
  27640. return str;
  27641. }
  27642. function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemIndent, onComment }) {
  27643. const { indent, indentStep, options: { commentString } } = ctx;
  27644. itemIndent += indentStep;
  27645. const itemCtx = Object.assign({}, ctx, {
  27646. indent: itemIndent,
  27647. inFlow: true,
  27648. type: null
  27649. });
  27650. let reqNewline = false;
  27651. let linesAtValue = 0;
  27652. const lines = [];
  27653. for (let i = 0; i < items.length; ++i) {
  27654. const item = items[i];
  27655. let comment = null;
  27656. if (isNode$1(item)) {
  27657. if (item.spaceBefore)
  27658. lines.push('');
  27659. addCommentBefore(ctx, lines, item.commentBefore, false);
  27660. if (item.comment)
  27661. comment = item.comment;
  27662. }
  27663. else if (isPair(item)) {
  27664. const ik = isNode$1(item.key) ? item.key : null;
  27665. if (ik) {
  27666. if (ik.spaceBefore)
  27667. lines.push('');
  27668. addCommentBefore(ctx, lines, ik.commentBefore, false);
  27669. if (ik.comment)
  27670. reqNewline = true;
  27671. }
  27672. const iv = isNode$1(item.value) ? item.value : null;
  27673. if (iv) {
  27674. if (iv.comment)
  27675. comment = iv.comment;
  27676. if (iv.commentBefore)
  27677. reqNewline = true;
  27678. }
  27679. else if (item.value == null && ik && ik.comment) {
  27680. comment = ik.comment;
  27681. }
  27682. }
  27683. if (comment)
  27684. reqNewline = true;
  27685. let str = stringify$2(item, itemCtx, () => (comment = null));
  27686. if (i < items.length - 1)
  27687. str += ',';
  27688. if (comment)
  27689. str += lineComment(str, itemIndent, commentString(comment));
  27690. if (!reqNewline && (lines.length > linesAtValue || str.includes('\n')))
  27691. reqNewline = true;
  27692. lines.push(str);
  27693. linesAtValue = lines.length;
  27694. }
  27695. let str;
  27696. const { start, end } = flowChars;
  27697. if (lines.length === 0) {
  27698. str = start + end;
  27699. }
  27700. else {
  27701. if (!reqNewline) {
  27702. const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
  27703. reqNewline = len > Collection.maxFlowStringSingleLineLength;
  27704. }
  27705. if (reqNewline) {
  27706. str = start;
  27707. for (const line of lines)
  27708. str += line ? `\n${indentStep}${indent}${line}` : '\n';
  27709. str += `\n${indent}${end}`;
  27710. }
  27711. else {
  27712. str = `${start} ${lines.join(' ')} ${end}`;
  27713. }
  27714. }
  27715. if (comment) {
  27716. str += lineComment(str, commentString(comment), indent);
  27717. if (onComment)
  27718. onComment();
  27719. }
  27720. return str;
  27721. }
  27722. function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
  27723. if (comment && chompKeep)
  27724. comment = comment.replace(/^\n+/, '');
  27725. if (comment) {
  27726. const ic = indentComment(commentString(comment), indent);
  27727. lines.push(ic.trimStart()); // Avoid double indent on first line
  27728. }
  27729. }
  27730. function findPair(items, key) {
  27731. const k = isScalar$1(key) ? key.value : key;
  27732. for (const it of items) {
  27733. if (isPair(it)) {
  27734. if (it.key === key || it.key === k)
  27735. return it;
  27736. if (isScalar$1(it.key) && it.key.value === k)
  27737. return it;
  27738. }
  27739. }
  27740. return undefined;
  27741. }
  27742. class YAMLMap extends Collection {
  27743. constructor(schema) {
  27744. super(MAP, schema);
  27745. this.items = [];
  27746. }
  27747. static get tagName() {
  27748. return 'tag:yaml.org,2002:map';
  27749. }
  27750. /**
  27751. * Adds a value to the collection.
  27752. *
  27753. * @param overwrite - If not set `true`, using a key that is already in the
  27754. * collection will throw. Otherwise, overwrites the previous value.
  27755. */
  27756. add(pair, overwrite) {
  27757. let _pair;
  27758. if (isPair(pair))
  27759. _pair = pair;
  27760. else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
  27761. // In TypeScript, this never happens.
  27762. _pair = new Pair(pair, pair?.value);
  27763. }
  27764. else
  27765. _pair = new Pair(pair.key, pair.value);
  27766. const prev = findPair(this.items, _pair.key);
  27767. const sortEntries = this.schema?.sortMapEntries;
  27768. if (prev) {
  27769. if (!overwrite)
  27770. throw new Error(`Key ${_pair.key} already set`);
  27771. // For scalars, keep the old node & its comments and anchors
  27772. if (isScalar$1(prev.value) && isScalarValue(_pair.value))
  27773. prev.value.value = _pair.value;
  27774. else
  27775. prev.value = _pair.value;
  27776. }
  27777. else if (sortEntries) {
  27778. const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);
  27779. if (i === -1)
  27780. this.items.push(_pair);
  27781. else
  27782. this.items.splice(i, 0, _pair);
  27783. }
  27784. else {
  27785. this.items.push(_pair);
  27786. }
  27787. }
  27788. delete(key) {
  27789. const it = findPair(this.items, key);
  27790. if (!it)
  27791. return false;
  27792. const del = this.items.splice(this.items.indexOf(it), 1);
  27793. return del.length > 0;
  27794. }
  27795. get(key, keepScalar) {
  27796. const it = findPair(this.items, key);
  27797. const node = it?.value;
  27798. return (!keepScalar && isScalar$1(node) ? node.value : node) ?? undefined;
  27799. }
  27800. has(key) {
  27801. return !!findPair(this.items, key);
  27802. }
  27803. set(key, value) {
  27804. this.add(new Pair(key, value), true);
  27805. }
  27806. /**
  27807. * @param ctx - Conversion context, originally set in Document#toJS()
  27808. * @param {Class} Type - If set, forces the returned collection type
  27809. * @returns Instance of Type, Map, or Object
  27810. */
  27811. toJSON(_, ctx, Type) {
  27812. const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};
  27813. if (ctx?.onCreate)
  27814. ctx.onCreate(map);
  27815. for (const item of this.items)
  27816. addPairToJSMap(ctx, map, item);
  27817. return map;
  27818. }
  27819. toString(ctx, onComment, onChompKeep) {
  27820. if (!ctx)
  27821. return JSON.stringify(this);
  27822. for (const item of this.items) {
  27823. if (!isPair(item))
  27824. throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
  27825. }
  27826. if (!ctx.allNullValues && this.hasAllNullValues(false))
  27827. ctx = Object.assign({}, ctx, { allNullValues: true });
  27828. return stringifyCollection(this, ctx, {
  27829. blockItemPrefix: '',
  27830. flowChars: { start: '{', end: '}' },
  27831. itemIndent: ctx.indent || '',
  27832. onChompKeep,
  27833. onComment
  27834. });
  27835. }
  27836. }
  27837. function createMap(schema, obj, ctx) {
  27838. const { keepUndefined, replacer } = ctx;
  27839. const map = new YAMLMap(schema);
  27840. const add = (key, value) => {
  27841. if (typeof replacer === 'function')
  27842. value = replacer.call(obj, key, value);
  27843. else if (Array.isArray(replacer) && !replacer.includes(key))
  27844. return;
  27845. if (value !== undefined || keepUndefined)
  27846. map.items.push(createPair(key, value, ctx));
  27847. };
  27848. if (obj instanceof Map) {
  27849. for (const [key, value] of obj)
  27850. add(key, value);
  27851. }
  27852. else if (obj && typeof obj === 'object') {
  27853. for (const key of Object.keys(obj))
  27854. add(key, obj[key]);
  27855. }
  27856. if (typeof schema.sortMapEntries === 'function') {
  27857. map.items.sort(schema.sortMapEntries);
  27858. }
  27859. return map;
  27860. }
  27861. const map = {
  27862. collection: 'map',
  27863. createNode: createMap,
  27864. default: true,
  27865. nodeClass: YAMLMap,
  27866. tag: 'tag:yaml.org,2002:map',
  27867. resolve(map, onError) {
  27868. if (!isMap(map))
  27869. onError('Expected a mapping for this tag');
  27870. return map;
  27871. }
  27872. };
  27873. class YAMLSeq extends Collection {
  27874. constructor(schema) {
  27875. super(SEQ, schema);
  27876. this.items = [];
  27877. }
  27878. static get tagName() {
  27879. return 'tag:yaml.org,2002:seq';
  27880. }
  27881. add(value) {
  27882. this.items.push(value);
  27883. }
  27884. /**
  27885. * Removes a value from the collection.
  27886. *
  27887. * `key` must contain a representation of an integer for this to succeed.
  27888. * It may be wrapped in a `Scalar`.
  27889. *
  27890. * @returns `true` if the item was found and removed.
  27891. */
  27892. delete(key) {
  27893. const idx = asItemIndex(key);
  27894. if (typeof idx !== 'number')
  27895. return false;
  27896. const del = this.items.splice(idx, 1);
  27897. return del.length > 0;
  27898. }
  27899. get(key, keepScalar) {
  27900. const idx = asItemIndex(key);
  27901. if (typeof idx !== 'number')
  27902. return undefined;
  27903. const it = this.items[idx];
  27904. return !keepScalar && isScalar$1(it) ? it.value : it;
  27905. }
  27906. /**
  27907. * Checks if the collection includes a value with the key `key`.
  27908. *
  27909. * `key` must contain a representation of an integer for this to succeed.
  27910. * It may be wrapped in a `Scalar`.
  27911. */
  27912. has(key) {
  27913. const idx = asItemIndex(key);
  27914. return typeof idx === 'number' && idx < this.items.length;
  27915. }
  27916. /**
  27917. * Sets a value in this collection. For `!!set`, `value` needs to be a
  27918. * boolean to add/remove the item from the set.
  27919. *
  27920. * If `key` does not contain a representation of an integer, this will throw.
  27921. * It may be wrapped in a `Scalar`.
  27922. */
  27923. set(key, value) {
  27924. const idx = asItemIndex(key);
  27925. if (typeof idx !== 'number')
  27926. throw new Error(`Expected a valid index, not ${key}.`);
  27927. const prev = this.items[idx];
  27928. if (isScalar$1(prev) && isScalarValue(value))
  27929. prev.value = value;
  27930. else
  27931. this.items[idx] = value;
  27932. }
  27933. toJSON(_, ctx) {
  27934. const seq = [];
  27935. if (ctx?.onCreate)
  27936. ctx.onCreate(seq);
  27937. let i = 0;
  27938. for (const item of this.items)
  27939. seq.push(toJS(item, String(i++), ctx));
  27940. return seq;
  27941. }
  27942. toString(ctx, onComment, onChompKeep) {
  27943. if (!ctx)
  27944. return JSON.stringify(this);
  27945. return stringifyCollection(this, ctx, {
  27946. blockItemPrefix: '- ',
  27947. flowChars: { start: '[', end: ']' },
  27948. itemIndent: (ctx.indent || '') + ' ',
  27949. onChompKeep,
  27950. onComment
  27951. });
  27952. }
  27953. }
  27954. function asItemIndex(key) {
  27955. let idx = isScalar$1(key) ? key.value : key;
  27956. if (idx && typeof idx === 'string')
  27957. idx = Number(idx);
  27958. return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0
  27959. ? idx
  27960. : null;
  27961. }
  27962. function createSeq(schema, obj, ctx) {
  27963. const { replacer } = ctx;
  27964. const seq = new YAMLSeq(schema);
  27965. if (obj && Symbol.iterator in Object(obj)) {
  27966. let i = 0;
  27967. for (let it of obj) {
  27968. if (typeof replacer === 'function') {
  27969. const key = obj instanceof Set ? it : String(i++);
  27970. it = replacer.call(obj, key, it);
  27971. }
  27972. seq.items.push(createNode(it, undefined, ctx));
  27973. }
  27974. }
  27975. return seq;
  27976. }
  27977. const seq = {
  27978. collection: 'seq',
  27979. createNode: createSeq,
  27980. default: true,
  27981. nodeClass: YAMLSeq,
  27982. tag: 'tag:yaml.org,2002:seq',
  27983. resolve(seq, onError) {
  27984. if (!isSeq(seq))
  27985. onError('Expected a sequence for this tag');
  27986. return seq;
  27987. }
  27988. };
  27989. const string = {
  27990. identify: value => typeof value === 'string',
  27991. default: true,
  27992. tag: 'tag:yaml.org,2002:str',
  27993. resolve: str => str,
  27994. stringify(item, ctx, onComment, onChompKeep) {
  27995. ctx = Object.assign({ actualString: true }, ctx);
  27996. return stringifyString(item, ctx, onComment, onChompKeep);
  27997. }
  27998. };
  27999. const nullTag = {
  28000. identify: value => value == null,
  28001. createNode: () => new Scalar(null),
  28002. default: true,
  28003. tag: 'tag:yaml.org,2002:null',
  28004. test: /^(?:~|[Nn]ull|NULL)?$/,
  28005. resolve: () => new Scalar(null),
  28006. stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)
  28007. ? source
  28008. : ctx.options.nullStr
  28009. };
  28010. const boolTag = {
  28011. identify: value => typeof value === 'boolean',
  28012. default: true,
  28013. tag: 'tag:yaml.org,2002:bool',
  28014. test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
  28015. resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'),
  28016. stringify({ source, value }, ctx) {
  28017. if (source && boolTag.test.test(source)) {
  28018. const sv = source[0] === 't' || source[0] === 'T';
  28019. if (value === sv)
  28020. return source;
  28021. }
  28022. return value ? ctx.options.trueStr : ctx.options.falseStr;
  28023. }
  28024. };
  28025. function stringifyNumber({ format, minFractionDigits, tag, value }) {
  28026. if (typeof value === 'bigint')
  28027. return String(value);
  28028. const num = typeof value === 'number' ? value : Number(value);
  28029. if (!isFinite(num))
  28030. return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';
  28031. let n = JSON.stringify(value);
  28032. if (!format &&
  28033. minFractionDigits &&
  28034. (!tag || tag === 'tag:yaml.org,2002:float') &&
  28035. /^\d/.test(n)) {
  28036. let i = n.indexOf('.');
  28037. if (i < 0) {
  28038. i = n.length;
  28039. n += '.';
  28040. }
  28041. let d = minFractionDigits - (n.length - i - 1);
  28042. while (d-- > 0)
  28043. n += '0';
  28044. }
  28045. return n;
  28046. }
  28047. const floatNaN$1 = {
  28048. identify: value => typeof value === 'number',
  28049. default: true,
  28050. tag: 'tag:yaml.org,2002:float',
  28051. test: /^(?:[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN))$/,
  28052. resolve: str => str.slice(-3).toLowerCase() === 'nan'
  28053. ? NaN
  28054. : str[0] === '-'
  28055. ? Number.NEGATIVE_INFINITY
  28056. : Number.POSITIVE_INFINITY,
  28057. stringify: stringifyNumber
  28058. };
  28059. const floatExp$1 = {
  28060. identify: value => typeof value === 'number',
  28061. default: true,
  28062. tag: 'tag:yaml.org,2002:float',
  28063. format: 'EXP',
  28064. test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
  28065. resolve: str => parseFloat(str),
  28066. stringify(node) {
  28067. const num = Number(node.value);
  28068. return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  28069. }
  28070. };
  28071. const float$1 = {
  28072. identify: value => typeof value === 'number',
  28073. default: true,
  28074. tag: 'tag:yaml.org,2002:float',
  28075. test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
  28076. resolve(str) {
  28077. const node = new Scalar(parseFloat(str));
  28078. const dot = str.indexOf('.');
  28079. if (dot !== -1 && str[str.length - 1] === '0')
  28080. node.minFractionDigits = str.length - dot - 1;
  28081. return node;
  28082. },
  28083. stringify: stringifyNumber
  28084. };
  28085. const intIdentify$2 = (value) => typeof value === 'bigint' || Number.isInteger(value);
  28086. const intResolve$1 = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));
  28087. function intStringify$1(node, radix, prefix) {
  28088. const { value } = node;
  28089. if (intIdentify$2(value) && value >= 0)
  28090. return prefix + value.toString(radix);
  28091. return stringifyNumber(node);
  28092. }
  28093. const intOct$1 = {
  28094. identify: value => intIdentify$2(value) && value >= 0,
  28095. default: true,
  28096. tag: 'tag:yaml.org,2002:int',
  28097. format: 'OCT',
  28098. test: /^0o[0-7]+$/,
  28099. resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt),
  28100. stringify: node => intStringify$1(node, 8, '0o')
  28101. };
  28102. const int$1 = {
  28103. identify: intIdentify$2,
  28104. default: true,
  28105. tag: 'tag:yaml.org,2002:int',
  28106. test: /^[-+]?[0-9]+$/,
  28107. resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt),
  28108. stringify: stringifyNumber
  28109. };
  28110. const intHex$1 = {
  28111. identify: value => intIdentify$2(value) && value >= 0,
  28112. default: true,
  28113. tag: 'tag:yaml.org,2002:int',
  28114. format: 'HEX',
  28115. test: /^0x[0-9a-fA-F]+$/,
  28116. resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt),
  28117. stringify: node => intStringify$1(node, 16, '0x')
  28118. };
  28119. const schema$2 = [
  28120. map,
  28121. seq,
  28122. string,
  28123. nullTag,
  28124. boolTag,
  28125. intOct$1,
  28126. int$1,
  28127. intHex$1,
  28128. floatNaN$1,
  28129. floatExp$1,
  28130. float$1
  28131. ];
  28132. function intIdentify$1(value) {
  28133. return typeof value === 'bigint' || Number.isInteger(value);
  28134. }
  28135. const stringifyJSON = ({ value }) => JSON.stringify(value);
  28136. const jsonScalars = [
  28137. {
  28138. identify: value => typeof value === 'string',
  28139. default: true,
  28140. tag: 'tag:yaml.org,2002:str',
  28141. resolve: str => str,
  28142. stringify: stringifyJSON
  28143. },
  28144. {
  28145. identify: value => value == null,
  28146. createNode: () => new Scalar(null),
  28147. default: true,
  28148. tag: 'tag:yaml.org,2002:null',
  28149. test: /^null$/,
  28150. resolve: () => null,
  28151. stringify: stringifyJSON
  28152. },
  28153. {
  28154. identify: value => typeof value === 'boolean',
  28155. default: true,
  28156. tag: 'tag:yaml.org,2002:bool',
  28157. test: /^true|false$/,
  28158. resolve: str => str === 'true',
  28159. stringify: stringifyJSON
  28160. },
  28161. {
  28162. identify: intIdentify$1,
  28163. default: true,
  28164. tag: 'tag:yaml.org,2002:int',
  28165. test: /^-?(?:0|[1-9][0-9]*)$/,
  28166. resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
  28167. stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
  28168. },
  28169. {
  28170. identify: value => typeof value === 'number',
  28171. default: true,
  28172. tag: 'tag:yaml.org,2002:float',
  28173. test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
  28174. resolve: str => parseFloat(str),
  28175. stringify: stringifyJSON
  28176. }
  28177. ];
  28178. const jsonError = {
  28179. default: true,
  28180. tag: '',
  28181. test: /^/,
  28182. resolve(str, onError) {
  28183. onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
  28184. return str;
  28185. }
  28186. };
  28187. const schema$1 = [map, seq].concat(jsonScalars, jsonError);
  28188. const binary = {
  28189. identify: value => value instanceof Uint8Array,
  28190. default: false,
  28191. tag: 'tag:yaml.org,2002:binary',
  28192. /**
  28193. * Returns a Buffer in node and an Uint8Array in browsers
  28194. *
  28195. * To use the resulting buffer as an image, you'll want to do something like:
  28196. *
  28197. * const blob = new Blob([buffer], { type: 'image/jpeg' })
  28198. * document.querySelector('#photo').src = URL.createObjectURL(blob)
  28199. */
  28200. resolve(src, onError) {
  28201. if (typeof Buffer === 'function') {
  28202. return Buffer.from(src, 'base64');
  28203. }
  28204. else if (typeof atob === 'function') {
  28205. // On IE 11, atob() can't handle newlines
  28206. const str = atob(src.replace(/[\n\r]/g, ''));
  28207. const buffer = new Uint8Array(str.length);
  28208. for (let i = 0; i < str.length; ++i)
  28209. buffer[i] = str.charCodeAt(i);
  28210. return buffer;
  28211. }
  28212. else {
  28213. onError('This environment does not support reading binary tags; either Buffer or atob is required');
  28214. return src;
  28215. }
  28216. },
  28217. stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
  28218. const buf = value; // checked earlier by binary.identify()
  28219. let str;
  28220. if (typeof Buffer === 'function') {
  28221. str =
  28222. buf instanceof Buffer
  28223. ? buf.toString('base64')
  28224. : Buffer.from(buf.buffer).toString('base64');
  28225. }
  28226. else if (typeof btoa === 'function') {
  28227. let s = '';
  28228. for (let i = 0; i < buf.length; ++i)
  28229. s += String.fromCharCode(buf[i]);
  28230. str = btoa(s);
  28231. }
  28232. else {
  28233. throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
  28234. }
  28235. if (!type)
  28236. type = Scalar.BLOCK_LITERAL;
  28237. if (type !== Scalar.QUOTE_DOUBLE) {
  28238. const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
  28239. const n = Math.ceil(str.length / lineWidth);
  28240. const lines = new Array(n);
  28241. for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
  28242. lines[i] = str.substr(o, lineWidth);
  28243. }
  28244. str = lines.join(type === Scalar.BLOCK_LITERAL ? '\n' : ' ');
  28245. }
  28246. return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
  28247. }
  28248. };
  28249. function resolvePairs(seq, onError) {
  28250. if (isSeq(seq)) {
  28251. for (let i = 0; i < seq.items.length; ++i) {
  28252. let item = seq.items[i];
  28253. if (isPair(item))
  28254. continue;
  28255. else if (isMap(item)) {
  28256. if (item.items.length > 1)
  28257. onError('Each pair must have its own sequence indicator');
  28258. const pair = item.items[0] || new Pair(new Scalar(null));
  28259. if (item.commentBefore)
  28260. pair.key.commentBefore = pair.key.commentBefore
  28261. ? `${item.commentBefore}\n${pair.key.commentBefore}`
  28262. : item.commentBefore;
  28263. if (item.comment) {
  28264. const cn = pair.value ?? pair.key;
  28265. cn.comment = cn.comment
  28266. ? `${item.comment}\n${cn.comment}`
  28267. : item.comment;
  28268. }
  28269. item = pair;
  28270. }
  28271. seq.items[i] = isPair(item) ? item : new Pair(item);
  28272. }
  28273. }
  28274. else
  28275. onError('Expected a sequence for this tag');
  28276. return seq;
  28277. }
  28278. function createPairs(schema, iterable, ctx) {
  28279. const { replacer } = ctx;
  28280. const pairs = new YAMLSeq(schema);
  28281. pairs.tag = 'tag:yaml.org,2002:pairs';
  28282. let i = 0;
  28283. if (iterable && Symbol.iterator in Object(iterable))
  28284. for (let it of iterable) {
  28285. if (typeof replacer === 'function')
  28286. it = replacer.call(iterable, String(i++), it);
  28287. let key, value;
  28288. if (Array.isArray(it)) {
  28289. if (it.length === 2) {
  28290. key = it[0];
  28291. value = it[1];
  28292. }
  28293. else
  28294. throw new TypeError(`Expected [key, value] tuple: ${it}`);
  28295. }
  28296. else if (it && it instanceof Object) {
  28297. const keys = Object.keys(it);
  28298. if (keys.length === 1) {
  28299. key = keys[0];
  28300. value = it[key];
  28301. }
  28302. else
  28303. throw new TypeError(`Expected { key: value } tuple: ${it}`);
  28304. }
  28305. else {
  28306. key = it;
  28307. }
  28308. pairs.items.push(createPair(key, value, ctx));
  28309. }
  28310. return pairs;
  28311. }
  28312. const pairs = {
  28313. collection: 'seq',
  28314. default: false,
  28315. tag: 'tag:yaml.org,2002:pairs',
  28316. resolve: resolvePairs,
  28317. createNode: createPairs
  28318. };
  28319. class YAMLOMap extends YAMLSeq {
  28320. constructor() {
  28321. super();
  28322. this.add = YAMLMap.prototype.add.bind(this);
  28323. this.delete = YAMLMap.prototype.delete.bind(this);
  28324. this.get = YAMLMap.prototype.get.bind(this);
  28325. this.has = YAMLMap.prototype.has.bind(this);
  28326. this.set = YAMLMap.prototype.set.bind(this);
  28327. this.tag = YAMLOMap.tag;
  28328. }
  28329. /**
  28330. * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
  28331. * but TypeScript won't allow widening the signature of a child method.
  28332. */
  28333. toJSON(_, ctx) {
  28334. if (!ctx)
  28335. return super.toJSON(_);
  28336. const map = new Map();
  28337. if (ctx?.onCreate)
  28338. ctx.onCreate(map);
  28339. for (const pair of this.items) {
  28340. let key, value;
  28341. if (isPair(pair)) {
  28342. key = toJS(pair.key, '', ctx);
  28343. value = toJS(pair.value, key, ctx);
  28344. }
  28345. else {
  28346. key = toJS(pair, '', ctx);
  28347. }
  28348. if (map.has(key))
  28349. throw new Error('Ordered maps must not include duplicate keys');
  28350. map.set(key, value);
  28351. }
  28352. return map;
  28353. }
  28354. }
  28355. YAMLOMap.tag = 'tag:yaml.org,2002:omap';
  28356. const omap = {
  28357. collection: 'seq',
  28358. identify: value => value instanceof Map,
  28359. nodeClass: YAMLOMap,
  28360. default: false,
  28361. tag: 'tag:yaml.org,2002:omap',
  28362. resolve(seq, onError) {
  28363. const pairs = resolvePairs(seq, onError);
  28364. const seenKeys = [];
  28365. for (const { key } of pairs.items) {
  28366. if (isScalar$1(key)) {
  28367. if (seenKeys.includes(key.value)) {
  28368. onError(`Ordered maps must not include duplicate keys: ${key.value}`);
  28369. }
  28370. else {
  28371. seenKeys.push(key.value);
  28372. }
  28373. }
  28374. }
  28375. return Object.assign(new YAMLOMap(), pairs);
  28376. },
  28377. createNode(schema, iterable, ctx) {
  28378. const pairs = createPairs(schema, iterable, ctx);
  28379. const omap = new YAMLOMap();
  28380. omap.items = pairs.items;
  28381. return omap;
  28382. }
  28383. };
  28384. function boolStringify({ value, source }, ctx) {
  28385. const boolObj = value ? trueTag : falseTag;
  28386. if (source && boolObj.test.test(source))
  28387. return source;
  28388. return value ? ctx.options.trueStr : ctx.options.falseStr;
  28389. }
  28390. const trueTag = {
  28391. identify: value => value === true,
  28392. default: true,
  28393. tag: 'tag:yaml.org,2002:bool',
  28394. test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
  28395. resolve: () => new Scalar(true),
  28396. stringify: boolStringify
  28397. };
  28398. const falseTag = {
  28399. identify: value => value === false,
  28400. default: true,
  28401. tag: 'tag:yaml.org,2002:bool',
  28402. test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
  28403. resolve: () => new Scalar(false),
  28404. stringify: boolStringify
  28405. };
  28406. const floatNaN = {
  28407. identify: value => typeof value === 'number',
  28408. default: true,
  28409. tag: 'tag:yaml.org,2002:float',
  28410. test: /^[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN)$/,
  28411. resolve: (str) => str.slice(-3).toLowerCase() === 'nan'
  28412. ? NaN
  28413. : str[0] === '-'
  28414. ? Number.NEGATIVE_INFINITY
  28415. : Number.POSITIVE_INFINITY,
  28416. stringify: stringifyNumber
  28417. };
  28418. const floatExp = {
  28419. identify: value => typeof value === 'number',
  28420. default: true,
  28421. tag: 'tag:yaml.org,2002:float',
  28422. format: 'EXP',
  28423. test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
  28424. resolve: (str) => parseFloat(str.replace(/_/g, '')),
  28425. stringify(node) {
  28426. const num = Number(node.value);
  28427. return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  28428. }
  28429. };
  28430. const float = {
  28431. identify: value => typeof value === 'number',
  28432. default: true,
  28433. tag: 'tag:yaml.org,2002:float',
  28434. test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
  28435. resolve(str) {
  28436. const node = new Scalar(parseFloat(str.replace(/_/g, '')));
  28437. const dot = str.indexOf('.');
  28438. if (dot !== -1) {
  28439. const f = str.substring(dot + 1).replace(/_/g, '');
  28440. if (f[f.length - 1] === '0')
  28441. node.minFractionDigits = f.length;
  28442. }
  28443. return node;
  28444. },
  28445. stringify: stringifyNumber
  28446. };
  28447. const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
  28448. function intResolve(str, offset, radix, { intAsBigInt }) {
  28449. const sign = str[0];
  28450. if (sign === '-' || sign === '+')
  28451. offset += 1;
  28452. str = str.substring(offset).replace(/_/g, '');
  28453. if (intAsBigInt) {
  28454. switch (radix) {
  28455. case 2:
  28456. str = `0b${str}`;
  28457. break;
  28458. case 8:
  28459. str = `0o${str}`;
  28460. break;
  28461. case 16:
  28462. str = `0x${str}`;
  28463. break;
  28464. }
  28465. const n = BigInt(str);
  28466. return sign === '-' ? BigInt(-1) * n : n;
  28467. }
  28468. const n = parseInt(str, radix);
  28469. return sign === '-' ? -1 * n : n;
  28470. }
  28471. function intStringify(node, radix, prefix) {
  28472. const { value } = node;
  28473. if (intIdentify(value)) {
  28474. const str = value.toString(radix);
  28475. return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
  28476. }
  28477. return stringifyNumber(node);
  28478. }
  28479. const intBin = {
  28480. identify: intIdentify,
  28481. default: true,
  28482. tag: 'tag:yaml.org,2002:int',
  28483. format: 'BIN',
  28484. test: /^[-+]?0b[0-1_]+$/,
  28485. resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
  28486. stringify: node => intStringify(node, 2, '0b')
  28487. };
  28488. const intOct = {
  28489. identify: intIdentify,
  28490. default: true,
  28491. tag: 'tag:yaml.org,2002:int',
  28492. format: 'OCT',
  28493. test: /^[-+]?0[0-7_]+$/,
  28494. resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
  28495. stringify: node => intStringify(node, 8, '0')
  28496. };
  28497. const int = {
  28498. identify: intIdentify,
  28499. default: true,
  28500. tag: 'tag:yaml.org,2002:int',
  28501. test: /^[-+]?[0-9][0-9_]*$/,
  28502. resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
  28503. stringify: stringifyNumber
  28504. };
  28505. const intHex = {
  28506. identify: intIdentify,
  28507. default: true,
  28508. tag: 'tag:yaml.org,2002:int',
  28509. format: 'HEX',
  28510. test: /^[-+]?0x[0-9a-fA-F_]+$/,
  28511. resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
  28512. stringify: node => intStringify(node, 16, '0x')
  28513. };
  28514. class YAMLSet extends YAMLMap {
  28515. constructor(schema) {
  28516. super(schema);
  28517. this.tag = YAMLSet.tag;
  28518. }
  28519. add(key) {
  28520. let pair;
  28521. if (isPair(key))
  28522. pair = key;
  28523. else if (typeof key === 'object' &&
  28524. 'key' in key &&
  28525. 'value' in key &&
  28526. key.value === null)
  28527. pair = new Pair(key.key, null);
  28528. else
  28529. pair = new Pair(key, null);
  28530. const prev = findPair(this.items, pair.key);
  28531. if (!prev)
  28532. this.items.push(pair);
  28533. }
  28534. /**
  28535. * If `keepPair` is `true`, returns the Pair matching `key`.
  28536. * Otherwise, returns the value of that Pair's key.
  28537. */
  28538. get(key, keepPair) {
  28539. const pair = findPair(this.items, key);
  28540. return !keepPair && isPair(pair)
  28541. ? isScalar$1(pair.key)
  28542. ? pair.key.value
  28543. : pair.key
  28544. : pair;
  28545. }
  28546. set(key, value) {
  28547. if (typeof value !== 'boolean')
  28548. throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
  28549. const prev = findPair(this.items, key);
  28550. if (prev && !value) {
  28551. this.items.splice(this.items.indexOf(prev), 1);
  28552. }
  28553. else if (!prev && value) {
  28554. this.items.push(new Pair(key));
  28555. }
  28556. }
  28557. toJSON(_, ctx) {
  28558. return super.toJSON(_, ctx, Set);
  28559. }
  28560. toString(ctx, onComment, onChompKeep) {
  28561. if (!ctx)
  28562. return JSON.stringify(this);
  28563. if (this.hasAllNullValues(true))
  28564. return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
  28565. else
  28566. throw new Error('Set items must all have null values');
  28567. }
  28568. }
  28569. YAMLSet.tag = 'tag:yaml.org,2002:set';
  28570. const set = {
  28571. collection: 'map',
  28572. identify: value => value instanceof Set,
  28573. nodeClass: YAMLSet,
  28574. default: false,
  28575. tag: 'tag:yaml.org,2002:set',
  28576. resolve(map, onError) {
  28577. if (isMap(map)) {
  28578. if (map.hasAllNullValues(true))
  28579. return Object.assign(new YAMLSet(), map);
  28580. else
  28581. onError('Set items must all have null values');
  28582. }
  28583. else
  28584. onError('Expected a mapping for this tag');
  28585. return map;
  28586. },
  28587. createNode(schema, iterable, ctx) {
  28588. const { replacer } = ctx;
  28589. const set = new YAMLSet(schema);
  28590. if (iterable && Symbol.iterator in Object(iterable))
  28591. for (let value of iterable) {
  28592. if (typeof replacer === 'function')
  28593. value = replacer.call(iterable, value, value);
  28594. set.items.push(createPair(value, null, ctx));
  28595. }
  28596. return set;
  28597. }
  28598. };
  28599. /** Internal types handle bigint as number, because TS can't figure it out. */
  28600. function parseSexagesimal(str, asBigInt) {
  28601. const sign = str[0];
  28602. const parts = sign === '-' || sign === '+' ? str.substring(1) : str;
  28603. const num = (n) => asBigInt ? BigInt(n) : Number(n);
  28604. const res = parts
  28605. .replace(/_/g, '')
  28606. .split(':')
  28607. .reduce((res, p) => res * num(60) + num(p), num(0));
  28608. return (sign === '-' ? num(-1) * res : res);
  28609. }
  28610. /**
  28611. * hhhh:mm:ss.sss
  28612. *
  28613. * Internal types handle bigint as number, because TS can't figure it out.
  28614. */
  28615. function stringifySexagesimal(node) {
  28616. let { value } = node;
  28617. let num = (n) => n;
  28618. if (typeof value === 'bigint')
  28619. num = n => BigInt(n);
  28620. else if (isNaN(value) || !isFinite(value))
  28621. return stringifyNumber(node);
  28622. let sign = '';
  28623. if (value < 0) {
  28624. sign = '-';
  28625. value *= num(-1);
  28626. }
  28627. const _60 = num(60);
  28628. const parts = [value % _60]; // seconds, including ms
  28629. if (value < 60) {
  28630. parts.unshift(0); // at least one : is required
  28631. }
  28632. else {
  28633. value = (value - parts[0]) / _60;
  28634. parts.unshift(value % _60); // minutes
  28635. if (value >= 60) {
  28636. value = (value - parts[0]) / _60;
  28637. parts.unshift(value); // hours
  28638. }
  28639. }
  28640. return (sign +
  28641. parts
  28642. .map(n => (n < 10 ? '0' + String(n) : String(n)))
  28643. .join(':')
  28644. .replace(/000000\d*$/, '') // % 60 may introduce error
  28645. );
  28646. }
  28647. const intTime = {
  28648. identify: value => typeof value === 'bigint' || Number.isInteger(value),
  28649. default: true,
  28650. tag: 'tag:yaml.org,2002:int',
  28651. format: 'TIME',
  28652. test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
  28653. resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
  28654. stringify: stringifySexagesimal
  28655. };
  28656. const floatTime = {
  28657. identify: value => typeof value === 'number',
  28658. default: true,
  28659. tag: 'tag:yaml.org,2002:float',
  28660. format: 'TIME',
  28661. test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
  28662. resolve: str => parseSexagesimal(str, false),
  28663. stringify: stringifySexagesimal
  28664. };
  28665. const timestamp = {
  28666. identify: value => value instanceof Date,
  28667. default: true,
  28668. tag: 'tag:yaml.org,2002:timestamp',
  28669. // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
  28670. // may be omitted altogether, resulting in a date format. In such a case, the time part is
  28671. // assumed to be 00:00:00Z (start of day, UTC).
  28672. test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
  28673. '(?:' + // time is optional
  28674. '(?:t|T|[ \\t]+)' + // t | T | whitespace
  28675. '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
  28676. '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
  28677. ')?$'),
  28678. resolve(str) {
  28679. const match = str.match(timestamp.test);
  28680. if (!match)
  28681. throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');
  28682. const [, year, month, day, hour, minute, second] = match.map(Number);
  28683. const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;
  28684. let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
  28685. const tz = match[8];
  28686. if (tz && tz !== 'Z') {
  28687. let d = parseSexagesimal(tz, false);
  28688. if (Math.abs(d) < 30)
  28689. d *= 60;
  28690. date -= 60000 * d;
  28691. }
  28692. return new Date(date);
  28693. },
  28694. stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
  28695. };
  28696. const schema = [
  28697. map,
  28698. seq,
  28699. string,
  28700. nullTag,
  28701. trueTag,
  28702. falseTag,
  28703. intBin,
  28704. intOct,
  28705. int,
  28706. intHex,
  28707. floatNaN,
  28708. floatExp,
  28709. float,
  28710. binary,
  28711. omap,
  28712. pairs,
  28713. set,
  28714. intTime,
  28715. floatTime,
  28716. timestamp
  28717. ];
  28718. const schemas = new Map([
  28719. ['core', schema$2],
  28720. ['failsafe', [map, seq, string]],
  28721. ['json', schema$1],
  28722. ['yaml11', schema],
  28723. ['yaml-1.1', schema]
  28724. ]);
  28725. const tagsByName = {
  28726. binary,
  28727. bool: boolTag,
  28728. float: float$1,
  28729. floatExp: floatExp$1,
  28730. floatNaN: floatNaN$1,
  28731. floatTime,
  28732. int: int$1,
  28733. intHex: intHex$1,
  28734. intOct: intOct$1,
  28735. intTime,
  28736. map,
  28737. null: nullTag,
  28738. omap,
  28739. pairs,
  28740. seq,
  28741. set,
  28742. timestamp
  28743. };
  28744. const coreKnownTags = {
  28745. 'tag:yaml.org,2002:binary': binary,
  28746. 'tag:yaml.org,2002:omap': omap,
  28747. 'tag:yaml.org,2002:pairs': pairs,
  28748. 'tag:yaml.org,2002:set': set,
  28749. 'tag:yaml.org,2002:timestamp': timestamp
  28750. };
  28751. function getTags(customTags, schemaName) {
  28752. let tags = schemas.get(schemaName);
  28753. if (!tags) {
  28754. if (Array.isArray(customTags))
  28755. tags = [];
  28756. else {
  28757. const keys = Array.from(schemas.keys())
  28758. .filter(key => key !== 'yaml11')
  28759. .map(key => JSON.stringify(key))
  28760. .join(', ');
  28761. throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
  28762. }
  28763. }
  28764. if (Array.isArray(customTags)) {
  28765. for (const tag of customTags)
  28766. tags = tags.concat(tag);
  28767. }
  28768. else if (typeof customTags === 'function') {
  28769. tags = customTags(tags.slice());
  28770. }
  28771. return tags.map(tag => {
  28772. if (typeof tag !== 'string')
  28773. return tag;
  28774. const tagObj = tagsByName[tag];
  28775. if (tagObj)
  28776. return tagObj;
  28777. const keys = Object.keys(tagsByName)
  28778. .map(key => JSON.stringify(key))
  28779. .join(', ');
  28780. throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
  28781. });
  28782. }
  28783. const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
  28784. class Schema {
  28785. constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
  28786. this.compat = Array.isArray(compat)
  28787. ? getTags(compat, 'compat')
  28788. : compat
  28789. ? getTags(null, compat)
  28790. : null;
  28791. this.merge = !!merge;
  28792. this.name = (typeof schema === 'string' && schema) || 'core';
  28793. this.knownTags = resolveKnownTags ? coreKnownTags : {};
  28794. this.tags = getTags(customTags, this.name);
  28795. this.toStringOptions = toStringDefaults ?? null;
  28796. Object.defineProperty(this, MAP, { value: map });
  28797. Object.defineProperty(this, SCALAR$1, { value: string });
  28798. Object.defineProperty(this, SEQ, { value: seq });
  28799. // Used by createMap()
  28800. this.sortMapEntries =
  28801. typeof sortMapEntries === 'function'
  28802. ? sortMapEntries
  28803. : sortMapEntries === true
  28804. ? sortMapEntriesByKey
  28805. : null;
  28806. }
  28807. clone() {
  28808. const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
  28809. copy.tags = this.tags.slice();
  28810. return copy;
  28811. }
  28812. }
  28813. function stringifyDocument(doc, options) {
  28814. const lines = [];
  28815. let hasDirectives = options.directives === true;
  28816. if (options.directives !== false && doc.directives) {
  28817. const dir = doc.directives.toString(doc);
  28818. if (dir) {
  28819. lines.push(dir);
  28820. hasDirectives = true;
  28821. }
  28822. else if (doc.directives.docStart)
  28823. hasDirectives = true;
  28824. }
  28825. if (hasDirectives)
  28826. lines.push('---');
  28827. const ctx = createStringifyContext(doc, options);
  28828. const { commentString } = ctx.options;
  28829. if (doc.commentBefore) {
  28830. if (lines.length !== 1)
  28831. lines.unshift('');
  28832. const cs = commentString(doc.commentBefore);
  28833. lines.unshift(indentComment(cs, ''));
  28834. }
  28835. let chompKeep = false;
  28836. let contentComment = null;
  28837. if (doc.contents) {
  28838. if (isNode$1(doc.contents)) {
  28839. if (doc.contents.spaceBefore && hasDirectives)
  28840. lines.push('');
  28841. if (doc.contents.commentBefore) {
  28842. const cs = commentString(doc.contents.commentBefore);
  28843. lines.push(indentComment(cs, ''));
  28844. }
  28845. // top-level block scalars need to be indented if followed by a comment
  28846. ctx.forceBlockIndent = !!doc.comment;
  28847. contentComment = doc.contents.comment;
  28848. }
  28849. const onChompKeep = contentComment ? undefined : () => (chompKeep = true);
  28850. let body = stringify$2(doc.contents, ctx, () => (contentComment = null), onChompKeep);
  28851. if (contentComment)
  28852. body += lineComment(body, '', commentString(contentComment));
  28853. if ((body[0] === '|' || body[0] === '>') &&
  28854. lines[lines.length - 1] === '---') {
  28855. // Top-level block scalars with a preceding doc marker ought to use the
  28856. // same line for their header.
  28857. lines[lines.length - 1] = `--- ${body}`;
  28858. }
  28859. else
  28860. lines.push(body);
  28861. }
  28862. else {
  28863. lines.push(stringify$2(doc.contents, ctx));
  28864. }
  28865. if (doc.directives?.docEnd) {
  28866. if (doc.comment) {
  28867. const cs = commentString(doc.comment);
  28868. if (cs.includes('\n')) {
  28869. lines.push('...');
  28870. lines.push(indentComment(cs, ''));
  28871. }
  28872. else {
  28873. lines.push(`... ${cs}`);
  28874. }
  28875. }
  28876. else {
  28877. lines.push('...');
  28878. }
  28879. }
  28880. else {
  28881. let dc = doc.comment;
  28882. if (dc && chompKeep)
  28883. dc = dc.replace(/^\n+/, '');
  28884. if (dc) {
  28885. if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
  28886. lines.push('');
  28887. lines.push(indentComment(commentString(dc), ''));
  28888. }
  28889. }
  28890. return lines.join('\n') + '\n';
  28891. }
  28892. /**
  28893. * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
  28894. * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
  28895. * 2021 edition: https://tc39.es/ecma262/#sec-json.parse
  28896. *
  28897. * Includes extensions for handling Map and Set objects.
  28898. */
  28899. function applyReviver(reviver, obj, key, val) {
  28900. if (val && typeof val === 'object') {
  28901. if (Array.isArray(val)) {
  28902. for (let i = 0, len = val.length; i < len; ++i) {
  28903. const v0 = val[i];
  28904. const v1 = applyReviver(reviver, val, String(i), v0);
  28905. if (v1 === undefined)
  28906. delete val[i];
  28907. else if (v1 !== v0)
  28908. val[i] = v1;
  28909. }
  28910. }
  28911. else if (val instanceof Map) {
  28912. for (const k of Array.from(val.keys())) {
  28913. const v0 = val.get(k);
  28914. const v1 = applyReviver(reviver, val, k, v0);
  28915. if (v1 === undefined)
  28916. val.delete(k);
  28917. else if (v1 !== v0)
  28918. val.set(k, v1);
  28919. }
  28920. }
  28921. else if (val instanceof Set) {
  28922. for (const v0 of Array.from(val)) {
  28923. const v1 = applyReviver(reviver, val, v0, v0);
  28924. if (v1 === undefined)
  28925. val.delete(v0);
  28926. else if (v1 !== v0) {
  28927. val.delete(v0);
  28928. val.add(v1);
  28929. }
  28930. }
  28931. }
  28932. else {
  28933. for (const [k, v0] of Object.entries(val)) {
  28934. const v1 = applyReviver(reviver, val, k, v0);
  28935. if (v1 === undefined)
  28936. delete val[k];
  28937. else if (v1 !== v0)
  28938. val[k] = v1;
  28939. }
  28940. }
  28941. }
  28942. return reviver.call(obj, key, val);
  28943. }
  28944. class Document {
  28945. constructor(value, replacer, options) {
  28946. /** A comment before this Document */
  28947. this.commentBefore = null;
  28948. /** A comment immediately after this Document */
  28949. this.comment = null;
  28950. /** Errors encountered during parsing. */
  28951. this.errors = [];
  28952. /** Warnings encountered during parsing. */
  28953. this.warnings = [];
  28954. Object.defineProperty(this, NODE_TYPE, { value: DOC });
  28955. let _replacer = null;
  28956. if (typeof replacer === 'function' || Array.isArray(replacer)) {
  28957. _replacer = replacer;
  28958. }
  28959. else if (options === undefined && replacer) {
  28960. options = replacer;
  28961. replacer = undefined;
  28962. }
  28963. const opt = Object.assign({
  28964. intAsBigInt: false,
  28965. keepSourceTokens: false,
  28966. logLevel: 'warn',
  28967. prettyErrors: true,
  28968. strict: true,
  28969. uniqueKeys: true,
  28970. version: '1.2'
  28971. }, options);
  28972. this.options = opt;
  28973. let { version } = opt;
  28974. if (options?._directives) {
  28975. this.directives = options._directives.atDocument();
  28976. if (this.directives.yaml.explicit)
  28977. version = this.directives.yaml.version;
  28978. }
  28979. else
  28980. this.directives = new Directives({ version });
  28981. this.setSchema(version, options);
  28982. if (value === undefined)
  28983. this.contents = null;
  28984. else {
  28985. this.contents = this.createNode(value, _replacer, options);
  28986. }
  28987. }
  28988. /**
  28989. * Create a deep copy of this Document and its contents.
  28990. *
  28991. * Custom Node values that inherit from `Object` still refer to their original instances.
  28992. */
  28993. clone() {
  28994. const copy = Object.create(Document.prototype, {
  28995. [NODE_TYPE]: { value: DOC }
  28996. });
  28997. copy.commentBefore = this.commentBefore;
  28998. copy.comment = this.comment;
  28999. copy.errors = this.errors.slice();
  29000. copy.warnings = this.warnings.slice();
  29001. copy.options = Object.assign({}, this.options);
  29002. if (this.directives)
  29003. copy.directives = this.directives.clone();
  29004. copy.schema = this.schema.clone();
  29005. copy.contents = isNode$1(this.contents)
  29006. ? this.contents.clone(copy.schema)
  29007. : this.contents;
  29008. if (this.range)
  29009. copy.range = this.range.slice();
  29010. return copy;
  29011. }
  29012. /** Adds a value to the document. */
  29013. add(value) {
  29014. if (assertCollection(this.contents))
  29015. this.contents.add(value);
  29016. }
  29017. /** Adds a value to the document. */
  29018. addIn(path, value) {
  29019. if (assertCollection(this.contents))
  29020. this.contents.addIn(path, value);
  29021. }
  29022. /**
  29023. * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
  29024. *
  29025. * If `node` already has an anchor, `name` is ignored.
  29026. * Otherwise, the `node.anchor` value will be set to `name`,
  29027. * or if an anchor with that name is already present in the document,
  29028. * `name` will be used as a prefix for a new unique anchor.
  29029. * If `name` is undefined, the generated anchor will use 'a' as a prefix.
  29030. */
  29031. createAlias(node, name) {
  29032. if (!node.anchor) {
  29033. const prev = anchorNames(this);
  29034. node.anchor =
  29035. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  29036. !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;
  29037. }
  29038. return new Alias(node.anchor);
  29039. }
  29040. createNode(value, replacer, options) {
  29041. let _replacer = undefined;
  29042. if (typeof replacer === 'function') {
  29043. value = replacer.call({ '': value }, '', value);
  29044. _replacer = replacer;
  29045. }
  29046. else if (Array.isArray(replacer)) {
  29047. const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;
  29048. const asStr = replacer.filter(keyToStr).map(String);
  29049. if (asStr.length > 0)
  29050. replacer = replacer.concat(asStr);
  29051. _replacer = replacer;
  29052. }
  29053. else if (options === undefined && replacer) {
  29054. options = replacer;
  29055. replacer = undefined;
  29056. }
  29057. const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
  29058. const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this,
  29059. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  29060. anchorPrefix || 'a');
  29061. const ctx = {
  29062. aliasDuplicateObjects: aliasDuplicateObjects ?? true,
  29063. keepUndefined: keepUndefined ?? false,
  29064. onAnchor,
  29065. onTagObj,
  29066. replacer: _replacer,
  29067. schema: this.schema,
  29068. sourceObjects
  29069. };
  29070. const node = createNode(value, tag, ctx);
  29071. if (flow && isCollection$1(node))
  29072. node.flow = true;
  29073. setAnchors();
  29074. return node;
  29075. }
  29076. /**
  29077. * Convert a key and a value into a `Pair` using the current schema,
  29078. * recursively wrapping all values as `Scalar` or `Collection` nodes.
  29079. */
  29080. createPair(key, value, options = {}) {
  29081. const k = this.createNode(key, null, options);
  29082. const v = this.createNode(value, null, options);
  29083. return new Pair(k, v);
  29084. }
  29085. /**
  29086. * Removes a value from the document.
  29087. * @returns `true` if the item was found and removed.
  29088. */
  29089. delete(key) {
  29090. return assertCollection(this.contents) ? this.contents.delete(key) : false;
  29091. }
  29092. /**
  29093. * Removes a value from the document.
  29094. * @returns `true` if the item was found and removed.
  29095. */
  29096. deleteIn(path) {
  29097. if (isEmptyPath(path)) {
  29098. if (this.contents == null)
  29099. return false;
  29100. this.contents = null;
  29101. return true;
  29102. }
  29103. return assertCollection(this.contents)
  29104. ? this.contents.deleteIn(path)
  29105. : false;
  29106. }
  29107. /**
  29108. * Returns item at `key`, or `undefined` if not found. By default unwraps
  29109. * scalar values from their surrounding node; to disable set `keepScalar` to
  29110. * `true` (collections are always returned intact).
  29111. */
  29112. get(key, keepScalar) {
  29113. return isCollection$1(this.contents)
  29114. ? this.contents.get(key, keepScalar)
  29115. : undefined;
  29116. }
  29117. /**
  29118. * Returns item at `path`, or `undefined` if not found. By default unwraps
  29119. * scalar values from their surrounding node; to disable set `keepScalar` to
  29120. * `true` (collections are always returned intact).
  29121. */
  29122. getIn(path, keepScalar) {
  29123. if (isEmptyPath(path))
  29124. return !keepScalar && isScalar$1(this.contents)
  29125. ? this.contents.value
  29126. : this.contents;
  29127. return isCollection$1(this.contents)
  29128. ? this.contents.getIn(path, keepScalar)
  29129. : undefined;
  29130. }
  29131. /**
  29132. * Checks if the document includes a value with the key `key`.
  29133. */
  29134. has(key) {
  29135. return isCollection$1(this.contents) ? this.contents.has(key) : false;
  29136. }
  29137. /**
  29138. * Checks if the document includes a value at `path`.
  29139. */
  29140. hasIn(path) {
  29141. if (isEmptyPath(path))
  29142. return this.contents !== undefined;
  29143. return isCollection$1(this.contents) ? this.contents.hasIn(path) : false;
  29144. }
  29145. /**
  29146. * Sets a value in this document. For `!!set`, `value` needs to be a
  29147. * boolean to add/remove the item from the set.
  29148. */
  29149. set(key, value) {
  29150. if (this.contents == null) {
  29151. this.contents = collectionFromPath(this.schema, [key], value);
  29152. }
  29153. else if (assertCollection(this.contents)) {
  29154. this.contents.set(key, value);
  29155. }
  29156. }
  29157. /**
  29158. * Sets a value in this document. For `!!set`, `value` needs to be a
  29159. * boolean to add/remove the item from the set.
  29160. */
  29161. setIn(path, value) {
  29162. if (isEmptyPath(path))
  29163. this.contents = value;
  29164. else if (this.contents == null) {
  29165. this.contents = collectionFromPath(this.schema, Array.from(path), value);
  29166. }
  29167. else if (assertCollection(this.contents)) {
  29168. this.contents.setIn(path, value);
  29169. }
  29170. }
  29171. /**
  29172. * Change the YAML version and schema used by the document.
  29173. * A `null` version disables support for directives, explicit tags, anchors, and aliases.
  29174. * It also requires the `schema` option to be given as a `Schema` instance value.
  29175. *
  29176. * Overrides all previously set schema options.
  29177. */
  29178. setSchema(version, options = {}) {
  29179. if (typeof version === 'number')
  29180. version = String(version);
  29181. let opt;
  29182. switch (version) {
  29183. case '1.1':
  29184. if (this.directives)
  29185. this.directives.yaml.version = '1.1';
  29186. else
  29187. this.directives = new Directives({ version: '1.1' });
  29188. opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' };
  29189. break;
  29190. case '1.2':
  29191. case 'next':
  29192. if (this.directives)
  29193. this.directives.yaml.version = version;
  29194. else
  29195. this.directives = new Directives({ version });
  29196. opt = { merge: false, resolveKnownTags: true, schema: 'core' };
  29197. break;
  29198. case null:
  29199. if (this.directives)
  29200. delete this.directives;
  29201. opt = null;
  29202. break;
  29203. default: {
  29204. const sv = JSON.stringify(version);
  29205. throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
  29206. }
  29207. }
  29208. // Not using `instanceof Schema` to allow for duck typing
  29209. if (options.schema instanceof Object)
  29210. this.schema = options.schema;
  29211. else if (opt)
  29212. this.schema = new Schema(Object.assign(opt, options));
  29213. else
  29214. throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
  29215. }
  29216. // json & jsonArg are only used from toJSON()
  29217. toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
  29218. const ctx = {
  29219. anchors: new Map(),
  29220. doc: this,
  29221. keep: !json,
  29222. mapAsMap: mapAsMap === true,
  29223. mapKeyWarned: false,
  29224. maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100,
  29225. stringify: stringify$2
  29226. };
  29227. const res = toJS(this.contents, jsonArg ?? '', ctx);
  29228. if (typeof onAnchor === 'function')
  29229. for (const { count, res } of ctx.anchors.values())
  29230. onAnchor(res, count);
  29231. return typeof reviver === 'function'
  29232. ? applyReviver(reviver, { '': res }, '', res)
  29233. : res;
  29234. }
  29235. /**
  29236. * A JSON representation of the document `contents`.
  29237. *
  29238. * @param jsonArg Used by `JSON.stringify` to indicate the array index or
  29239. * property name.
  29240. */
  29241. toJSON(jsonArg, onAnchor) {
  29242. return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
  29243. }
  29244. /** A YAML representation of the document. */
  29245. toString(options = {}) {
  29246. if (this.errors.length > 0)
  29247. throw new Error('Document with errors cannot be stringified');
  29248. if ('indent' in options &&
  29249. (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
  29250. const s = JSON.stringify(options.indent);
  29251. throw new Error(`"indent" option must be a positive integer, not ${s}`);
  29252. }
  29253. return stringifyDocument(this, options);
  29254. }
  29255. }
  29256. function assertCollection(contents) {
  29257. if (isCollection$1(contents))
  29258. return true;
  29259. throw new Error('Expected a YAML collection as document contents');
  29260. }
  29261. class YAMLError extends Error {
  29262. constructor(name, pos, code, message) {
  29263. super();
  29264. this.name = name;
  29265. this.code = code;
  29266. this.message = message;
  29267. this.pos = pos;
  29268. }
  29269. }
  29270. class YAMLParseError extends YAMLError {
  29271. constructor(pos, code, message) {
  29272. super('YAMLParseError', pos, code, message);
  29273. }
  29274. }
  29275. class YAMLWarning extends YAMLError {
  29276. constructor(pos, code, message) {
  29277. super('YAMLWarning', pos, code, message);
  29278. }
  29279. }
  29280. const prettifyError = (src, lc) => (error) => {
  29281. if (error.pos[0] === -1)
  29282. return;
  29283. error.linePos = error.pos.map(pos => lc.linePos(pos));
  29284. const { line, col } = error.linePos[0];
  29285. error.message += ` at line ${line}, column ${col}`;
  29286. let ci = col - 1;
  29287. let lineStr = src
  29288. .substring(lc.lineStarts[line - 1], lc.lineStarts[line])
  29289. .replace(/[\n\r]+$/, '');
  29290. // Trim to max 80 chars, keeping col position near the middle
  29291. if (ci >= 60 && lineStr.length > 80) {
  29292. const trimStart = Math.min(ci - 39, lineStr.length - 79);
  29293. lineStr = '…' + lineStr.substring(trimStart);
  29294. ci -= trimStart - 1;
  29295. }
  29296. if (lineStr.length > 80)
  29297. lineStr = lineStr.substring(0, 79) + '…';
  29298. // Include previous line in context if pointing at line start
  29299. if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
  29300. // Regexp won't match if start is trimmed
  29301. let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
  29302. if (prev.length > 80)
  29303. prev = prev.substring(0, 79) + '…\n';
  29304. lineStr = prev + lineStr;
  29305. }
  29306. if (/[^ ]/.test(lineStr)) {
  29307. let count = 1;
  29308. const end = error.linePos[1];
  29309. if (end && end.line === line && end.col > col) {
  29310. count = Math.min(end.col - col, 80 - ci);
  29311. }
  29312. const pointer = ' '.repeat(ci) + '^'.repeat(count);
  29313. error.message += `:\n\n${lineStr}\n${pointer}\n`;
  29314. }
  29315. };
  29316. function resolveProps(tokens, { flow, indicator, next, offset, onError, startOnNewline }) {
  29317. let spaceBefore = false;
  29318. let atNewline = startOnNewline;
  29319. let hasSpace = startOnNewline;
  29320. let comment = '';
  29321. let commentSep = '';
  29322. let hasNewline = false;
  29323. let hasNewlineAfterProp = false;
  29324. let reqSpace = false;
  29325. let anchor = null;
  29326. let tag = null;
  29327. let comma = null;
  29328. let found = null;
  29329. let start = null;
  29330. for (const token of tokens) {
  29331. if (reqSpace) {
  29332. if (token.type !== 'space' &&
  29333. token.type !== 'newline' &&
  29334. token.type !== 'comma')
  29335. onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
  29336. reqSpace = false;
  29337. }
  29338. switch (token.type) {
  29339. case 'space':
  29340. // At the doc level, tabs at line start may be parsed
  29341. // as leading white space rather than indentation.
  29342. // In a flow collection, only the parser handles indent.
  29343. if (!flow &&
  29344. atNewline &&
  29345. indicator !== 'doc-start' &&
  29346. token.source[0] === '\t')
  29347. onError(token, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
  29348. hasSpace = true;
  29349. break;
  29350. case 'comment': {
  29351. if (!hasSpace)
  29352. onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
  29353. const cb = token.source.substring(1) || ' ';
  29354. if (!comment)
  29355. comment = cb;
  29356. else
  29357. comment += commentSep + cb;
  29358. commentSep = '';
  29359. atNewline = false;
  29360. break;
  29361. }
  29362. case 'newline':
  29363. if (atNewline) {
  29364. if (comment)
  29365. comment += token.source;
  29366. else
  29367. spaceBefore = true;
  29368. }
  29369. else
  29370. commentSep += token.source;
  29371. atNewline = true;
  29372. hasNewline = true;
  29373. if (anchor || tag)
  29374. hasNewlineAfterProp = true;
  29375. hasSpace = true;
  29376. break;
  29377. case 'anchor':
  29378. if (anchor)
  29379. onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');
  29380. if (token.source.endsWith(':'))
  29381. onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);
  29382. anchor = token;
  29383. if (start === null)
  29384. start = token.offset;
  29385. atNewline = false;
  29386. hasSpace = false;
  29387. reqSpace = true;
  29388. break;
  29389. case 'tag': {
  29390. if (tag)
  29391. onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');
  29392. tag = token;
  29393. if (start === null)
  29394. start = token.offset;
  29395. atNewline = false;
  29396. hasSpace = false;
  29397. reqSpace = true;
  29398. break;
  29399. }
  29400. case indicator:
  29401. // Could here handle preceding comments differently
  29402. if (anchor || tag)
  29403. onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);
  29404. if (found)
  29405. onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);
  29406. found = token;
  29407. atNewline = false;
  29408. hasSpace = false;
  29409. break;
  29410. case 'comma':
  29411. if (flow) {
  29412. if (comma)
  29413. onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);
  29414. comma = token;
  29415. atNewline = false;
  29416. hasSpace = false;
  29417. break;
  29418. }
  29419. // else fallthrough
  29420. default:
  29421. onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);
  29422. atNewline = false;
  29423. hasSpace = false;
  29424. }
  29425. }
  29426. const last = tokens[tokens.length - 1];
  29427. const end = last ? last.offset + last.source.length : offset;
  29428. if (reqSpace &&
  29429. next &&
  29430. next.type !== 'space' &&
  29431. next.type !== 'newline' &&
  29432. next.type !== 'comma' &&
  29433. (next.type !== 'scalar' || next.source !== ''))
  29434. onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
  29435. return {
  29436. comma,
  29437. found,
  29438. spaceBefore,
  29439. comment,
  29440. hasNewline,
  29441. hasNewlineAfterProp,
  29442. anchor,
  29443. tag,
  29444. end,
  29445. start: start ?? end
  29446. };
  29447. }
  29448. function containsNewline(key) {
  29449. if (!key)
  29450. return null;
  29451. switch (key.type) {
  29452. case 'alias':
  29453. case 'scalar':
  29454. case 'double-quoted-scalar':
  29455. case 'single-quoted-scalar':
  29456. if (key.source.includes('\n'))
  29457. return true;
  29458. if (key.end)
  29459. for (const st of key.end)
  29460. if (st.type === 'newline')
  29461. return true;
  29462. return false;
  29463. case 'flow-collection':
  29464. for (const it of key.items) {
  29465. for (const st of it.start)
  29466. if (st.type === 'newline')
  29467. return true;
  29468. if (it.sep)
  29469. for (const st of it.sep)
  29470. if (st.type === 'newline')
  29471. return true;
  29472. if (containsNewline(it.key) || containsNewline(it.value))
  29473. return true;
  29474. }
  29475. return false;
  29476. default:
  29477. return true;
  29478. }
  29479. }
  29480. function flowIndentCheck(indent, fc, onError) {
  29481. if (fc?.type === 'flow-collection') {
  29482. const end = fc.end[0];
  29483. if (end.indent === indent &&
  29484. (end.source === ']' || end.source === '}') &&
  29485. containsNewline(fc)) {
  29486. const msg = 'Flow end indicator should be more indented than parent';
  29487. onError(end, 'BAD_INDENT', msg, true);
  29488. }
  29489. }
  29490. }
  29491. function mapIncludes(ctx, items, search) {
  29492. const { uniqueKeys } = ctx.options;
  29493. if (uniqueKeys === false)
  29494. return false;
  29495. const isEqual = typeof uniqueKeys === 'function'
  29496. ? uniqueKeys
  29497. : (a, b) => a === b ||
  29498. (isScalar$1(a) &&
  29499. isScalar$1(b) &&
  29500. a.value === b.value &&
  29501. !(a.value === '<<' && ctx.schema.merge));
  29502. return items.some(pair => isEqual(pair.key, search));
  29503. }
  29504. const startColMsg = 'All mapping items must start at the same column';
  29505. function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError) {
  29506. const map = new YAMLMap(ctx.schema);
  29507. if (ctx.atRoot)
  29508. ctx.atRoot = false;
  29509. let offset = bm.offset;
  29510. for (const collItem of bm.items) {
  29511. const { start, key, sep, value } = collItem;
  29512. // key properties
  29513. const keyProps = resolveProps(start, {
  29514. indicator: 'explicit-key-ind',
  29515. next: key ?? sep?.[0],
  29516. offset,
  29517. onError,
  29518. startOnNewline: true
  29519. });
  29520. const implicitKey = !keyProps.found;
  29521. if (implicitKey) {
  29522. if (key) {
  29523. if (key.type === 'block-seq')
  29524. onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');
  29525. else if ('indent' in key && key.indent !== bm.indent)
  29526. onError(offset, 'BAD_INDENT', startColMsg);
  29527. }
  29528. if (!keyProps.anchor && !keyProps.tag && !sep) {
  29529. // TODO: assert being at last item?
  29530. if (keyProps.comment) {
  29531. if (map.comment)
  29532. map.comment += '\n' + keyProps.comment;
  29533. else
  29534. map.comment = keyProps.comment;
  29535. }
  29536. continue;
  29537. }
  29538. if (keyProps.hasNewlineAfterProp || containsNewline(key)) {
  29539. onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');
  29540. }
  29541. }
  29542. else if (keyProps.found?.indent !== bm.indent) {
  29543. onError(offset, 'BAD_INDENT', startColMsg);
  29544. }
  29545. // key value
  29546. const keyStart = keyProps.end;
  29547. const keyNode = key
  29548. ? composeNode(ctx, key, keyProps, onError)
  29549. : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
  29550. if (ctx.schema.compat)
  29551. flowIndentCheck(bm.indent, key, onError);
  29552. if (mapIncludes(ctx, map.items, keyNode))
  29553. onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
  29554. // value properties
  29555. const valueProps = resolveProps(sep ?? [], {
  29556. indicator: 'map-value-ind',
  29557. next: value,
  29558. offset: keyNode.range[2],
  29559. onError,
  29560. startOnNewline: !key || key.type === 'block-scalar'
  29561. });
  29562. offset = valueProps.end;
  29563. if (valueProps.found) {
  29564. if (implicitKey) {
  29565. if (value?.type === 'block-map' && !valueProps.hasNewline)
  29566. onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');
  29567. if (ctx.options.strict &&
  29568. keyProps.start < valueProps.found.offset - 1024)
  29569. onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');
  29570. }
  29571. // value value
  29572. const valueNode = value
  29573. ? composeNode(ctx, value, valueProps, onError)
  29574. : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
  29575. if (ctx.schema.compat)
  29576. flowIndentCheck(bm.indent, value, onError);
  29577. offset = valueNode.range[2];
  29578. const pair = new Pair(keyNode, valueNode);
  29579. if (ctx.options.keepSourceTokens)
  29580. pair.srcToken = collItem;
  29581. map.items.push(pair);
  29582. }
  29583. else {
  29584. // key with no value
  29585. if (implicitKey)
  29586. onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');
  29587. if (valueProps.comment) {
  29588. if (keyNode.comment)
  29589. keyNode.comment += '\n' + valueProps.comment;
  29590. else
  29591. keyNode.comment = valueProps.comment;
  29592. }
  29593. const pair = new Pair(keyNode);
  29594. if (ctx.options.keepSourceTokens)
  29595. pair.srcToken = collItem;
  29596. map.items.push(pair);
  29597. }
  29598. }
  29599. map.range = [bm.offset, offset, offset];
  29600. return map;
  29601. }
  29602. function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError) {
  29603. const seq = new YAMLSeq(ctx.schema);
  29604. if (ctx.atRoot)
  29605. ctx.atRoot = false;
  29606. let offset = bs.offset;
  29607. for (const { start, value } of bs.items) {
  29608. const props = resolveProps(start, {
  29609. indicator: 'seq-item-ind',
  29610. next: value,
  29611. offset,
  29612. onError,
  29613. startOnNewline: true
  29614. });
  29615. offset = props.end;
  29616. if (!props.found) {
  29617. if (props.anchor || props.tag || value) {
  29618. if (value && value.type === 'block-seq')
  29619. onError(offset, 'BAD_INDENT', 'All sequence items must start at the same column');
  29620. else
  29621. onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');
  29622. }
  29623. else {
  29624. // TODO: assert being at last item?
  29625. if (props.comment)
  29626. seq.comment = props.comment;
  29627. continue;
  29628. }
  29629. }
  29630. const node = value
  29631. ? composeNode(ctx, value, props, onError)
  29632. : composeEmptyNode(ctx, offset, start, null, props, onError);
  29633. if (ctx.schema.compat)
  29634. flowIndentCheck(bs.indent, value, onError);
  29635. offset = node.range[2];
  29636. seq.items.push(node);
  29637. }
  29638. seq.range = [bs.offset, offset, offset];
  29639. return seq;
  29640. }
  29641. function resolveEnd(end, offset, reqSpace, onError) {
  29642. let comment = '';
  29643. if (end) {
  29644. let hasSpace = false;
  29645. let sep = '';
  29646. for (const token of end) {
  29647. const { source, type } = token;
  29648. switch (type) {
  29649. case 'space':
  29650. hasSpace = true;
  29651. break;
  29652. case 'comment': {
  29653. if (reqSpace && !hasSpace)
  29654. onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
  29655. const cb = source.substring(1) || ' ';
  29656. if (!comment)
  29657. comment = cb;
  29658. else
  29659. comment += sep + cb;
  29660. sep = '';
  29661. break;
  29662. }
  29663. case 'newline':
  29664. if (comment)
  29665. sep += source;
  29666. hasSpace = true;
  29667. break;
  29668. default:
  29669. onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);
  29670. }
  29671. offset += source.length;
  29672. }
  29673. }
  29674. return { comment, offset };
  29675. }
  29676. const blockMsg = 'Block collections are not allowed within flow collections';
  29677. const isBlock$1 = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
  29678. function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError) {
  29679. const isMap = fc.start.source === '{';
  29680. const fcName = isMap ? 'flow map' : 'flow sequence';
  29681. const coll = isMap
  29682. ? new YAMLMap(ctx.schema)
  29683. : new YAMLSeq(ctx.schema);
  29684. coll.flow = true;
  29685. const atRoot = ctx.atRoot;
  29686. if (atRoot)
  29687. ctx.atRoot = false;
  29688. let offset = fc.offset + fc.start.source.length;
  29689. for (let i = 0; i < fc.items.length; ++i) {
  29690. const collItem = fc.items[i];
  29691. const { start, key, sep, value } = collItem;
  29692. const props = resolveProps(start, {
  29693. flow: fcName,
  29694. indicator: 'explicit-key-ind',
  29695. next: key ?? sep?.[0],
  29696. offset,
  29697. onError,
  29698. startOnNewline: false
  29699. });
  29700. if (!props.found) {
  29701. if (!props.anchor && !props.tag && !sep && !value) {
  29702. if (i === 0 && props.comma)
  29703. onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
  29704. else if (i < fc.items.length - 1)
  29705. onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);
  29706. if (props.comment) {
  29707. if (coll.comment)
  29708. coll.comment += '\n' + props.comment;
  29709. else
  29710. coll.comment = props.comment;
  29711. }
  29712. offset = props.end;
  29713. continue;
  29714. }
  29715. if (!isMap && ctx.options.strict && containsNewline(key))
  29716. onError(key, // checked by containsNewline()
  29717. 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
  29718. }
  29719. if (i === 0) {
  29720. if (props.comma)
  29721. onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
  29722. }
  29723. else {
  29724. if (!props.comma)
  29725. onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);
  29726. if (props.comment) {
  29727. let prevItemComment = '';
  29728. loop: for (const st of start) {
  29729. switch (st.type) {
  29730. case 'comma':
  29731. case 'space':
  29732. break;
  29733. case 'comment':
  29734. prevItemComment = st.source.substring(1);
  29735. break loop;
  29736. default:
  29737. break loop;
  29738. }
  29739. }
  29740. if (prevItemComment) {
  29741. let prev = coll.items[coll.items.length - 1];
  29742. if (isPair(prev))
  29743. prev = prev.value ?? prev.key;
  29744. if (prev.comment)
  29745. prev.comment += '\n' + prevItemComment;
  29746. else
  29747. prev.comment = prevItemComment;
  29748. props.comment = props.comment.substring(prevItemComment.length + 1);
  29749. }
  29750. }
  29751. }
  29752. if (!isMap && !sep && !props.found) {
  29753. // item is a value in a seq
  29754. // → key & sep are empty, start does not include ? or :
  29755. const valueNode = value
  29756. ? composeNode(ctx, value, props, onError)
  29757. : composeEmptyNode(ctx, props.end, sep, null, props, onError);
  29758. coll.items.push(valueNode);
  29759. offset = valueNode.range[2];
  29760. if (isBlock$1(value))
  29761. onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
  29762. }
  29763. else {
  29764. // item is a key+value pair
  29765. // key value
  29766. const keyStart = props.end;
  29767. const keyNode = key
  29768. ? composeNode(ctx, key, props, onError)
  29769. : composeEmptyNode(ctx, keyStart, start, null, props, onError);
  29770. if (isBlock$1(key))
  29771. onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);
  29772. // value properties
  29773. const valueProps = resolveProps(sep ?? [], {
  29774. flow: fcName,
  29775. indicator: 'map-value-ind',
  29776. next: value,
  29777. offset: keyNode.range[2],
  29778. onError,
  29779. startOnNewline: false
  29780. });
  29781. if (valueProps.found) {
  29782. if (!isMap && !props.found && ctx.options.strict) {
  29783. if (sep)
  29784. for (const st of sep) {
  29785. if (st === valueProps.found)
  29786. break;
  29787. if (st.type === 'newline') {
  29788. onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
  29789. break;
  29790. }
  29791. }
  29792. if (props.start < valueProps.found.offset - 1024)
  29793. onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');
  29794. }
  29795. }
  29796. else if (value) {
  29797. if ('source' in value && value.source && value.source[0] === ':')
  29798. onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);
  29799. else
  29800. onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);
  29801. }
  29802. // value value
  29803. const valueNode = value
  29804. ? composeNode(ctx, value, valueProps, onError)
  29805. : valueProps.found
  29806. ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)
  29807. : null;
  29808. if (valueNode) {
  29809. if (isBlock$1(value))
  29810. onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
  29811. }
  29812. else if (valueProps.comment) {
  29813. if (keyNode.comment)
  29814. keyNode.comment += '\n' + valueProps.comment;
  29815. else
  29816. keyNode.comment = valueProps.comment;
  29817. }
  29818. const pair = new Pair(keyNode, valueNode);
  29819. if (ctx.options.keepSourceTokens)
  29820. pair.srcToken = collItem;
  29821. if (isMap) {
  29822. const map = coll;
  29823. if (mapIncludes(ctx, map.items, keyNode))
  29824. onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
  29825. map.items.push(pair);
  29826. }
  29827. else {
  29828. const map = new YAMLMap(ctx.schema);
  29829. map.flow = true;
  29830. map.items.push(pair);
  29831. coll.items.push(map);
  29832. }
  29833. offset = valueNode ? valueNode.range[2] : valueProps.end;
  29834. }
  29835. }
  29836. const expectedEnd = isMap ? '}' : ']';
  29837. const [ce, ...ee] = fc.end;
  29838. let cePos = offset;
  29839. if (ce && ce.source === expectedEnd)
  29840. cePos = ce.offset + ce.source.length;
  29841. else {
  29842. const name = fcName[0].toUpperCase() + fcName.substring(1);
  29843. const msg = atRoot
  29844. ? `${name} must end with a ${expectedEnd}`
  29845. : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
  29846. onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);
  29847. if (ce && ce.source.length !== 1)
  29848. ee.unshift(ce);
  29849. }
  29850. if (ee.length > 0) {
  29851. const end = resolveEnd(ee, cePos, ctx.options.strict, onError);
  29852. if (end.comment) {
  29853. if (coll.comment)
  29854. coll.comment += '\n' + end.comment;
  29855. else
  29856. coll.comment = end.comment;
  29857. }
  29858. coll.range = [fc.offset, cePos, end.offset];
  29859. }
  29860. else {
  29861. coll.range = [fc.offset, cePos, cePos];
  29862. }
  29863. return coll;
  29864. }
  29865. function composeCollection(CN, ctx, token, tagToken, onError) {
  29866. let coll;
  29867. switch (token.type) {
  29868. case 'block-map': {
  29869. coll = resolveBlockMap(CN, ctx, token, onError);
  29870. break;
  29871. }
  29872. case 'block-seq': {
  29873. coll = resolveBlockSeq(CN, ctx, token, onError);
  29874. break;
  29875. }
  29876. case 'flow-collection': {
  29877. coll = resolveFlowCollection(CN, ctx, token, onError);
  29878. break;
  29879. }
  29880. }
  29881. if (!tagToken)
  29882. return coll;
  29883. const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
  29884. if (!tagName)
  29885. return coll;
  29886. // Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841
  29887. const Coll = coll.constructor;
  29888. if (tagName === '!' || tagName === Coll.tagName) {
  29889. coll.tag = Coll.tagName;
  29890. return coll;
  29891. }
  29892. const expType = isMap(coll) ? 'map' : 'seq';
  29893. let tag = ctx.schema.tags.find(t => t.collection === expType && t.tag === tagName);
  29894. if (!tag) {
  29895. const kt = ctx.schema.knownTags[tagName];
  29896. if (kt && kt.collection === expType) {
  29897. ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
  29898. tag = kt;
  29899. }
  29900. else {
  29901. onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
  29902. coll.tag = tagName;
  29903. return coll;
  29904. }
  29905. }
  29906. const res = tag.resolve(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options);
  29907. const node = isNode$1(res)
  29908. ? res
  29909. : new Scalar(res);
  29910. node.range = coll.range;
  29911. node.tag = tagName;
  29912. if (tag?.format)
  29913. node.format = tag.format;
  29914. return node;
  29915. }
  29916. function resolveBlockScalar(scalar, strict, onError) {
  29917. const start = scalar.offset;
  29918. const header = parseBlockScalarHeader(scalar, strict, onError);
  29919. if (!header)
  29920. return { value: '', type: null, comment: '', range: [start, start, start] };
  29921. const type = header.mode === '>' ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;
  29922. const lines = scalar.source ? splitLines(scalar.source) : [];
  29923. // determine the end of content & start of chomping
  29924. let chompStart = lines.length;
  29925. for (let i = lines.length - 1; i >= 0; --i) {
  29926. const content = lines[i][1];
  29927. if (content === '' || content === '\r')
  29928. chompStart = i;
  29929. else
  29930. break;
  29931. }
  29932. // shortcut for empty contents
  29933. if (chompStart === 0) {
  29934. const value = header.chomp === '+' && lines.length > 0
  29935. ? '\n'.repeat(Math.max(1, lines.length - 1))
  29936. : '';
  29937. let end = start + header.length;
  29938. if (scalar.source)
  29939. end += scalar.source.length;
  29940. return { value, type, comment: header.comment, range: [start, end, end] };
  29941. }
  29942. // find the indentation level to trim from start
  29943. let trimIndent = scalar.indent + header.indent;
  29944. let offset = scalar.offset + header.length;
  29945. let contentStart = 0;
  29946. for (let i = 0; i < chompStart; ++i) {
  29947. const [indent, content] = lines[i];
  29948. if (content === '' || content === '\r') {
  29949. if (header.indent === 0 && indent.length > trimIndent)
  29950. trimIndent = indent.length;
  29951. }
  29952. else {
  29953. if (indent.length < trimIndent) {
  29954. const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
  29955. onError(offset + indent.length, 'MISSING_CHAR', message);
  29956. }
  29957. if (header.indent === 0)
  29958. trimIndent = indent.length;
  29959. contentStart = i;
  29960. break;
  29961. }
  29962. offset += indent.length + content.length + 1;
  29963. }
  29964. // include trailing more-indented empty lines in content
  29965. for (let i = lines.length - 1; i >= chompStart; --i) {
  29966. if (lines[i][0].length > trimIndent)
  29967. chompStart = i + 1;
  29968. }
  29969. let value = '';
  29970. let sep = '';
  29971. let prevMoreIndented = false;
  29972. // leading whitespace is kept intact
  29973. for (let i = 0; i < contentStart; ++i)
  29974. value += lines[i][0].slice(trimIndent) + '\n';
  29975. for (let i = contentStart; i < chompStart; ++i) {
  29976. let [indent, content] = lines[i];
  29977. offset += indent.length + content.length + 1;
  29978. const crlf = content[content.length - 1] === '\r';
  29979. if (crlf)
  29980. content = content.slice(0, -1);
  29981. /* istanbul ignore if already caught in lexer */
  29982. if (content && indent.length < trimIndent) {
  29983. const src = header.indent
  29984. ? 'explicit indentation indicator'
  29985. : 'first line';
  29986. const message = `Block scalar lines must not be less indented than their ${src}`;
  29987. onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);
  29988. indent = '';
  29989. }
  29990. if (type === Scalar.BLOCK_LITERAL) {
  29991. value += sep + indent.slice(trimIndent) + content;
  29992. sep = '\n';
  29993. }
  29994. else if (indent.length > trimIndent || content[0] === '\t') {
  29995. // more-indented content within a folded block
  29996. if (sep === ' ')
  29997. sep = '\n';
  29998. else if (!prevMoreIndented && sep === '\n')
  29999. sep = '\n\n';
  30000. value += sep + indent.slice(trimIndent) + content;
  30001. sep = '\n';
  30002. prevMoreIndented = true;
  30003. }
  30004. else if (content === '') {
  30005. // empty line
  30006. if (sep === '\n')
  30007. value += '\n';
  30008. else
  30009. sep = '\n';
  30010. }
  30011. else {
  30012. value += sep + content;
  30013. sep = ' ';
  30014. prevMoreIndented = false;
  30015. }
  30016. }
  30017. switch (header.chomp) {
  30018. case '-':
  30019. break;
  30020. case '+':
  30021. for (let i = chompStart; i < lines.length; ++i)
  30022. value += '\n' + lines[i][0].slice(trimIndent);
  30023. if (value[value.length - 1] !== '\n')
  30024. value += '\n';
  30025. break;
  30026. default:
  30027. value += '\n';
  30028. }
  30029. const end = start + header.length + scalar.source.length;
  30030. return { value, type, comment: header.comment, range: [start, end, end] };
  30031. }
  30032. function parseBlockScalarHeader({ offset, props }, strict, onError) {
  30033. /* istanbul ignore if should not happen */
  30034. if (props[0].type !== 'block-scalar-header') {
  30035. onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');
  30036. return null;
  30037. }
  30038. const { source } = props[0];
  30039. const mode = source[0];
  30040. let indent = 0;
  30041. let chomp = '';
  30042. let error = -1;
  30043. for (let i = 1; i < source.length; ++i) {
  30044. const ch = source[i];
  30045. if (!chomp && (ch === '-' || ch === '+'))
  30046. chomp = ch;
  30047. else {
  30048. const n = Number(ch);
  30049. if (!indent && n)
  30050. indent = n;
  30051. else if (error === -1)
  30052. error = offset + i;
  30053. }
  30054. }
  30055. if (error !== -1)
  30056. onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);
  30057. let hasSpace = false;
  30058. let comment = '';
  30059. let length = source.length;
  30060. for (let i = 1; i < props.length; ++i) {
  30061. const token = props[i];
  30062. switch (token.type) {
  30063. case 'space':
  30064. hasSpace = true;
  30065. // fallthrough
  30066. case 'newline':
  30067. length += token.source.length;
  30068. break;
  30069. case 'comment':
  30070. if (strict && !hasSpace) {
  30071. const message = 'Comments must be separated from other tokens by white space characters';
  30072. onError(token, 'MISSING_CHAR', message);
  30073. }
  30074. length += token.source.length;
  30075. comment = token.source.substring(1);
  30076. break;
  30077. case 'error':
  30078. onError(token, 'UNEXPECTED_TOKEN', token.message);
  30079. length += token.source.length;
  30080. break;
  30081. /* istanbul ignore next should not happen */
  30082. default: {
  30083. const message = `Unexpected token in block scalar header: ${token.type}`;
  30084. onError(token, 'UNEXPECTED_TOKEN', message);
  30085. const ts = token.source;
  30086. if (ts && typeof ts === 'string')
  30087. length += ts.length;
  30088. }
  30089. }
  30090. }
  30091. return { mode, indent, chomp, comment, length };
  30092. }
  30093. /** @returns Array of lines split up as `[indent, content]` */
  30094. function splitLines(source) {
  30095. const split = source.split(/\n( *)/);
  30096. const first = split[0];
  30097. const m = first.match(/^( *)/);
  30098. const line0 = m?.[1]
  30099. ? [m[1], first.slice(m[1].length)]
  30100. : ['', first];
  30101. const lines = [line0];
  30102. for (let i = 1; i < split.length; i += 2)
  30103. lines.push([split[i], split[i + 1]]);
  30104. return lines;
  30105. }
  30106. function resolveFlowScalar(scalar, strict, onError) {
  30107. const { offset, type, source, end } = scalar;
  30108. let _type;
  30109. let value;
  30110. const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
  30111. switch (type) {
  30112. case 'scalar':
  30113. _type = Scalar.PLAIN;
  30114. value = plainValue(source, _onError);
  30115. break;
  30116. case 'single-quoted-scalar':
  30117. _type = Scalar.QUOTE_SINGLE;
  30118. value = singleQuotedValue(source, _onError);
  30119. break;
  30120. case 'double-quoted-scalar':
  30121. _type = Scalar.QUOTE_DOUBLE;
  30122. value = doubleQuotedValue(source, _onError);
  30123. break;
  30124. /* istanbul ignore next should not happen */
  30125. default:
  30126. onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);
  30127. return {
  30128. value: '',
  30129. type: null,
  30130. comment: '',
  30131. range: [offset, offset + source.length, offset + source.length]
  30132. };
  30133. }
  30134. const valueEnd = offset + source.length;
  30135. const re = resolveEnd(end, valueEnd, strict, onError);
  30136. return {
  30137. value,
  30138. type: _type,
  30139. comment: re.comment,
  30140. range: [offset, valueEnd, re.offset]
  30141. };
  30142. }
  30143. function plainValue(source, onError) {
  30144. let badChar = '';
  30145. switch (source[0]) {
  30146. /* istanbul ignore next should not happen */
  30147. case '\t':
  30148. badChar = 'a tab character';
  30149. break;
  30150. case ',':
  30151. badChar = 'flow indicator character ,';
  30152. break;
  30153. case '%':
  30154. badChar = 'directive indicator character %';
  30155. break;
  30156. case '|':
  30157. case '>': {
  30158. badChar = `block scalar indicator ${source[0]}`;
  30159. break;
  30160. }
  30161. case '@':
  30162. case '`': {
  30163. badChar = `reserved character ${source[0]}`;
  30164. break;
  30165. }
  30166. }
  30167. if (badChar)
  30168. onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);
  30169. return foldLines(source);
  30170. }
  30171. function singleQuotedValue(source, onError) {
  30172. if (source[source.length - 1] !== "'" || source.length === 1)
  30173. onError(source.length, 'MISSING_CHAR', "Missing closing 'quote");
  30174. return foldLines(source.slice(1, -1)).replace(/''/g, "'");
  30175. }
  30176. function foldLines(source) {
  30177. /**
  30178. * The negative lookbehind here and in the `re` RegExp is to
  30179. * prevent causing a polynomial search time in certain cases.
  30180. *
  30181. * The try-catch is for Safari, which doesn't support this yet:
  30182. * https://caniuse.com/js-regexp-lookbehind
  30183. */
  30184. let first, line;
  30185. try {
  30186. first = new RegExp('(.*?)(?<![ \t])[ \t]*\r?\n', 'sy');
  30187. line = new RegExp('[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n', 'sy');
  30188. }
  30189. catch (_) {
  30190. first = /(.*?)[ \t]*\r?\n/sy;
  30191. line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
  30192. }
  30193. let match = first.exec(source);
  30194. if (!match)
  30195. return source;
  30196. let res = match[1];
  30197. let sep = ' ';
  30198. let pos = first.lastIndex;
  30199. line.lastIndex = pos;
  30200. while ((match = line.exec(source))) {
  30201. if (match[1] === '') {
  30202. if (sep === '\n')
  30203. res += sep;
  30204. else
  30205. sep = '\n';
  30206. }
  30207. else {
  30208. res += sep + match[1];
  30209. sep = ' ';
  30210. }
  30211. pos = line.lastIndex;
  30212. }
  30213. const last = /[ \t]*(.*)/sy;
  30214. last.lastIndex = pos;
  30215. match = last.exec(source);
  30216. return res + sep + (match?.[1] ?? '');
  30217. }
  30218. function doubleQuotedValue(source, onError) {
  30219. let res = '';
  30220. for (let i = 1; i < source.length - 1; ++i) {
  30221. const ch = source[i];
  30222. if (ch === '\r' && source[i + 1] === '\n')
  30223. continue;
  30224. if (ch === '\n') {
  30225. const { fold, offset } = foldNewline(source, i);
  30226. res += fold;
  30227. i = offset;
  30228. }
  30229. else if (ch === '\\') {
  30230. let next = source[++i];
  30231. const cc = escapeCodes[next];
  30232. if (cc)
  30233. res += cc;
  30234. else if (next === '\n') {
  30235. // skip escaped newlines, but still trim the following line
  30236. next = source[i + 1];
  30237. while (next === ' ' || next === '\t')
  30238. next = source[++i + 1];
  30239. }
  30240. else if (next === '\r' && source[i + 1] === '\n') {
  30241. // skip escaped CRLF newlines, but still trim the following line
  30242. next = source[++i + 1];
  30243. while (next === ' ' || next === '\t')
  30244. next = source[++i + 1];
  30245. }
  30246. else if (next === 'x' || next === 'u' || next === 'U') {
  30247. const length = { x: 2, u: 4, U: 8 }[next];
  30248. res += parseCharCode(source, i + 1, length, onError);
  30249. i += length;
  30250. }
  30251. else {
  30252. const raw = source.substr(i - 1, 2);
  30253. onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
  30254. res += raw;
  30255. }
  30256. }
  30257. else if (ch === ' ' || ch === '\t') {
  30258. // trim trailing whitespace
  30259. const wsStart = i;
  30260. let next = source[i + 1];
  30261. while (next === ' ' || next === '\t')
  30262. next = source[++i + 1];
  30263. if (next !== '\n' && !(next === '\r' && source[i + 2] === '\n'))
  30264. res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
  30265. }
  30266. else {
  30267. res += ch;
  30268. }
  30269. }
  30270. if (source[source.length - 1] !== '"' || source.length === 1)
  30271. onError(source.length, 'MISSING_CHAR', 'Missing closing "quote');
  30272. return res;
  30273. }
  30274. /**
  30275. * Fold a single newline into a space, multiple newlines to N - 1 newlines.
  30276. * Presumes `source[offset] === '\n'`
  30277. */
  30278. function foldNewline(source, offset) {
  30279. let fold = '';
  30280. let ch = source[offset + 1];
  30281. while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
  30282. if (ch === '\r' && source[offset + 2] !== '\n')
  30283. break;
  30284. if (ch === '\n')
  30285. fold += '\n';
  30286. offset += 1;
  30287. ch = source[offset + 1];
  30288. }
  30289. if (!fold)
  30290. fold = ' ';
  30291. return { fold, offset };
  30292. }
  30293. const escapeCodes = {
  30294. '0': '\0',
  30295. a: '\x07',
  30296. b: '\b',
  30297. e: '\x1b',
  30298. f: '\f',
  30299. n: '\n',
  30300. r: '\r',
  30301. t: '\t',
  30302. v: '\v',
  30303. N: '\u0085',
  30304. _: '\u00a0',
  30305. L: '\u2028',
  30306. P: '\u2029',
  30307. ' ': ' ',
  30308. '"': '"',
  30309. '/': '/',
  30310. '\\': '\\',
  30311. '\t': '\t'
  30312. };
  30313. function parseCharCode(source, offset, length, onError) {
  30314. const cc = source.substr(offset, length);
  30315. const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
  30316. const code = ok ? parseInt(cc, 16) : NaN;
  30317. if (isNaN(code)) {
  30318. const raw = source.substr(offset - 2, length + 2);
  30319. onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
  30320. return raw;
  30321. }
  30322. return String.fromCodePoint(code);
  30323. }
  30324. function composeScalar(ctx, token, tagToken, onError) {
  30325. const { value, type, comment, range } = token.type === 'block-scalar'
  30326. ? resolveBlockScalar(token, ctx.options.strict, onError)
  30327. : resolveFlowScalar(token, ctx.options.strict, onError);
  30328. const tagName = tagToken
  30329. ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))
  30330. : null;
  30331. const tag = tagToken && tagName
  30332. ? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError)
  30333. : token.type === 'scalar'
  30334. ? findScalarTagByTest(ctx, value, token, onError)
  30335. : ctx.schema[SCALAR$1];
  30336. let scalar;
  30337. try {
  30338. const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);
  30339. scalar = isScalar$1(res) ? res : new Scalar(res);
  30340. }
  30341. catch (error) {
  30342. const msg = error instanceof Error ? error.message : String(error);
  30343. onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);
  30344. scalar = new Scalar(value);
  30345. }
  30346. scalar.range = range;
  30347. scalar.source = value;
  30348. if (type)
  30349. scalar.type = type;
  30350. if (tagName)
  30351. scalar.tag = tagName;
  30352. if (tag.format)
  30353. scalar.format = tag.format;
  30354. if (comment)
  30355. scalar.comment = comment;
  30356. return scalar;
  30357. }
  30358. function findScalarTagByName(schema, value, tagName, tagToken, onError) {
  30359. if (tagName === '!')
  30360. return schema[SCALAR$1]; // non-specific tag
  30361. const matchWithTest = [];
  30362. for (const tag of schema.tags) {
  30363. if (!tag.collection && tag.tag === tagName) {
  30364. if (tag.default && tag.test)
  30365. matchWithTest.push(tag);
  30366. else
  30367. return tag;
  30368. }
  30369. }
  30370. for (const tag of matchWithTest)
  30371. if (tag.test?.test(value))
  30372. return tag;
  30373. const kt = schema.knownTags[tagName];
  30374. if (kt && !kt.collection) {
  30375. // Ensure that the known tag is available for stringifying,
  30376. // but does not get used by default.
  30377. schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
  30378. return kt;
  30379. }
  30380. onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');
  30381. return schema[SCALAR$1];
  30382. }
  30383. function findScalarTagByTest({ directives, schema }, value, token, onError) {
  30384. const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[SCALAR$1];
  30385. if (schema.compat) {
  30386. const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??
  30387. schema[SCALAR$1];
  30388. if (tag.tag !== compat.tag) {
  30389. const ts = directives.tagString(tag.tag);
  30390. const cs = directives.tagString(compat.tag);
  30391. const msg = `Value may be parsed as either ${ts} or ${cs}`;
  30392. onError(token, 'TAG_RESOLVE_FAILED', msg, true);
  30393. }
  30394. }
  30395. return tag;
  30396. }
  30397. function emptyScalarPosition(offset, before, pos) {
  30398. if (before) {
  30399. if (pos === null)
  30400. pos = before.length;
  30401. for (let i = pos - 1; i >= 0; --i) {
  30402. let st = before[i];
  30403. switch (st.type) {
  30404. case 'space':
  30405. case 'comment':
  30406. case 'newline':
  30407. offset -= st.source.length;
  30408. continue;
  30409. }
  30410. // Technically, an empty scalar is immediately after the last non-empty
  30411. // node, but it's more useful to place it after any whitespace.
  30412. st = before[++i];
  30413. while (st?.type === 'space') {
  30414. offset += st.source.length;
  30415. st = before[++i];
  30416. }
  30417. break;
  30418. }
  30419. }
  30420. return offset;
  30421. }
  30422. const CN = { composeNode, composeEmptyNode };
  30423. function composeNode(ctx, token, props, onError) {
  30424. const { spaceBefore, comment, anchor, tag } = props;
  30425. let node;
  30426. let isSrcToken = true;
  30427. switch (token.type) {
  30428. case 'alias':
  30429. node = composeAlias(ctx, token, onError);
  30430. if (anchor || tag)
  30431. onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');
  30432. break;
  30433. case 'scalar':
  30434. case 'single-quoted-scalar':
  30435. case 'double-quoted-scalar':
  30436. case 'block-scalar':
  30437. node = composeScalar(ctx, token, tag, onError);
  30438. if (anchor)
  30439. node.anchor = anchor.source.substring(1);
  30440. break;
  30441. case 'block-map':
  30442. case 'block-seq':
  30443. case 'flow-collection':
  30444. node = composeCollection(CN, ctx, token, tag, onError);
  30445. if (anchor)
  30446. node.anchor = anchor.source.substring(1);
  30447. break;
  30448. default: {
  30449. const message = token.type === 'error'
  30450. ? token.message
  30451. : `Unsupported token (type: ${token.type})`;
  30452. onError(token, 'UNEXPECTED_TOKEN', message);
  30453. node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError);
  30454. isSrcToken = false;
  30455. }
  30456. }
  30457. if (anchor && node.anchor === '')
  30458. onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
  30459. if (spaceBefore)
  30460. node.spaceBefore = true;
  30461. if (comment) {
  30462. if (token.type === 'scalar' && token.source === '')
  30463. node.comment = comment;
  30464. else
  30465. node.commentBefore = comment;
  30466. }
  30467. // @ts-expect-error Type checking misses meaning of isSrcToken
  30468. if (ctx.options.keepSourceTokens && isSrcToken)
  30469. node.srcToken = token;
  30470. return node;
  30471. }
  30472. function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag }, onError) {
  30473. const token = {
  30474. type: 'scalar',
  30475. offset: emptyScalarPosition(offset, before, pos),
  30476. indent: -1,
  30477. source: ''
  30478. };
  30479. const node = composeScalar(ctx, token, tag, onError);
  30480. if (anchor) {
  30481. node.anchor = anchor.source.substring(1);
  30482. if (node.anchor === '')
  30483. onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
  30484. }
  30485. if (spaceBefore)
  30486. node.spaceBefore = true;
  30487. if (comment)
  30488. node.comment = comment;
  30489. return node;
  30490. }
  30491. function composeAlias({ options }, { offset, source, end }, onError) {
  30492. const alias = new Alias(source.substring(1));
  30493. if (alias.source === '')
  30494. onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');
  30495. if (alias.source.endsWith(':'))
  30496. onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);
  30497. const valueEnd = offset + source.length;
  30498. const re = resolveEnd(end, valueEnd, options.strict, onError);
  30499. alias.range = [offset, valueEnd, re.offset];
  30500. if (re.comment)
  30501. alias.comment = re.comment;
  30502. return alias;
  30503. }
  30504. function composeDoc(options, directives, { offset, start, value, end }, onError) {
  30505. const opts = Object.assign({ _directives: directives }, options);
  30506. const doc = new Document(undefined, opts);
  30507. const ctx = {
  30508. atRoot: true,
  30509. directives: doc.directives,
  30510. options: doc.options,
  30511. schema: doc.schema
  30512. };
  30513. const props = resolveProps(start, {
  30514. indicator: 'doc-start',
  30515. next: value ?? end?.[0],
  30516. offset,
  30517. onError,
  30518. startOnNewline: true
  30519. });
  30520. if (props.found) {
  30521. doc.directives.docStart = true;
  30522. if (value &&
  30523. (value.type === 'block-map' || value.type === 'block-seq') &&
  30524. !props.hasNewline)
  30525. onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
  30526. }
  30527. doc.contents = value
  30528. ? composeNode(ctx, value, props, onError)
  30529. : composeEmptyNode(ctx, props.end, start, null, props, onError);
  30530. const contentEnd = doc.contents.range[2];
  30531. const re = resolveEnd(end, contentEnd, false, onError);
  30532. if (re.comment)
  30533. doc.comment = re.comment;
  30534. doc.range = [offset, contentEnd, re.offset];
  30535. return doc;
  30536. }
  30537. function getErrorPos(src) {
  30538. if (typeof src === 'number')
  30539. return [src, src + 1];
  30540. if (Array.isArray(src))
  30541. return src.length === 2 ? src : [src[0], src[1]];
  30542. const { offset, source } = src;
  30543. return [offset, offset + (typeof source === 'string' ? source.length : 1)];
  30544. }
  30545. function parsePrelude(prelude) {
  30546. let comment = '';
  30547. let atComment = false;
  30548. let afterEmptyLine = false;
  30549. for (let i = 0; i < prelude.length; ++i) {
  30550. const source = prelude[i];
  30551. switch (source[0]) {
  30552. case '#':
  30553. comment +=
  30554. (comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') +
  30555. (source.substring(1) || ' ');
  30556. atComment = true;
  30557. afterEmptyLine = false;
  30558. break;
  30559. case '%':
  30560. if (prelude[i + 1]?.[0] !== '#')
  30561. i += 1;
  30562. atComment = false;
  30563. break;
  30564. default:
  30565. // This may be wrong after doc-end, but in that case it doesn't matter
  30566. if (!atComment)
  30567. afterEmptyLine = true;
  30568. atComment = false;
  30569. }
  30570. }
  30571. return { comment, afterEmptyLine };
  30572. }
  30573. /**
  30574. * Compose a stream of CST nodes into a stream of YAML Documents.
  30575. *
  30576. * ```ts
  30577. * import { Composer, Parser } from 'yaml'
  30578. *
  30579. * const src: string = ...
  30580. * const tokens = new Parser().parse(src)
  30581. * const docs = new Composer().compose(tokens)
  30582. * ```
  30583. */
  30584. class Composer {
  30585. constructor(options = {}) {
  30586. this.doc = null;
  30587. this.atDirectives = false;
  30588. this.prelude = [];
  30589. this.errors = [];
  30590. this.warnings = [];
  30591. this.onError = (source, code, message, warning) => {
  30592. const pos = getErrorPos(source);
  30593. if (warning)
  30594. this.warnings.push(new YAMLWarning(pos, code, message));
  30595. else
  30596. this.errors.push(new YAMLParseError(pos, code, message));
  30597. };
  30598. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  30599. this.directives = new Directives({ version: options.version || '1.2' });
  30600. this.options = options;
  30601. }
  30602. decorate(doc, afterDoc) {
  30603. const { comment, afterEmptyLine } = parsePrelude(this.prelude);
  30604. //console.log({ dc: doc.comment, prelude, comment })
  30605. if (comment) {
  30606. const dc = doc.contents;
  30607. if (afterDoc) {
  30608. doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment;
  30609. }
  30610. else if (afterEmptyLine || doc.directives.docStart || !dc) {
  30611. doc.commentBefore = comment;
  30612. }
  30613. else if (isCollection$1(dc) && !dc.flow && dc.items.length > 0) {
  30614. let it = dc.items[0];
  30615. if (isPair(it))
  30616. it = it.key;
  30617. const cb = it.commentBefore;
  30618. it.commentBefore = cb ? `${comment}\n${cb}` : comment;
  30619. }
  30620. else {
  30621. const cb = dc.commentBefore;
  30622. dc.commentBefore = cb ? `${comment}\n${cb}` : comment;
  30623. }
  30624. }
  30625. if (afterDoc) {
  30626. Array.prototype.push.apply(doc.errors, this.errors);
  30627. Array.prototype.push.apply(doc.warnings, this.warnings);
  30628. }
  30629. else {
  30630. doc.errors = this.errors;
  30631. doc.warnings = this.warnings;
  30632. }
  30633. this.prelude = [];
  30634. this.errors = [];
  30635. this.warnings = [];
  30636. }
  30637. /**
  30638. * Current stream status information.
  30639. *
  30640. * Mostly useful at the end of input for an empty stream.
  30641. */
  30642. streamInfo() {
  30643. return {
  30644. comment: parsePrelude(this.prelude).comment,
  30645. directives: this.directives,
  30646. errors: this.errors,
  30647. warnings: this.warnings
  30648. };
  30649. }
  30650. /**
  30651. * Compose tokens into documents.
  30652. *
  30653. * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
  30654. * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
  30655. */
  30656. *compose(tokens, forceDoc = false, endOffset = -1) {
  30657. for (const token of tokens)
  30658. yield* this.next(token);
  30659. yield* this.end(forceDoc, endOffset);
  30660. }
  30661. /** Advance the composer by one CST token. */
  30662. *next(token) {
  30663. switch (token.type) {
  30664. case 'directive':
  30665. this.directives.add(token.source, (offset, message, warning) => {
  30666. const pos = getErrorPos(token);
  30667. pos[0] += offset;
  30668. this.onError(pos, 'BAD_DIRECTIVE', message, warning);
  30669. });
  30670. this.prelude.push(token.source);
  30671. this.atDirectives = true;
  30672. break;
  30673. case 'document': {
  30674. const doc = composeDoc(this.options, this.directives, token, this.onError);
  30675. if (this.atDirectives && !doc.directives.docStart)
  30676. this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');
  30677. this.decorate(doc, false);
  30678. if (this.doc)
  30679. yield this.doc;
  30680. this.doc = doc;
  30681. this.atDirectives = false;
  30682. break;
  30683. }
  30684. case 'byte-order-mark':
  30685. case 'space':
  30686. break;
  30687. case 'comment':
  30688. case 'newline':
  30689. this.prelude.push(token.source);
  30690. break;
  30691. case 'error': {
  30692. const msg = token.source
  30693. ? `${token.message}: ${JSON.stringify(token.source)}`
  30694. : token.message;
  30695. const error = new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);
  30696. if (this.atDirectives || !this.doc)
  30697. this.errors.push(error);
  30698. else
  30699. this.doc.errors.push(error);
  30700. break;
  30701. }
  30702. case 'doc-end': {
  30703. if (!this.doc) {
  30704. const msg = 'Unexpected doc-end without preceding document';
  30705. this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));
  30706. break;
  30707. }
  30708. this.doc.directives.docEnd = true;
  30709. const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
  30710. this.decorate(this.doc, true);
  30711. if (end.comment) {
  30712. const dc = this.doc.comment;
  30713. this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment;
  30714. }
  30715. this.doc.range[2] = end.offset;
  30716. break;
  30717. }
  30718. default:
  30719. this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));
  30720. }
  30721. }
  30722. /**
  30723. * Call at end of input to yield any remaining document.
  30724. *
  30725. * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
  30726. * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
  30727. */
  30728. *end(forceDoc = false, endOffset = -1) {
  30729. if (this.doc) {
  30730. this.decorate(this.doc, true);
  30731. yield this.doc;
  30732. this.doc = null;
  30733. }
  30734. else if (forceDoc) {
  30735. const opts = Object.assign({ _directives: this.directives }, this.options);
  30736. const doc = new Document(undefined, opts);
  30737. if (this.atDirectives)
  30738. this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');
  30739. doc.range = [0, endOffset, endOffset];
  30740. this.decorate(doc, false);
  30741. yield doc;
  30742. }
  30743. }
  30744. }
  30745. function resolveAsScalar(token, strict = true, onError) {
  30746. if (token) {
  30747. const _onError = (pos, code, message) => {
  30748. const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
  30749. if (onError)
  30750. onError(offset, code, message);
  30751. else
  30752. throw new YAMLParseError([offset, offset + 1], code, message);
  30753. };
  30754. switch (token.type) {
  30755. case 'scalar':
  30756. case 'single-quoted-scalar':
  30757. case 'double-quoted-scalar':
  30758. return resolveFlowScalar(token, strict, _onError);
  30759. case 'block-scalar':
  30760. return resolveBlockScalar(token, strict, _onError);
  30761. }
  30762. }
  30763. return null;
  30764. }
  30765. /**
  30766. * Create a new scalar token with `value`
  30767. *
  30768. * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
  30769. * as this function does not support any schema operations and won't check for such conflicts.
  30770. *
  30771. * @param value The string representation of the value, which will have its content properly indented.
  30772. * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.
  30773. * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
  30774. * @param context.indent The indent level of the token.
  30775. * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.
  30776. * @param context.offset The offset position of the token.
  30777. * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
  30778. */
  30779. function createScalarToken(value, context) {
  30780. const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;
  30781. const source = stringifyString({ type, value }, {
  30782. implicitKey,
  30783. indent: indent > 0 ? ' '.repeat(indent) : '',
  30784. inFlow,
  30785. options: { blockQuote: true, lineWidth: -1 }
  30786. });
  30787. const end = context.end ?? [
  30788. { type: 'newline', offset: -1, indent, source: '\n' }
  30789. ];
  30790. switch (source[0]) {
  30791. case '|':
  30792. case '>': {
  30793. const he = source.indexOf('\n');
  30794. const head = source.substring(0, he);
  30795. const body = source.substring(he + 1) + '\n';
  30796. const props = [
  30797. { type: 'block-scalar-header', offset, indent, source: head }
  30798. ];
  30799. if (!addEndtoBlockProps(props, end))
  30800. props.push({ type: 'newline', offset: -1, indent, source: '\n' });
  30801. return { type: 'block-scalar', offset, indent, props, source: body };
  30802. }
  30803. case '"':
  30804. return { type: 'double-quoted-scalar', offset, indent, source, end };
  30805. case "'":
  30806. return { type: 'single-quoted-scalar', offset, indent, source, end };
  30807. default:
  30808. return { type: 'scalar', offset, indent, source, end };
  30809. }
  30810. }
  30811. /**
  30812. * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.
  30813. *
  30814. * Best efforts are made to retain any comments previously associated with the `token`,
  30815. * though all contents within a collection's `items` will be overwritten.
  30816. *
  30817. * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
  30818. * as this function does not support any schema operations and won't check for such conflicts.
  30819. *
  30820. * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.
  30821. * @param value The string representation of the value, which will have its content properly indented.
  30822. * @param context.afterKey In most cases, values after a key should have an additional level of indentation.
  30823. * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
  30824. * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.
  30825. * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
  30826. */
  30827. function setScalarValue(token, value, context = {}) {
  30828. let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
  30829. let indent = 'indent' in token ? token.indent : null;
  30830. if (afterKey && typeof indent === 'number')
  30831. indent += 2;
  30832. if (!type)
  30833. switch (token.type) {
  30834. case 'single-quoted-scalar':
  30835. type = 'QUOTE_SINGLE';
  30836. break;
  30837. case 'double-quoted-scalar':
  30838. type = 'QUOTE_DOUBLE';
  30839. break;
  30840. case 'block-scalar': {
  30841. const header = token.props[0];
  30842. if (header.type !== 'block-scalar-header')
  30843. throw new Error('Invalid block scalar header');
  30844. type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';
  30845. break;
  30846. }
  30847. default:
  30848. type = 'PLAIN';
  30849. }
  30850. const source = stringifyString({ type, value }, {
  30851. implicitKey: implicitKey || indent === null,
  30852. indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',
  30853. inFlow,
  30854. options: { blockQuote: true, lineWidth: -1 }
  30855. });
  30856. switch (source[0]) {
  30857. case '|':
  30858. case '>':
  30859. setBlockScalarValue(token, source);
  30860. break;
  30861. case '"':
  30862. setFlowScalarValue(token, source, 'double-quoted-scalar');
  30863. break;
  30864. case "'":
  30865. setFlowScalarValue(token, source, 'single-quoted-scalar');
  30866. break;
  30867. default:
  30868. setFlowScalarValue(token, source, 'scalar');
  30869. }
  30870. }
  30871. function setBlockScalarValue(token, source) {
  30872. const he = source.indexOf('\n');
  30873. const head = source.substring(0, he);
  30874. const body = source.substring(he + 1) + '\n';
  30875. if (token.type === 'block-scalar') {
  30876. const header = token.props[0];
  30877. if (header.type !== 'block-scalar-header')
  30878. throw new Error('Invalid block scalar header');
  30879. header.source = head;
  30880. token.source = body;
  30881. }
  30882. else {
  30883. const { offset } = token;
  30884. const indent = 'indent' in token ? token.indent : -1;
  30885. const props = [
  30886. { type: 'block-scalar-header', offset, indent, source: head }
  30887. ];
  30888. if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))
  30889. props.push({ type: 'newline', offset: -1, indent, source: '\n' });
  30890. for (const key of Object.keys(token))
  30891. if (key !== 'type' && key !== 'offset')
  30892. delete token[key];
  30893. Object.assign(token, { type: 'block-scalar', indent, props, source: body });
  30894. }
  30895. }
  30896. /** @returns `true` if last token is a newline */
  30897. function addEndtoBlockProps(props, end) {
  30898. if (end)
  30899. for (const st of end)
  30900. switch (st.type) {
  30901. case 'space':
  30902. case 'comment':
  30903. props.push(st);
  30904. break;
  30905. case 'newline':
  30906. props.push(st);
  30907. return true;
  30908. }
  30909. return false;
  30910. }
  30911. function setFlowScalarValue(token, source, type) {
  30912. switch (token.type) {
  30913. case 'scalar':
  30914. case 'double-quoted-scalar':
  30915. case 'single-quoted-scalar':
  30916. token.type = type;
  30917. token.source = source;
  30918. break;
  30919. case 'block-scalar': {
  30920. const end = token.props.slice(1);
  30921. let oa = source.length;
  30922. if (token.props[0].type === 'block-scalar-header')
  30923. oa -= token.props[0].source.length;
  30924. for (const tok of end)
  30925. tok.offset += oa;
  30926. delete token.props;
  30927. Object.assign(token, { type, source, end });
  30928. break;
  30929. }
  30930. case 'block-map':
  30931. case 'block-seq': {
  30932. const offset = token.offset + source.length;
  30933. const nl = { type: 'newline', offset, indent: token.indent, source: '\n' };
  30934. delete token.items;
  30935. Object.assign(token, { type, source, end: [nl] });
  30936. break;
  30937. }
  30938. default: {
  30939. const indent = 'indent' in token ? token.indent : -1;
  30940. const end = 'end' in token && Array.isArray(token.end)
  30941. ? token.end.filter(st => st.type === 'space' ||
  30942. st.type === 'comment' ||
  30943. st.type === 'newline')
  30944. : [];
  30945. for (const key of Object.keys(token))
  30946. if (key !== 'type' && key !== 'offset')
  30947. delete token[key];
  30948. Object.assign(token, { type, indent, source, end });
  30949. }
  30950. }
  30951. }
  30952. /**
  30953. * Stringify a CST document, token, or collection item
  30954. *
  30955. * Fair warning: This applies no validation whatsoever, and
  30956. * simply concatenates the sources in their logical order.
  30957. */
  30958. const stringify$1 = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);
  30959. function stringifyToken(token) {
  30960. switch (token.type) {
  30961. case 'block-scalar': {
  30962. let res = '';
  30963. for (const tok of token.props)
  30964. res += stringifyToken(tok);
  30965. return res + token.source;
  30966. }
  30967. case 'block-map':
  30968. case 'block-seq': {
  30969. let res = '';
  30970. for (const item of token.items)
  30971. res += stringifyItem(item);
  30972. return res;
  30973. }
  30974. case 'flow-collection': {
  30975. let res = token.start.source;
  30976. for (const item of token.items)
  30977. res += stringifyItem(item);
  30978. for (const st of token.end)
  30979. res += st.source;
  30980. return res;
  30981. }
  30982. case 'document': {
  30983. let res = stringifyItem(token);
  30984. if (token.end)
  30985. for (const st of token.end)
  30986. res += st.source;
  30987. return res;
  30988. }
  30989. default: {
  30990. let res = token.source;
  30991. if ('end' in token && token.end)
  30992. for (const st of token.end)
  30993. res += st.source;
  30994. return res;
  30995. }
  30996. }
  30997. }
  30998. function stringifyItem({ start, key, sep, value }) {
  30999. let res = '';
  31000. for (const st of start)
  31001. res += st.source;
  31002. if (key)
  31003. res += stringifyToken(key);
  31004. if (sep)
  31005. for (const st of sep)
  31006. res += st.source;
  31007. if (value)
  31008. res += stringifyToken(value);
  31009. return res;
  31010. }
  31011. const BREAK = Symbol('break visit');
  31012. const SKIP = Symbol('skip children');
  31013. const REMOVE = Symbol('remove item');
  31014. /**
  31015. * Apply a visitor to a CST document or item.
  31016. *
  31017. * Walks through the tree (depth-first) starting from the root, calling a
  31018. * `visitor` function with two arguments when entering each item:
  31019. * - `item`: The current item, which included the following members:
  31020. * - `start: SourceToken[]` – Source tokens before the key or value,
  31021. * possibly including its anchor or tag.
  31022. * - `key?: Token | null` – Set for pair values. May then be `null`, if
  31023. * the key before the `:` separator is empty.
  31024. * - `sep?: SourceToken[]` – Source tokens between the key and the value,
  31025. * which should include the `:` map value indicator if `value` is set.
  31026. * - `value?: Token` – The value of a sequence item, or of a map pair.
  31027. * - `path`: The steps from the root to the current node, as an array of
  31028. * `['key' | 'value', number]` tuples.
  31029. *
  31030. * The return value of the visitor may be used to control the traversal:
  31031. * - `undefined` (default): Do nothing and continue
  31032. * - `visit.SKIP`: Do not visit the children of this token, continue with
  31033. * next sibling
  31034. * - `visit.BREAK`: Terminate traversal completely
  31035. * - `visit.REMOVE`: Remove the current item, then continue with the next one
  31036. * - `number`: Set the index of the next step. This is useful especially if
  31037. * the index of the current token has changed.
  31038. * - `function`: Define the next visitor for this item. After the original
  31039. * visitor is called on item entry, next visitors are called after handling
  31040. * a non-empty `key` and when exiting the item.
  31041. */
  31042. function visit(cst, visitor) {
  31043. if ('type' in cst && cst.type === 'document')
  31044. cst = { start: cst.start, value: cst.value };
  31045. _visit(Object.freeze([]), cst, visitor);
  31046. }
  31047. // Without the `as symbol` casts, TS declares these in the `visit`
  31048. // namespace using `var`, but then complains about that because
  31049. // `unique symbol` must be `const`.
  31050. /** Terminate visit traversal completely */
  31051. visit.BREAK = BREAK;
  31052. /** Do not visit the children of the current item */
  31053. visit.SKIP = SKIP;
  31054. /** Remove the current item */
  31055. visit.REMOVE = REMOVE;
  31056. /** Find the item at `path` from `cst` as the root */
  31057. visit.itemAtPath = (cst, path) => {
  31058. let item = cst;
  31059. for (const [field, index] of path) {
  31060. const tok = item?.[field];
  31061. if (tok && 'items' in tok) {
  31062. item = tok.items[index];
  31063. }
  31064. else
  31065. return undefined;
  31066. }
  31067. return item;
  31068. };
  31069. /**
  31070. * Get the immediate parent collection of the item at `path` from `cst` as the root.
  31071. *
  31072. * Throws an error if the collection is not found, which should never happen if the item itself exists.
  31073. */
  31074. visit.parentCollection = (cst, path) => {
  31075. const parent = visit.itemAtPath(cst, path.slice(0, -1));
  31076. const field = path[path.length - 1][0];
  31077. const coll = parent?.[field];
  31078. if (coll && 'items' in coll)
  31079. return coll;
  31080. throw new Error('Parent collection not found');
  31081. };
  31082. function _visit(path, item, visitor) {
  31083. let ctrl = visitor(item, path);
  31084. if (typeof ctrl === 'symbol')
  31085. return ctrl;
  31086. for (const field of ['key', 'value']) {
  31087. const token = item[field];
  31088. if (token && 'items' in token) {
  31089. for (let i = 0; i < token.items.length; ++i) {
  31090. const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
  31091. if (typeof ci === 'number')
  31092. i = ci - 1;
  31093. else if (ci === BREAK)
  31094. return BREAK;
  31095. else if (ci === REMOVE) {
  31096. token.items.splice(i, 1);
  31097. i -= 1;
  31098. }
  31099. }
  31100. if (typeof ctrl === 'function' && field === 'key')
  31101. ctrl = ctrl(item, path);
  31102. }
  31103. }
  31104. return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;
  31105. }
  31106. /** The byte order mark */
  31107. const BOM = '\u{FEFF}';
  31108. /** Start of doc-mode */
  31109. const DOCUMENT = '\x02'; // C0: Start of Text
  31110. /** Unexpected end of flow-mode */
  31111. const FLOW_END = '\x18'; // C0: Cancel
  31112. /** Next token is a scalar value */
  31113. const SCALAR = '\x1f'; // C0: Unit Separator
  31114. /** @returns `true` if `token` is a flow or block collection */
  31115. const isCollection = (token) => !!token && 'items' in token;
  31116. /** @returns `true` if `token` is a flow or block scalar; not an alias */
  31117. const isScalar = (token) => !!token &&
  31118. (token.type === 'scalar' ||
  31119. token.type === 'single-quoted-scalar' ||
  31120. token.type === 'double-quoted-scalar' ||
  31121. token.type === 'block-scalar');
  31122. /* istanbul ignore next */
  31123. /** Get a printable representation of a lexer token */
  31124. function prettyToken(token) {
  31125. switch (token) {
  31126. case BOM:
  31127. return '<BOM>';
  31128. case DOCUMENT:
  31129. return '<DOC>';
  31130. case FLOW_END:
  31131. return '<FLOW_END>';
  31132. case SCALAR:
  31133. return '<SCALAR>';
  31134. default:
  31135. return JSON.stringify(token);
  31136. }
  31137. }
  31138. /** Identify the type of a lexer token. May return `null` for unknown tokens. */
  31139. function tokenType(source) {
  31140. switch (source) {
  31141. case BOM:
  31142. return 'byte-order-mark';
  31143. case DOCUMENT:
  31144. return 'doc-mode';
  31145. case FLOW_END:
  31146. return 'flow-error-end';
  31147. case SCALAR:
  31148. return 'scalar';
  31149. case '---':
  31150. return 'doc-start';
  31151. case '...':
  31152. return 'doc-end';
  31153. case '':
  31154. case '\n':
  31155. case '\r\n':
  31156. return 'newline';
  31157. case '-':
  31158. return 'seq-item-ind';
  31159. case '?':
  31160. return 'explicit-key-ind';
  31161. case ':':
  31162. return 'map-value-ind';
  31163. case '{':
  31164. return 'flow-map-start';
  31165. case '}':
  31166. return 'flow-map-end';
  31167. case '[':
  31168. return 'flow-seq-start';
  31169. case ']':
  31170. return 'flow-seq-end';
  31171. case ',':
  31172. return 'comma';
  31173. }
  31174. switch (source[0]) {
  31175. case ' ':
  31176. case '\t':
  31177. return 'space';
  31178. case '#':
  31179. return 'comment';
  31180. case '%':
  31181. return 'directive-line';
  31182. case '*':
  31183. return 'alias';
  31184. case '&':
  31185. return 'anchor';
  31186. case '!':
  31187. return 'tag';
  31188. case "'":
  31189. return 'single-quoted-scalar';
  31190. case '"':
  31191. return 'double-quoted-scalar';
  31192. case '|':
  31193. case '>':
  31194. return 'block-scalar-header';
  31195. }
  31196. return null;
  31197. }
  31198. var cst = {
  31199. __proto__: null,
  31200. BOM: BOM,
  31201. DOCUMENT: DOCUMENT,
  31202. FLOW_END: FLOW_END,
  31203. SCALAR: SCALAR,
  31204. createScalarToken: createScalarToken,
  31205. isCollection: isCollection,
  31206. isScalar: isScalar,
  31207. prettyToken: prettyToken,
  31208. resolveAsScalar: resolveAsScalar,
  31209. setScalarValue: setScalarValue,
  31210. stringify: stringify$1,
  31211. tokenType: tokenType,
  31212. visit: visit
  31213. };
  31214. /*
  31215. START -> stream
  31216. stream
  31217. directive -> line-end -> stream
  31218. indent + line-end -> stream
  31219. [else] -> line-start
  31220. line-end
  31221. comment -> line-end
  31222. newline -> .
  31223. input-end -> END
  31224. line-start
  31225. doc-start -> doc
  31226. doc-end -> stream
  31227. [else] -> indent -> block-start
  31228. block-start
  31229. seq-item-start -> block-start
  31230. explicit-key-start -> block-start
  31231. map-value-start -> block-start
  31232. [else] -> doc
  31233. doc
  31234. line-end -> line-start
  31235. spaces -> doc
  31236. anchor -> doc
  31237. tag -> doc
  31238. flow-start -> flow -> doc
  31239. flow-end -> error -> doc
  31240. seq-item-start -> error -> doc
  31241. explicit-key-start -> error -> doc
  31242. map-value-start -> doc
  31243. alias -> doc
  31244. quote-start -> quoted-scalar -> doc
  31245. block-scalar-header -> line-end -> block-scalar(min) -> line-start
  31246. [else] -> plain-scalar(false, min) -> doc
  31247. flow
  31248. line-end -> flow
  31249. spaces -> flow
  31250. anchor -> flow
  31251. tag -> flow
  31252. flow-start -> flow -> flow
  31253. flow-end -> .
  31254. seq-item-start -> error -> flow
  31255. explicit-key-start -> flow
  31256. map-value-start -> flow
  31257. alias -> flow
  31258. quote-start -> quoted-scalar -> flow
  31259. comma -> flow
  31260. [else] -> plain-scalar(true, 0) -> flow
  31261. quoted-scalar
  31262. quote-end -> .
  31263. [else] -> quoted-scalar
  31264. block-scalar(min)
  31265. newline + peek(indent < min) -> .
  31266. [else] -> block-scalar(min)
  31267. plain-scalar(is-flow, min)
  31268. scalar-end(is-flow) -> .
  31269. peek(newline + (indent < min)) -> .
  31270. [else] -> plain-scalar(min)
  31271. */
  31272. function isEmpty(ch) {
  31273. switch (ch) {
  31274. case undefined:
  31275. case ' ':
  31276. case '\n':
  31277. case '\r':
  31278. case '\t':
  31279. return true;
  31280. default:
  31281. return false;
  31282. }
  31283. }
  31284. const hexDigits = '0123456789ABCDEFabcdef'.split('');
  31285. const tagChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()".split('');
  31286. const invalidFlowScalarChars = ',[]{}'.split('');
  31287. const invalidAnchorChars = ' ,[]{}\n\r\t'.split('');
  31288. const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.includes(ch);
  31289. /**
  31290. * Splits an input string into lexical tokens, i.e. smaller strings that are
  31291. * easily identifiable by `tokens.tokenType()`.
  31292. *
  31293. * Lexing starts always in a "stream" context. Incomplete input may be buffered
  31294. * until a complete token can be emitted.
  31295. *
  31296. * In addition to slices of the original input, the following control characters
  31297. * may also be emitted:
  31298. *
  31299. * - `\x02` (Start of Text): A document starts with the next token
  31300. * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error)
  31301. * - `\x1f` (Unit Separator): Next token is a scalar value
  31302. * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents
  31303. */
  31304. class Lexer {
  31305. constructor() {
  31306. /**
  31307. * Flag indicating whether the end of the current buffer marks the end of
  31308. * all input
  31309. */
  31310. this.atEnd = false;
  31311. /**
  31312. * Explicit indent set in block scalar header, as an offset from the current
  31313. * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not
  31314. * explicitly set.
  31315. */
  31316. this.blockScalarIndent = -1;
  31317. /**
  31318. * Block scalars that include a + (keep) chomping indicator in their header
  31319. * include trailing empty lines, which are otherwise excluded from the
  31320. * scalar's contents.
  31321. */
  31322. this.blockScalarKeep = false;
  31323. /** Current input */
  31324. this.buffer = '';
  31325. /**
  31326. * Flag noting whether the map value indicator : can immediately follow this
  31327. * node within a flow context.
  31328. */
  31329. this.flowKey = false;
  31330. /** Count of surrounding flow collection levels. */
  31331. this.flowLevel = 0;
  31332. /**
  31333. * Minimum level of indentation required for next lines to be parsed as a
  31334. * part of the current scalar value.
  31335. */
  31336. this.indentNext = 0;
  31337. /** Indentation level of the current line. */
  31338. this.indentValue = 0;
  31339. /** Position of the next \n character. */
  31340. this.lineEndPos = null;
  31341. /** Stores the state of the lexer if reaching the end of incpomplete input */
  31342. this.next = null;
  31343. /** A pointer to `buffer`; the current position of the lexer. */
  31344. this.pos = 0;
  31345. }
  31346. /**
  31347. * Generate YAML tokens from the `source` string. If `incomplete`,
  31348. * a part of the last line may be left as a buffer for the next call.
  31349. *
  31350. * @returns A generator of lexical tokens
  31351. */
  31352. *lex(source, incomplete = false) {
  31353. if (source) {
  31354. this.buffer = this.buffer ? this.buffer + source : source;
  31355. this.lineEndPos = null;
  31356. }
  31357. this.atEnd = !incomplete;
  31358. let next = this.next ?? 'stream';
  31359. while (next && (incomplete || this.hasChars(1)))
  31360. next = yield* this.parseNext(next);
  31361. }
  31362. atLineEnd() {
  31363. let i = this.pos;
  31364. let ch = this.buffer[i];
  31365. while (ch === ' ' || ch === '\t')
  31366. ch = this.buffer[++i];
  31367. if (!ch || ch === '#' || ch === '\n')
  31368. return true;
  31369. if (ch === '\r')
  31370. return this.buffer[i + 1] === '\n';
  31371. return false;
  31372. }
  31373. charAt(n) {
  31374. return this.buffer[this.pos + n];
  31375. }
  31376. continueScalar(offset) {
  31377. let ch = this.buffer[offset];
  31378. if (this.indentNext > 0) {
  31379. let indent = 0;
  31380. while (ch === ' ')
  31381. ch = this.buffer[++indent + offset];
  31382. if (ch === '\r') {
  31383. const next = this.buffer[indent + offset + 1];
  31384. if (next === '\n' || (!next && !this.atEnd))
  31385. return offset + indent + 1;
  31386. }
  31387. return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd)
  31388. ? offset + indent
  31389. : -1;
  31390. }
  31391. if (ch === '-' || ch === '.') {
  31392. const dt = this.buffer.substr(offset, 3);
  31393. if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))
  31394. return -1;
  31395. }
  31396. return offset;
  31397. }
  31398. getLine() {
  31399. let end = this.lineEndPos;
  31400. if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {
  31401. end = this.buffer.indexOf('\n', this.pos);
  31402. this.lineEndPos = end;
  31403. }
  31404. if (end === -1)
  31405. return this.atEnd ? this.buffer.substring(this.pos) : null;
  31406. if (this.buffer[end - 1] === '\r')
  31407. end -= 1;
  31408. return this.buffer.substring(this.pos, end);
  31409. }
  31410. hasChars(n) {
  31411. return this.pos + n <= this.buffer.length;
  31412. }
  31413. setNext(state) {
  31414. this.buffer = this.buffer.substring(this.pos);
  31415. this.pos = 0;
  31416. this.lineEndPos = null;
  31417. this.next = state;
  31418. return null;
  31419. }
  31420. peek(n) {
  31421. return this.buffer.substr(this.pos, n);
  31422. }
  31423. *parseNext(next) {
  31424. switch (next) {
  31425. case 'stream':
  31426. return yield* this.parseStream();
  31427. case 'line-start':
  31428. return yield* this.parseLineStart();
  31429. case 'block-start':
  31430. return yield* this.parseBlockStart();
  31431. case 'doc':
  31432. return yield* this.parseDocument();
  31433. case 'flow':
  31434. return yield* this.parseFlowCollection();
  31435. case 'quoted-scalar':
  31436. return yield* this.parseQuotedScalar();
  31437. case 'block-scalar':
  31438. return yield* this.parseBlockScalar();
  31439. case 'plain-scalar':
  31440. return yield* this.parsePlainScalar();
  31441. }
  31442. }
  31443. *parseStream() {
  31444. let line = this.getLine();
  31445. if (line === null)
  31446. return this.setNext('stream');
  31447. if (line[0] === BOM) {
  31448. yield* this.pushCount(1);
  31449. line = line.substring(1);
  31450. }
  31451. if (line[0] === '%') {
  31452. let dirEnd = line.length;
  31453. const cs = line.indexOf('#');
  31454. if (cs !== -1) {
  31455. const ch = line[cs - 1];
  31456. if (ch === ' ' || ch === '\t')
  31457. dirEnd = cs - 1;
  31458. }
  31459. while (true) {
  31460. const ch = line[dirEnd - 1];
  31461. if (ch === ' ' || ch === '\t')
  31462. dirEnd -= 1;
  31463. else
  31464. break;
  31465. }
  31466. const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
  31467. yield* this.pushCount(line.length - n); // possible comment
  31468. this.pushNewline();
  31469. return 'stream';
  31470. }
  31471. if (this.atLineEnd()) {
  31472. const sp = yield* this.pushSpaces(true);
  31473. yield* this.pushCount(line.length - sp);
  31474. yield* this.pushNewline();
  31475. return 'stream';
  31476. }
  31477. yield DOCUMENT;
  31478. return yield* this.parseLineStart();
  31479. }
  31480. *parseLineStart() {
  31481. const ch = this.charAt(0);
  31482. if (!ch && !this.atEnd)
  31483. return this.setNext('line-start');
  31484. if (ch === '-' || ch === '.') {
  31485. if (!this.atEnd && !this.hasChars(4))
  31486. return this.setNext('line-start');
  31487. const s = this.peek(3);
  31488. if (s === '---' && isEmpty(this.charAt(3))) {
  31489. yield* this.pushCount(3);
  31490. this.indentValue = 0;
  31491. this.indentNext = 0;
  31492. return 'doc';
  31493. }
  31494. else if (s === '...' && isEmpty(this.charAt(3))) {
  31495. yield* this.pushCount(3);
  31496. return 'stream';
  31497. }
  31498. }
  31499. this.indentValue = yield* this.pushSpaces(false);
  31500. if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
  31501. this.indentNext = this.indentValue;
  31502. return yield* this.parseBlockStart();
  31503. }
  31504. *parseBlockStart() {
  31505. const [ch0, ch1] = this.peek(2);
  31506. if (!ch1 && !this.atEnd)
  31507. return this.setNext('block-start');
  31508. if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {
  31509. const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
  31510. this.indentNext = this.indentValue + 1;
  31511. this.indentValue += n;
  31512. return yield* this.parseBlockStart();
  31513. }
  31514. return 'doc';
  31515. }
  31516. *parseDocument() {
  31517. yield* this.pushSpaces(true);
  31518. const line = this.getLine();
  31519. if (line === null)
  31520. return this.setNext('doc');
  31521. let n = yield* this.pushIndicators();
  31522. switch (line[n]) {
  31523. case '#':
  31524. yield* this.pushCount(line.length - n);
  31525. // fallthrough
  31526. case undefined:
  31527. yield* this.pushNewline();
  31528. return yield* this.parseLineStart();
  31529. case '{':
  31530. case '[':
  31531. yield* this.pushCount(1);
  31532. this.flowKey = false;
  31533. this.flowLevel = 1;
  31534. return 'flow';
  31535. case '}':
  31536. case ']':
  31537. // this is an error
  31538. yield* this.pushCount(1);
  31539. return 'doc';
  31540. case '*':
  31541. yield* this.pushUntil(isNotAnchorChar);
  31542. return 'doc';
  31543. case '"':
  31544. case "'":
  31545. return yield* this.parseQuotedScalar();
  31546. case '|':
  31547. case '>':
  31548. n += yield* this.parseBlockScalarHeader();
  31549. n += yield* this.pushSpaces(true);
  31550. yield* this.pushCount(line.length - n);
  31551. yield* this.pushNewline();
  31552. return yield* this.parseBlockScalar();
  31553. default:
  31554. return yield* this.parsePlainScalar();
  31555. }
  31556. }
  31557. *parseFlowCollection() {
  31558. let nl, sp;
  31559. let indent = -1;
  31560. do {
  31561. nl = yield* this.pushNewline();
  31562. if (nl > 0) {
  31563. sp = yield* this.pushSpaces(false);
  31564. this.indentValue = indent = sp;
  31565. }
  31566. else {
  31567. sp = 0;
  31568. }
  31569. sp += yield* this.pushSpaces(true);
  31570. } while (nl + sp > 0);
  31571. const line = this.getLine();
  31572. if (line === null)
  31573. return this.setNext('flow');
  31574. if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||
  31575. (indent === 0 &&
  31576. (line.startsWith('---') || line.startsWith('...')) &&
  31577. isEmpty(line[3]))) {
  31578. // Allowing for the terminal ] or } at the same (rather than greater)
  31579. // indent level as the initial [ or { is technically invalid, but
  31580. // failing here would be surprising to users.
  31581. const atFlowEndMarker = indent === this.indentNext - 1 &&
  31582. this.flowLevel === 1 &&
  31583. (line[0] === ']' || line[0] === '}');
  31584. if (!atFlowEndMarker) {
  31585. // this is an error
  31586. this.flowLevel = 0;
  31587. yield FLOW_END;
  31588. return yield* this.parseLineStart();
  31589. }
  31590. }
  31591. let n = 0;
  31592. while (line[n] === ',') {
  31593. n += yield* this.pushCount(1);
  31594. n += yield* this.pushSpaces(true);
  31595. this.flowKey = false;
  31596. }
  31597. n += yield* this.pushIndicators();
  31598. switch (line[n]) {
  31599. case undefined:
  31600. return 'flow';
  31601. case '#':
  31602. yield* this.pushCount(line.length - n);
  31603. return 'flow';
  31604. case '{':
  31605. case '[':
  31606. yield* this.pushCount(1);
  31607. this.flowKey = false;
  31608. this.flowLevel += 1;
  31609. return 'flow';
  31610. case '}':
  31611. case ']':
  31612. yield* this.pushCount(1);
  31613. this.flowKey = true;
  31614. this.flowLevel -= 1;
  31615. return this.flowLevel ? 'flow' : 'doc';
  31616. case '*':
  31617. yield* this.pushUntil(isNotAnchorChar);
  31618. return 'flow';
  31619. case '"':
  31620. case "'":
  31621. this.flowKey = true;
  31622. return yield* this.parseQuotedScalar();
  31623. case ':': {
  31624. const next = this.charAt(1);
  31625. if (this.flowKey || isEmpty(next) || next === ',') {
  31626. this.flowKey = false;
  31627. yield* this.pushCount(1);
  31628. yield* this.pushSpaces(true);
  31629. return 'flow';
  31630. }
  31631. }
  31632. // fallthrough
  31633. default:
  31634. this.flowKey = false;
  31635. return yield* this.parsePlainScalar();
  31636. }
  31637. }
  31638. *parseQuotedScalar() {
  31639. const quote = this.charAt(0);
  31640. let end = this.buffer.indexOf(quote, this.pos + 1);
  31641. if (quote === "'") {
  31642. while (end !== -1 && this.buffer[end + 1] === "'")
  31643. end = this.buffer.indexOf("'", end + 2);
  31644. }
  31645. else {
  31646. // double-quote
  31647. while (end !== -1) {
  31648. let n = 0;
  31649. while (this.buffer[end - 1 - n] === '\\')
  31650. n += 1;
  31651. if (n % 2 === 0)
  31652. break;
  31653. end = this.buffer.indexOf('"', end + 1);
  31654. }
  31655. }
  31656. // Only looking for newlines within the quotes
  31657. const qb = this.buffer.substring(0, end);
  31658. let nl = qb.indexOf('\n', this.pos);
  31659. if (nl !== -1) {
  31660. while (nl !== -1) {
  31661. const cs = this.continueScalar(nl + 1);
  31662. if (cs === -1)
  31663. break;
  31664. nl = qb.indexOf('\n', cs);
  31665. }
  31666. if (nl !== -1) {
  31667. // this is an error caused by an unexpected unindent
  31668. end = nl - (qb[nl - 1] === '\r' ? 2 : 1);
  31669. }
  31670. }
  31671. if (end === -1) {
  31672. if (!this.atEnd)
  31673. return this.setNext('quoted-scalar');
  31674. end = this.buffer.length;
  31675. }
  31676. yield* this.pushToIndex(end + 1, false);
  31677. return this.flowLevel ? 'flow' : 'doc';
  31678. }
  31679. *parseBlockScalarHeader() {
  31680. this.blockScalarIndent = -1;
  31681. this.blockScalarKeep = false;
  31682. let i = this.pos;
  31683. while (true) {
  31684. const ch = this.buffer[++i];
  31685. if (ch === '+')
  31686. this.blockScalarKeep = true;
  31687. else if (ch > '0' && ch <= '9')
  31688. this.blockScalarIndent = Number(ch) - 1;
  31689. else if (ch !== '-')
  31690. break;
  31691. }
  31692. return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');
  31693. }
  31694. *parseBlockScalar() {
  31695. let nl = this.pos - 1; // may be -1 if this.pos === 0
  31696. let indent = 0;
  31697. let ch;
  31698. loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {
  31699. switch (ch) {
  31700. case ' ':
  31701. indent += 1;
  31702. break;
  31703. case '\n':
  31704. nl = i;
  31705. indent = 0;
  31706. break;
  31707. case '\r': {
  31708. const next = this.buffer[i + 1];
  31709. if (!next && !this.atEnd)
  31710. return this.setNext('block-scalar');
  31711. if (next === '\n')
  31712. break;
  31713. } // fallthrough
  31714. default:
  31715. break loop;
  31716. }
  31717. }
  31718. if (!ch && !this.atEnd)
  31719. return this.setNext('block-scalar');
  31720. if (indent >= this.indentNext) {
  31721. if (this.blockScalarIndent === -1)
  31722. this.indentNext = indent;
  31723. else
  31724. this.indentNext += this.blockScalarIndent;
  31725. do {
  31726. const cs = this.continueScalar(nl + 1);
  31727. if (cs === -1)
  31728. break;
  31729. nl = this.buffer.indexOf('\n', cs);
  31730. } while (nl !== -1);
  31731. if (nl === -1) {
  31732. if (!this.atEnd)
  31733. return this.setNext('block-scalar');
  31734. nl = this.buffer.length;
  31735. }
  31736. }
  31737. if (!this.blockScalarKeep) {
  31738. do {
  31739. let i = nl - 1;
  31740. let ch = this.buffer[i];
  31741. if (ch === '\r')
  31742. ch = this.buffer[--i];
  31743. const lastChar = i; // Drop the line if last char not more indented
  31744. while (ch === ' ' || ch === '\t')
  31745. ch = this.buffer[--i];
  31746. if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar)
  31747. nl = i;
  31748. else
  31749. break;
  31750. } while (true);
  31751. }
  31752. yield SCALAR;
  31753. yield* this.pushToIndex(nl + 1, true);
  31754. return yield* this.parseLineStart();
  31755. }
  31756. *parsePlainScalar() {
  31757. const inFlow = this.flowLevel > 0;
  31758. let end = this.pos - 1;
  31759. let i = this.pos - 1;
  31760. let ch;
  31761. while ((ch = this.buffer[++i])) {
  31762. if (ch === ':') {
  31763. const next = this.buffer[i + 1];
  31764. if (isEmpty(next) || (inFlow && next === ','))
  31765. break;
  31766. end = i;
  31767. }
  31768. else if (isEmpty(ch)) {
  31769. let next = this.buffer[i + 1];
  31770. if (ch === '\r') {
  31771. if (next === '\n') {
  31772. i += 1;
  31773. ch = '\n';
  31774. next = this.buffer[i + 1];
  31775. }
  31776. else
  31777. end = i;
  31778. }
  31779. if (next === '#' || (inFlow && invalidFlowScalarChars.includes(next)))
  31780. break;
  31781. if (ch === '\n') {
  31782. const cs = this.continueScalar(i + 1);
  31783. if (cs === -1)
  31784. break;
  31785. i = Math.max(i, cs - 2); // to advance, but still account for ' #'
  31786. }
  31787. }
  31788. else {
  31789. if (inFlow && invalidFlowScalarChars.includes(ch))
  31790. break;
  31791. end = i;
  31792. }
  31793. }
  31794. if (!ch && !this.atEnd)
  31795. return this.setNext('plain-scalar');
  31796. yield SCALAR;
  31797. yield* this.pushToIndex(end + 1, true);
  31798. return inFlow ? 'flow' : 'doc';
  31799. }
  31800. *pushCount(n) {
  31801. if (n > 0) {
  31802. yield this.buffer.substr(this.pos, n);
  31803. this.pos += n;
  31804. return n;
  31805. }
  31806. return 0;
  31807. }
  31808. *pushToIndex(i, allowEmpty) {
  31809. const s = this.buffer.slice(this.pos, i);
  31810. if (s) {
  31811. yield s;
  31812. this.pos += s.length;
  31813. return s.length;
  31814. }
  31815. else if (allowEmpty)
  31816. yield '';
  31817. return 0;
  31818. }
  31819. *pushIndicators() {
  31820. switch (this.charAt(0)) {
  31821. case '!':
  31822. return ((yield* this.pushTag()) +
  31823. (yield* this.pushSpaces(true)) +
  31824. (yield* this.pushIndicators()));
  31825. case '&':
  31826. return ((yield* this.pushUntil(isNotAnchorChar)) +
  31827. (yield* this.pushSpaces(true)) +
  31828. (yield* this.pushIndicators()));
  31829. case '-': // this is an error
  31830. case '?': // this is an error outside flow collections
  31831. case ':': {
  31832. const inFlow = this.flowLevel > 0;
  31833. const ch1 = this.charAt(1);
  31834. if (isEmpty(ch1) || (inFlow && invalidFlowScalarChars.includes(ch1))) {
  31835. if (!inFlow)
  31836. this.indentNext = this.indentValue + 1;
  31837. else if (this.flowKey)
  31838. this.flowKey = false;
  31839. return ((yield* this.pushCount(1)) +
  31840. (yield* this.pushSpaces(true)) +
  31841. (yield* this.pushIndicators()));
  31842. }
  31843. }
  31844. }
  31845. return 0;
  31846. }
  31847. *pushTag() {
  31848. if (this.charAt(1) === '<') {
  31849. let i = this.pos + 2;
  31850. let ch = this.buffer[i];
  31851. while (!isEmpty(ch) && ch !== '>')
  31852. ch = this.buffer[++i];
  31853. return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);
  31854. }
  31855. else {
  31856. let i = this.pos + 1;
  31857. let ch = this.buffer[i];
  31858. while (ch) {
  31859. if (tagChars.includes(ch))
  31860. ch = this.buffer[++i];
  31861. else if (ch === '%' &&
  31862. hexDigits.includes(this.buffer[i + 1]) &&
  31863. hexDigits.includes(this.buffer[i + 2])) {
  31864. ch = this.buffer[(i += 3)];
  31865. }
  31866. else
  31867. break;
  31868. }
  31869. return yield* this.pushToIndex(i, false);
  31870. }
  31871. }
  31872. *pushNewline() {
  31873. const ch = this.buffer[this.pos];
  31874. if (ch === '\n')
  31875. return yield* this.pushCount(1);
  31876. else if (ch === '\r' && this.charAt(1) === '\n')
  31877. return yield* this.pushCount(2);
  31878. else
  31879. return 0;
  31880. }
  31881. *pushSpaces(allowTabs) {
  31882. let i = this.pos - 1;
  31883. let ch;
  31884. do {
  31885. ch = this.buffer[++i];
  31886. } while (ch === ' ' || (allowTabs && ch === '\t'));
  31887. const n = i - this.pos;
  31888. if (n > 0) {
  31889. yield this.buffer.substr(this.pos, n);
  31890. this.pos = i;
  31891. }
  31892. return n;
  31893. }
  31894. *pushUntil(test) {
  31895. let i = this.pos;
  31896. let ch = this.buffer[i];
  31897. while (!test(ch))
  31898. ch = this.buffer[++i];
  31899. return yield* this.pushToIndex(i, false);
  31900. }
  31901. }
  31902. /**
  31903. * Tracks newlines during parsing in order to provide an efficient API for
  31904. * determining the one-indexed `{ line, col }` position for any offset
  31905. * within the input.
  31906. */
  31907. class LineCounter {
  31908. constructor() {
  31909. this.lineStarts = [];
  31910. /**
  31911. * Should be called in ascending order. Otherwise, call
  31912. * `lineCounter.lineStarts.sort()` before calling `linePos()`.
  31913. */
  31914. this.addNewLine = (offset) => this.lineStarts.push(offset);
  31915. /**
  31916. * Performs a binary search and returns the 1-indexed { line, col }
  31917. * position of `offset`. If `line === 0`, `addNewLine` has never been
  31918. * called or `offset` is before the first known newline.
  31919. */
  31920. this.linePos = (offset) => {
  31921. let low = 0;
  31922. let high = this.lineStarts.length;
  31923. while (low < high) {
  31924. const mid = (low + high) >> 1; // Math.floor((low + high) / 2)
  31925. if (this.lineStarts[mid] < offset)
  31926. low = mid + 1;
  31927. else
  31928. high = mid;
  31929. }
  31930. if (this.lineStarts[low] === offset)
  31931. return { line: low + 1, col: 1 };
  31932. if (low === 0)
  31933. return { line: 0, col: offset };
  31934. const start = this.lineStarts[low - 1];
  31935. return { line: low, col: offset - start + 1 };
  31936. };
  31937. }
  31938. }
  31939. function includesToken(list, type) {
  31940. for (let i = 0; i < list.length; ++i)
  31941. if (list[i].type === type)
  31942. return true;
  31943. return false;
  31944. }
  31945. function findNonEmptyIndex(list) {
  31946. for (let i = 0; i < list.length; ++i) {
  31947. switch (list[i].type) {
  31948. case 'space':
  31949. case 'comment':
  31950. case 'newline':
  31951. break;
  31952. default:
  31953. return i;
  31954. }
  31955. }
  31956. return -1;
  31957. }
  31958. function isFlowToken(token) {
  31959. switch (token?.type) {
  31960. case 'alias':
  31961. case 'scalar':
  31962. case 'single-quoted-scalar':
  31963. case 'double-quoted-scalar':
  31964. case 'flow-collection':
  31965. return true;
  31966. default:
  31967. return false;
  31968. }
  31969. }
  31970. function getPrevProps(parent) {
  31971. switch (parent.type) {
  31972. case 'document':
  31973. return parent.start;
  31974. case 'block-map': {
  31975. const it = parent.items[parent.items.length - 1];
  31976. return it.sep ?? it.start;
  31977. }
  31978. case 'block-seq':
  31979. return parent.items[parent.items.length - 1].start;
  31980. /* istanbul ignore next should not happen */
  31981. default:
  31982. return [];
  31983. }
  31984. }
  31985. /** Note: May modify input array */
  31986. function getFirstKeyStartProps(prev) {
  31987. if (prev.length === 0)
  31988. return [];
  31989. let i = prev.length;
  31990. loop: while (--i >= 0) {
  31991. switch (prev[i].type) {
  31992. case 'doc-start':
  31993. case 'explicit-key-ind':
  31994. case 'map-value-ind':
  31995. case 'seq-item-ind':
  31996. case 'newline':
  31997. break loop;
  31998. }
  31999. }
  32000. while (prev[++i]?.type === 'space') {
  32001. /* loop */
  32002. }
  32003. return prev.splice(i, prev.length);
  32004. }
  32005. function fixFlowSeqItems(fc) {
  32006. if (fc.start.type === 'flow-seq-start') {
  32007. for (const it of fc.items) {
  32008. if (it.sep &&
  32009. !it.value &&
  32010. !includesToken(it.start, 'explicit-key-ind') &&
  32011. !includesToken(it.sep, 'map-value-ind')) {
  32012. if (it.key)
  32013. it.value = it.key;
  32014. delete it.key;
  32015. if (isFlowToken(it.value)) {
  32016. if (it.value.end)
  32017. Array.prototype.push.apply(it.value.end, it.sep);
  32018. else
  32019. it.value.end = it.sep;
  32020. }
  32021. else
  32022. Array.prototype.push.apply(it.start, it.sep);
  32023. delete it.sep;
  32024. }
  32025. }
  32026. }
  32027. }
  32028. /**
  32029. * A YAML concrete syntax tree (CST) parser
  32030. *
  32031. * ```ts
  32032. * const src: string = ...
  32033. * for (const token of new Parser().parse(src)) {
  32034. * // token: Token
  32035. * }
  32036. * ```
  32037. *
  32038. * To use the parser with a user-provided lexer:
  32039. *
  32040. * ```ts
  32041. * function* parse(source: string, lexer: Lexer) {
  32042. * const parser = new Parser()
  32043. * for (const lexeme of lexer.lex(source))
  32044. * yield* parser.next(lexeme)
  32045. * yield* parser.end()
  32046. * }
  32047. *
  32048. * const src: string = ...
  32049. * const lexer = new Lexer()
  32050. * for (const token of parse(src, lexer)) {
  32051. * // token: Token
  32052. * }
  32053. * ```
  32054. */
  32055. class Parser {
  32056. /**
  32057. * @param onNewLine - If defined, called separately with the start position of
  32058. * each new line (in `parse()`, including the start of input).
  32059. */
  32060. constructor(onNewLine) {
  32061. /** If true, space and sequence indicators count as indentation */
  32062. this.atNewLine = true;
  32063. /** If true, next token is a scalar value */
  32064. this.atScalar = false;
  32065. /** Current indentation level */
  32066. this.indent = 0;
  32067. /** Current offset since the start of parsing */
  32068. this.offset = 0;
  32069. /** On the same line with a block map key */
  32070. this.onKeyLine = false;
  32071. /** Top indicates the node that's currently being built */
  32072. this.stack = [];
  32073. /** The source of the current token, set in parse() */
  32074. this.source = '';
  32075. /** The type of the current token, set in parse() */
  32076. this.type = '';
  32077. // Must be defined after `next()`
  32078. this.lexer = new Lexer();
  32079. this.onNewLine = onNewLine;
  32080. }
  32081. /**
  32082. * Parse `source` as a YAML stream.
  32083. * If `incomplete`, a part of the last line may be left as a buffer for the next call.
  32084. *
  32085. * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
  32086. *
  32087. * @returns A generator of tokens representing each directive, document, and other structure.
  32088. */
  32089. *parse(source, incomplete = false) {
  32090. if (this.onNewLine && this.offset === 0)
  32091. this.onNewLine(0);
  32092. for (const lexeme of this.lexer.lex(source, incomplete))
  32093. yield* this.next(lexeme);
  32094. if (!incomplete)
  32095. yield* this.end();
  32096. }
  32097. /**
  32098. * Advance the parser by the `source` of one lexical token.
  32099. */
  32100. *next(source) {
  32101. this.source = source;
  32102. if (this.atScalar) {
  32103. this.atScalar = false;
  32104. yield* this.step();
  32105. this.offset += source.length;
  32106. return;
  32107. }
  32108. const type = tokenType(source);
  32109. if (!type) {
  32110. const message = `Not a YAML token: ${source}`;
  32111. yield* this.pop({ type: 'error', offset: this.offset, message, source });
  32112. this.offset += source.length;
  32113. }
  32114. else if (type === 'scalar') {
  32115. this.atNewLine = false;
  32116. this.atScalar = true;
  32117. this.type = 'scalar';
  32118. }
  32119. else {
  32120. this.type = type;
  32121. yield* this.step();
  32122. switch (type) {
  32123. case 'newline':
  32124. this.atNewLine = true;
  32125. this.indent = 0;
  32126. if (this.onNewLine)
  32127. this.onNewLine(this.offset + source.length);
  32128. break;
  32129. case 'space':
  32130. if (this.atNewLine && source[0] === ' ')
  32131. this.indent += source.length;
  32132. break;
  32133. case 'explicit-key-ind':
  32134. case 'map-value-ind':
  32135. case 'seq-item-ind':
  32136. if (this.atNewLine)
  32137. this.indent += source.length;
  32138. break;
  32139. case 'doc-mode':
  32140. case 'flow-error-end':
  32141. return;
  32142. default:
  32143. this.atNewLine = false;
  32144. }
  32145. this.offset += source.length;
  32146. }
  32147. }
  32148. /** Call at end of input to push out any remaining constructions */
  32149. *end() {
  32150. while (this.stack.length > 0)
  32151. yield* this.pop();
  32152. }
  32153. get sourceToken() {
  32154. const st = {
  32155. type: this.type,
  32156. offset: this.offset,
  32157. indent: this.indent,
  32158. source: this.source
  32159. };
  32160. return st;
  32161. }
  32162. *step() {
  32163. const top = this.peek(1);
  32164. if (this.type === 'doc-end' && (!top || top.type !== 'doc-end')) {
  32165. while (this.stack.length > 0)
  32166. yield* this.pop();
  32167. this.stack.push({
  32168. type: 'doc-end',
  32169. offset: this.offset,
  32170. source: this.source
  32171. });
  32172. return;
  32173. }
  32174. if (!top)
  32175. return yield* this.stream();
  32176. switch (top.type) {
  32177. case 'document':
  32178. return yield* this.document(top);
  32179. case 'alias':
  32180. case 'scalar':
  32181. case 'single-quoted-scalar':
  32182. case 'double-quoted-scalar':
  32183. return yield* this.scalar(top);
  32184. case 'block-scalar':
  32185. return yield* this.blockScalar(top);
  32186. case 'block-map':
  32187. return yield* this.blockMap(top);
  32188. case 'block-seq':
  32189. return yield* this.blockSequence(top);
  32190. case 'flow-collection':
  32191. return yield* this.flowCollection(top);
  32192. case 'doc-end':
  32193. return yield* this.documentEnd(top);
  32194. }
  32195. /* istanbul ignore next should not happen */
  32196. yield* this.pop();
  32197. }
  32198. peek(n) {
  32199. return this.stack[this.stack.length - n];
  32200. }
  32201. *pop(error) {
  32202. const token = error ?? this.stack.pop();
  32203. /* istanbul ignore if should not happen */
  32204. if (!token) {
  32205. const message = 'Tried to pop an empty stack';
  32206. yield { type: 'error', offset: this.offset, source: '', message };
  32207. }
  32208. else if (this.stack.length === 0) {
  32209. yield token;
  32210. }
  32211. else {
  32212. const top = this.peek(1);
  32213. if (token.type === 'block-scalar') {
  32214. // Block scalars use their parent rather than header indent
  32215. token.indent = 'indent' in top ? top.indent : 0;
  32216. }
  32217. else if (token.type === 'flow-collection' && top.type === 'document') {
  32218. // Ignore all indent for top-level flow collections
  32219. token.indent = 0;
  32220. }
  32221. if (token.type === 'flow-collection')
  32222. fixFlowSeqItems(token);
  32223. switch (top.type) {
  32224. case 'document':
  32225. top.value = token;
  32226. break;
  32227. case 'block-scalar':
  32228. top.props.push(token); // error
  32229. break;
  32230. case 'block-map': {
  32231. const it = top.items[top.items.length - 1];
  32232. if (it.value) {
  32233. top.items.push({ start: [], key: token, sep: [] });
  32234. this.onKeyLine = true;
  32235. return;
  32236. }
  32237. else if (it.sep) {
  32238. it.value = token;
  32239. }
  32240. else {
  32241. Object.assign(it, { key: token, sep: [] });
  32242. this.onKeyLine = !includesToken(it.start, 'explicit-key-ind');
  32243. return;
  32244. }
  32245. break;
  32246. }
  32247. case 'block-seq': {
  32248. const it = top.items[top.items.length - 1];
  32249. if (it.value)
  32250. top.items.push({ start: [], value: token });
  32251. else
  32252. it.value = token;
  32253. break;
  32254. }
  32255. case 'flow-collection': {
  32256. const it = top.items[top.items.length - 1];
  32257. if (!it || it.value)
  32258. top.items.push({ start: [], key: token, sep: [] });
  32259. else if (it.sep)
  32260. it.value = token;
  32261. else
  32262. Object.assign(it, { key: token, sep: [] });
  32263. return;
  32264. }
  32265. /* istanbul ignore next should not happen */
  32266. default:
  32267. yield* this.pop();
  32268. yield* this.pop(token);
  32269. }
  32270. if ((top.type === 'document' ||
  32271. top.type === 'block-map' ||
  32272. top.type === 'block-seq') &&
  32273. (token.type === 'block-map' || token.type === 'block-seq')) {
  32274. const last = token.items[token.items.length - 1];
  32275. if (last &&
  32276. !last.sep &&
  32277. !last.value &&
  32278. last.start.length > 0 &&
  32279. findNonEmptyIndex(last.start) === -1 &&
  32280. (token.indent === 0 ||
  32281. last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {
  32282. if (top.type === 'document')
  32283. top.end = last.start;
  32284. else
  32285. top.items.push({ start: last.start });
  32286. token.items.splice(-1, 1);
  32287. }
  32288. }
  32289. }
  32290. }
  32291. *stream() {
  32292. switch (this.type) {
  32293. case 'directive-line':
  32294. yield { type: 'directive', offset: this.offset, source: this.source };
  32295. return;
  32296. case 'byte-order-mark':
  32297. case 'space':
  32298. case 'comment':
  32299. case 'newline':
  32300. yield this.sourceToken;
  32301. return;
  32302. case 'doc-mode':
  32303. case 'doc-start': {
  32304. const doc = {
  32305. type: 'document',
  32306. offset: this.offset,
  32307. start: []
  32308. };
  32309. if (this.type === 'doc-start')
  32310. doc.start.push(this.sourceToken);
  32311. this.stack.push(doc);
  32312. return;
  32313. }
  32314. }
  32315. yield {
  32316. type: 'error',
  32317. offset: this.offset,
  32318. message: `Unexpected ${this.type} token in YAML stream`,
  32319. source: this.source
  32320. };
  32321. }
  32322. *document(doc) {
  32323. if (doc.value)
  32324. return yield* this.lineEnd(doc);
  32325. switch (this.type) {
  32326. case 'doc-start': {
  32327. if (findNonEmptyIndex(doc.start) !== -1) {
  32328. yield* this.pop();
  32329. yield* this.step();
  32330. }
  32331. else
  32332. doc.start.push(this.sourceToken);
  32333. return;
  32334. }
  32335. case 'anchor':
  32336. case 'tag':
  32337. case 'space':
  32338. case 'comment':
  32339. case 'newline':
  32340. doc.start.push(this.sourceToken);
  32341. return;
  32342. }
  32343. const bv = this.startBlockValue(doc);
  32344. if (bv)
  32345. this.stack.push(bv);
  32346. else {
  32347. yield {
  32348. type: 'error',
  32349. offset: this.offset,
  32350. message: `Unexpected ${this.type} token in YAML document`,
  32351. source: this.source
  32352. };
  32353. }
  32354. }
  32355. *scalar(scalar) {
  32356. if (this.type === 'map-value-ind') {
  32357. const prev = getPrevProps(this.peek(2));
  32358. const start = getFirstKeyStartProps(prev);
  32359. let sep;
  32360. if (scalar.end) {
  32361. sep = scalar.end;
  32362. sep.push(this.sourceToken);
  32363. delete scalar.end;
  32364. }
  32365. else
  32366. sep = [this.sourceToken];
  32367. const map = {
  32368. type: 'block-map',
  32369. offset: scalar.offset,
  32370. indent: scalar.indent,
  32371. items: [{ start, key: scalar, sep }]
  32372. };
  32373. this.onKeyLine = true;
  32374. this.stack[this.stack.length - 1] = map;
  32375. }
  32376. else
  32377. yield* this.lineEnd(scalar);
  32378. }
  32379. *blockScalar(scalar) {
  32380. switch (this.type) {
  32381. case 'space':
  32382. case 'comment':
  32383. case 'newline':
  32384. scalar.props.push(this.sourceToken);
  32385. return;
  32386. case 'scalar':
  32387. scalar.source = this.source;
  32388. // block-scalar source includes trailing newline
  32389. this.atNewLine = true;
  32390. this.indent = 0;
  32391. if (this.onNewLine) {
  32392. let nl = this.source.indexOf('\n') + 1;
  32393. while (nl !== 0) {
  32394. this.onNewLine(this.offset + nl);
  32395. nl = this.source.indexOf('\n', nl) + 1;
  32396. }
  32397. }
  32398. yield* this.pop();
  32399. break;
  32400. /* istanbul ignore next should not happen */
  32401. default:
  32402. yield* this.pop();
  32403. yield* this.step();
  32404. }
  32405. }
  32406. *blockMap(map) {
  32407. const it = map.items[map.items.length - 1];
  32408. // it.sep is true-ish if pair already has key or : separator
  32409. switch (this.type) {
  32410. case 'newline':
  32411. this.onKeyLine = false;
  32412. if (it.value) {
  32413. const end = 'end' in it.value ? it.value.end : undefined;
  32414. const last = Array.isArray(end) ? end[end.length - 1] : undefined;
  32415. if (last?.type === 'comment')
  32416. end?.push(this.sourceToken);
  32417. else
  32418. map.items.push({ start: [this.sourceToken] });
  32419. }
  32420. else if (it.sep) {
  32421. it.sep.push(this.sourceToken);
  32422. }
  32423. else {
  32424. it.start.push(this.sourceToken);
  32425. }
  32426. return;
  32427. case 'space':
  32428. case 'comment':
  32429. if (it.value) {
  32430. map.items.push({ start: [this.sourceToken] });
  32431. }
  32432. else if (it.sep) {
  32433. it.sep.push(this.sourceToken);
  32434. }
  32435. else {
  32436. if (this.atIndentedComment(it.start, map.indent)) {
  32437. const prev = map.items[map.items.length - 2];
  32438. const end = prev?.value?.end;
  32439. if (Array.isArray(end)) {
  32440. Array.prototype.push.apply(end, it.start);
  32441. end.push(this.sourceToken);
  32442. map.items.pop();
  32443. return;
  32444. }
  32445. }
  32446. it.start.push(this.sourceToken);
  32447. }
  32448. return;
  32449. }
  32450. if (this.indent >= map.indent) {
  32451. const atNextItem = !this.onKeyLine && this.indent === map.indent && it.sep;
  32452. // For empty nodes, assign newline-separated not indented empty tokens to following node
  32453. let start = [];
  32454. if (atNextItem && it.sep && !it.value) {
  32455. const nl = [];
  32456. for (let i = 0; i < it.sep.length; ++i) {
  32457. const st = it.sep[i];
  32458. switch (st.type) {
  32459. case 'newline':
  32460. nl.push(i);
  32461. break;
  32462. case 'space':
  32463. break;
  32464. case 'comment':
  32465. if (st.indent > map.indent)
  32466. nl.length = 0;
  32467. break;
  32468. default:
  32469. nl.length = 0;
  32470. }
  32471. }
  32472. if (nl.length >= 2)
  32473. start = it.sep.splice(nl[1]);
  32474. }
  32475. switch (this.type) {
  32476. case 'anchor':
  32477. case 'tag':
  32478. if (atNextItem || it.value) {
  32479. start.push(this.sourceToken);
  32480. map.items.push({ start });
  32481. this.onKeyLine = true;
  32482. }
  32483. else if (it.sep) {
  32484. it.sep.push(this.sourceToken);
  32485. }
  32486. else {
  32487. it.start.push(this.sourceToken);
  32488. }
  32489. return;
  32490. case 'explicit-key-ind':
  32491. if (!it.sep && !includesToken(it.start, 'explicit-key-ind')) {
  32492. it.start.push(this.sourceToken);
  32493. }
  32494. else if (atNextItem || it.value) {
  32495. start.push(this.sourceToken);
  32496. map.items.push({ start });
  32497. }
  32498. else {
  32499. this.stack.push({
  32500. type: 'block-map',
  32501. offset: this.offset,
  32502. indent: this.indent,
  32503. items: [{ start: [this.sourceToken] }]
  32504. });
  32505. }
  32506. this.onKeyLine = true;
  32507. return;
  32508. case 'map-value-ind':
  32509. if (includesToken(it.start, 'explicit-key-ind')) {
  32510. if (!it.sep) {
  32511. if (includesToken(it.start, 'newline')) {
  32512. Object.assign(it, { key: null, sep: [this.sourceToken] });
  32513. }
  32514. else {
  32515. const start = getFirstKeyStartProps(it.start);
  32516. this.stack.push({
  32517. type: 'block-map',
  32518. offset: this.offset,
  32519. indent: this.indent,
  32520. items: [{ start, key: null, sep: [this.sourceToken] }]
  32521. });
  32522. }
  32523. }
  32524. else if (it.value) {
  32525. map.items.push({ start: [], key: null, sep: [this.sourceToken] });
  32526. }
  32527. else if (includesToken(it.sep, 'map-value-ind')) {
  32528. this.stack.push({
  32529. type: 'block-map',
  32530. offset: this.offset,
  32531. indent: this.indent,
  32532. items: [{ start, key: null, sep: [this.sourceToken] }]
  32533. });
  32534. }
  32535. else if (isFlowToken(it.key) &&
  32536. !includesToken(it.sep, 'newline')) {
  32537. const start = getFirstKeyStartProps(it.start);
  32538. const key = it.key;
  32539. const sep = it.sep;
  32540. sep.push(this.sourceToken);
  32541. // @ts-expect-error type guard is wrong here
  32542. delete it.key, delete it.sep;
  32543. this.stack.push({
  32544. type: 'block-map',
  32545. offset: this.offset,
  32546. indent: this.indent,
  32547. items: [{ start, key, sep }]
  32548. });
  32549. }
  32550. else if (start.length > 0) {
  32551. // Not actually at next item
  32552. it.sep = it.sep.concat(start, this.sourceToken);
  32553. }
  32554. else {
  32555. it.sep.push(this.sourceToken);
  32556. }
  32557. }
  32558. else {
  32559. if (!it.sep) {
  32560. Object.assign(it, { key: null, sep: [this.sourceToken] });
  32561. }
  32562. else if (it.value || atNextItem) {
  32563. map.items.push({ start, key: null, sep: [this.sourceToken] });
  32564. }
  32565. else if (includesToken(it.sep, 'map-value-ind')) {
  32566. this.stack.push({
  32567. type: 'block-map',
  32568. offset: this.offset,
  32569. indent: this.indent,
  32570. items: [{ start: [], key: null, sep: [this.sourceToken] }]
  32571. });
  32572. }
  32573. else {
  32574. it.sep.push(this.sourceToken);
  32575. }
  32576. }
  32577. this.onKeyLine = true;
  32578. return;
  32579. case 'alias':
  32580. case 'scalar':
  32581. case 'single-quoted-scalar':
  32582. case 'double-quoted-scalar': {
  32583. const fs = this.flowScalar(this.type);
  32584. if (atNextItem || it.value) {
  32585. map.items.push({ start, key: fs, sep: [] });
  32586. this.onKeyLine = true;
  32587. }
  32588. else if (it.sep) {
  32589. this.stack.push(fs);
  32590. }
  32591. else {
  32592. Object.assign(it, { key: fs, sep: [] });
  32593. this.onKeyLine = true;
  32594. }
  32595. return;
  32596. }
  32597. default: {
  32598. const bv = this.startBlockValue(map);
  32599. if (bv) {
  32600. if (atNextItem &&
  32601. bv.type !== 'block-seq' &&
  32602. includesToken(it.start, 'explicit-key-ind')) {
  32603. map.items.push({ start });
  32604. }
  32605. this.stack.push(bv);
  32606. return;
  32607. }
  32608. }
  32609. }
  32610. }
  32611. yield* this.pop();
  32612. yield* this.step();
  32613. }
  32614. *blockSequence(seq) {
  32615. const it = seq.items[seq.items.length - 1];
  32616. switch (this.type) {
  32617. case 'newline':
  32618. if (it.value) {
  32619. const end = 'end' in it.value ? it.value.end : undefined;
  32620. const last = Array.isArray(end) ? end[end.length - 1] : undefined;
  32621. if (last?.type === 'comment')
  32622. end?.push(this.sourceToken);
  32623. else
  32624. seq.items.push({ start: [this.sourceToken] });
  32625. }
  32626. else
  32627. it.start.push(this.sourceToken);
  32628. return;
  32629. case 'space':
  32630. case 'comment':
  32631. if (it.value)
  32632. seq.items.push({ start: [this.sourceToken] });
  32633. else {
  32634. if (this.atIndentedComment(it.start, seq.indent)) {
  32635. const prev = seq.items[seq.items.length - 2];
  32636. const end = prev?.value?.end;
  32637. if (Array.isArray(end)) {
  32638. Array.prototype.push.apply(end, it.start);
  32639. end.push(this.sourceToken);
  32640. seq.items.pop();
  32641. return;
  32642. }
  32643. }
  32644. it.start.push(this.sourceToken);
  32645. }
  32646. return;
  32647. case 'anchor':
  32648. case 'tag':
  32649. if (it.value || this.indent <= seq.indent)
  32650. break;
  32651. it.start.push(this.sourceToken);
  32652. return;
  32653. case 'seq-item-ind':
  32654. if (this.indent !== seq.indent)
  32655. break;
  32656. if (it.value || includesToken(it.start, 'seq-item-ind'))
  32657. seq.items.push({ start: [this.sourceToken] });
  32658. else
  32659. it.start.push(this.sourceToken);
  32660. return;
  32661. }
  32662. if (this.indent > seq.indent) {
  32663. const bv = this.startBlockValue(seq);
  32664. if (bv) {
  32665. this.stack.push(bv);
  32666. return;
  32667. }
  32668. }
  32669. yield* this.pop();
  32670. yield* this.step();
  32671. }
  32672. *flowCollection(fc) {
  32673. const it = fc.items[fc.items.length - 1];
  32674. if (this.type === 'flow-error-end') {
  32675. let top;
  32676. do {
  32677. yield* this.pop();
  32678. top = this.peek(1);
  32679. } while (top && top.type === 'flow-collection');
  32680. }
  32681. else if (fc.end.length === 0) {
  32682. switch (this.type) {
  32683. case 'comma':
  32684. case 'explicit-key-ind':
  32685. if (!it || it.sep)
  32686. fc.items.push({ start: [this.sourceToken] });
  32687. else
  32688. it.start.push(this.sourceToken);
  32689. return;
  32690. case 'map-value-ind':
  32691. if (!it || it.value)
  32692. fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
  32693. else if (it.sep)
  32694. it.sep.push(this.sourceToken);
  32695. else
  32696. Object.assign(it, { key: null, sep: [this.sourceToken] });
  32697. return;
  32698. case 'space':
  32699. case 'comment':
  32700. case 'newline':
  32701. case 'anchor':
  32702. case 'tag':
  32703. if (!it || it.value)
  32704. fc.items.push({ start: [this.sourceToken] });
  32705. else if (it.sep)
  32706. it.sep.push(this.sourceToken);
  32707. else
  32708. it.start.push(this.sourceToken);
  32709. return;
  32710. case 'alias':
  32711. case 'scalar':
  32712. case 'single-quoted-scalar':
  32713. case 'double-quoted-scalar': {
  32714. const fs = this.flowScalar(this.type);
  32715. if (!it || it.value)
  32716. fc.items.push({ start: [], key: fs, sep: [] });
  32717. else if (it.sep)
  32718. this.stack.push(fs);
  32719. else
  32720. Object.assign(it, { key: fs, sep: [] });
  32721. return;
  32722. }
  32723. case 'flow-map-end':
  32724. case 'flow-seq-end':
  32725. fc.end.push(this.sourceToken);
  32726. return;
  32727. }
  32728. const bv = this.startBlockValue(fc);
  32729. /* istanbul ignore else should not happen */
  32730. if (bv)
  32731. this.stack.push(bv);
  32732. else {
  32733. yield* this.pop();
  32734. yield* this.step();
  32735. }
  32736. }
  32737. else {
  32738. const parent = this.peek(2);
  32739. if (parent.type === 'block-map' &&
  32740. ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||
  32741. (this.type === 'newline' &&
  32742. !parent.items[parent.items.length - 1].sep))) {
  32743. yield* this.pop();
  32744. yield* this.step();
  32745. }
  32746. else if (this.type === 'map-value-ind' &&
  32747. parent.type !== 'flow-collection') {
  32748. const prev = getPrevProps(parent);
  32749. const start = getFirstKeyStartProps(prev);
  32750. fixFlowSeqItems(fc);
  32751. const sep = fc.end.splice(1, fc.end.length);
  32752. sep.push(this.sourceToken);
  32753. const map = {
  32754. type: 'block-map',
  32755. offset: fc.offset,
  32756. indent: fc.indent,
  32757. items: [{ start, key: fc, sep }]
  32758. };
  32759. this.onKeyLine = true;
  32760. this.stack[this.stack.length - 1] = map;
  32761. }
  32762. else {
  32763. yield* this.lineEnd(fc);
  32764. }
  32765. }
  32766. }
  32767. flowScalar(type) {
  32768. if (this.onNewLine) {
  32769. let nl = this.source.indexOf('\n') + 1;
  32770. while (nl !== 0) {
  32771. this.onNewLine(this.offset + nl);
  32772. nl = this.source.indexOf('\n', nl) + 1;
  32773. }
  32774. }
  32775. return {
  32776. type,
  32777. offset: this.offset,
  32778. indent: this.indent,
  32779. source: this.source
  32780. };
  32781. }
  32782. startBlockValue(parent) {
  32783. switch (this.type) {
  32784. case 'alias':
  32785. case 'scalar':
  32786. case 'single-quoted-scalar':
  32787. case 'double-quoted-scalar':
  32788. return this.flowScalar(this.type);
  32789. case 'block-scalar-header':
  32790. return {
  32791. type: 'block-scalar',
  32792. offset: this.offset,
  32793. indent: this.indent,
  32794. props: [this.sourceToken],
  32795. source: ''
  32796. };
  32797. case 'flow-map-start':
  32798. case 'flow-seq-start':
  32799. return {
  32800. type: 'flow-collection',
  32801. offset: this.offset,
  32802. indent: this.indent,
  32803. start: this.sourceToken,
  32804. items: [],
  32805. end: []
  32806. };
  32807. case 'seq-item-ind':
  32808. return {
  32809. type: 'block-seq',
  32810. offset: this.offset,
  32811. indent: this.indent,
  32812. items: [{ start: [this.sourceToken] }]
  32813. };
  32814. case 'explicit-key-ind': {
  32815. this.onKeyLine = true;
  32816. const prev = getPrevProps(parent);
  32817. const start = getFirstKeyStartProps(prev);
  32818. start.push(this.sourceToken);
  32819. return {
  32820. type: 'block-map',
  32821. offset: this.offset,
  32822. indent: this.indent,
  32823. items: [{ start }]
  32824. };
  32825. }
  32826. case 'map-value-ind': {
  32827. this.onKeyLine = true;
  32828. const prev = getPrevProps(parent);
  32829. const start = getFirstKeyStartProps(prev);
  32830. return {
  32831. type: 'block-map',
  32832. offset: this.offset,
  32833. indent: this.indent,
  32834. items: [{ start, key: null, sep: [this.sourceToken] }]
  32835. };
  32836. }
  32837. }
  32838. return null;
  32839. }
  32840. atIndentedComment(start, indent) {
  32841. if (this.type !== 'comment')
  32842. return false;
  32843. if (this.indent <= indent)
  32844. return false;
  32845. return start.every(st => st.type === 'newline' || st.type === 'space');
  32846. }
  32847. *documentEnd(docEnd) {
  32848. if (this.type !== 'doc-mode') {
  32849. if (docEnd.end)
  32850. docEnd.end.push(this.sourceToken);
  32851. else
  32852. docEnd.end = [this.sourceToken];
  32853. if (this.type === 'newline')
  32854. yield* this.pop();
  32855. }
  32856. }
  32857. *lineEnd(token) {
  32858. switch (this.type) {
  32859. case 'comma':
  32860. case 'doc-start':
  32861. case 'doc-end':
  32862. case 'flow-seq-end':
  32863. case 'flow-map-end':
  32864. case 'map-value-ind':
  32865. yield* this.pop();
  32866. yield* this.step();
  32867. break;
  32868. case 'newline':
  32869. this.onKeyLine = false;
  32870. // fallthrough
  32871. case 'space':
  32872. case 'comment':
  32873. default:
  32874. // all other values are errors
  32875. if (token.end)
  32876. token.end.push(this.sourceToken);
  32877. else
  32878. token.end = [this.sourceToken];
  32879. if (this.type === 'newline')
  32880. yield* this.pop();
  32881. }
  32882. }
  32883. }
  32884. function parseOptions(options) {
  32885. const prettyErrors = options.prettyErrors !== false;
  32886. const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null;
  32887. return { lineCounter, prettyErrors };
  32888. }
  32889. /**
  32890. * Parse the input as a stream of YAML documents.
  32891. *
  32892. * Documents should be separated from each other by `...` or `---` marker lines.
  32893. *
  32894. * @returns If an empty `docs` array is returned, it will be of type
  32895. * EmptyStream and contain additional stream information. In
  32896. * TypeScript, you should use `'empty' in docs` as a type guard for it.
  32897. */
  32898. function parseAllDocuments(source, options = {}) {
  32899. const { lineCounter, prettyErrors } = parseOptions(options);
  32900. const parser = new Parser(lineCounter?.addNewLine);
  32901. const composer = new Composer(options);
  32902. const docs = Array.from(composer.compose(parser.parse(source)));
  32903. if (prettyErrors && lineCounter)
  32904. for (const doc of docs) {
  32905. doc.errors.forEach(prettifyError(source, lineCounter));
  32906. doc.warnings.forEach(prettifyError(source, lineCounter));
  32907. }
  32908. if (docs.length > 0)
  32909. return docs;
  32910. return Object.assign([], { empty: true }, composer.streamInfo());
  32911. }
  32912. /** Parse an input string into a single YAML.Document */
  32913. function parseDocument(source, options = {}) {
  32914. const { lineCounter, prettyErrors } = parseOptions(options);
  32915. const parser = new Parser(lineCounter?.addNewLine);
  32916. const composer = new Composer(options);
  32917. // `doc` is always set by compose.end(true) at the very latest
  32918. let doc = null;
  32919. for (const _doc of composer.compose(parser.parse(source), true, source.length)) {
  32920. if (!doc)
  32921. doc = _doc;
  32922. else if (doc.options.logLevel !== 'silent') {
  32923. doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));
  32924. break;
  32925. }
  32926. }
  32927. if (prettyErrors && lineCounter) {
  32928. doc.errors.forEach(prettifyError(source, lineCounter));
  32929. doc.warnings.forEach(prettifyError(source, lineCounter));
  32930. }
  32931. return doc;
  32932. }
  32933. function parse$a(src, reviver, options) {
  32934. let _reviver = undefined;
  32935. if (typeof reviver === 'function') {
  32936. _reviver = reviver;
  32937. }
  32938. else if (options === undefined && reviver && typeof reviver === 'object') {
  32939. options = reviver;
  32940. }
  32941. const doc = parseDocument(src, options);
  32942. if (!doc)
  32943. return null;
  32944. doc.warnings.forEach(warning => warn(doc.options.logLevel, warning));
  32945. if (doc.errors.length > 0) {
  32946. if (doc.options.logLevel !== 'silent')
  32947. throw doc.errors[0];
  32948. else
  32949. doc.errors = [];
  32950. }
  32951. return doc.toJS(Object.assign({ reviver: _reviver }, options));
  32952. }
  32953. function stringify(value, replacer, options) {
  32954. let _replacer = null;
  32955. if (typeof replacer === 'function' || Array.isArray(replacer)) {
  32956. _replacer = replacer;
  32957. }
  32958. else if (options === undefined && replacer) {
  32959. options = replacer;
  32960. }
  32961. if (typeof options === 'string')
  32962. options = options.length;
  32963. if (typeof options === 'number') {
  32964. const indent = Math.round(options);
  32965. options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
  32966. }
  32967. if (value === undefined) {
  32968. const { keepUndefined } = options ?? replacer ?? {};
  32969. if (!keepUndefined)
  32970. return undefined;
  32971. }
  32972. return new Document(value, _replacer, options).toString(options);
  32973. }
  32974. var YAML = {
  32975. __proto__: null,
  32976. Alias: Alias,
  32977. CST: cst,
  32978. Composer: Composer,
  32979. Document: Document,
  32980. Lexer: Lexer,
  32981. LineCounter: LineCounter,
  32982. Pair: Pair,
  32983. Parser: Parser,
  32984. Scalar: Scalar,
  32985. Schema: Schema,
  32986. YAMLError: YAMLError,
  32987. YAMLMap: YAMLMap,
  32988. YAMLParseError: YAMLParseError,
  32989. YAMLSeq: YAMLSeq,
  32990. YAMLWarning: YAMLWarning,
  32991. isAlias: isAlias,
  32992. isCollection: isCollection$1,
  32993. isDocument: isDocument,
  32994. isMap: isMap,
  32995. isNode: isNode$1,
  32996. isPair: isPair,
  32997. isScalar: isScalar$1,
  32998. isSeq: isSeq,
  32999. parse: parse$a,
  33000. parseAllDocuments: parseAllDocuments,
  33001. parseDocument: parseDocument,
  33002. stringify: stringify,
  33003. visit: visit$1,
  33004. visitAsync: visitAsync
  33005. };
  33006. // `export * as default from ...` fails on Webpack v4
  33007. var browser$1 = {
  33008. __proto__: null,
  33009. Alias: Alias,
  33010. CST: cst,
  33011. Composer: Composer,
  33012. Document: Document,
  33013. Lexer: Lexer,
  33014. LineCounter: LineCounter,
  33015. Pair: Pair,
  33016. Parser: Parser,
  33017. Scalar: Scalar,
  33018. Schema: Schema,
  33019. YAMLError: YAMLError,
  33020. YAMLMap: YAMLMap,
  33021. YAMLParseError: YAMLParseError,
  33022. YAMLSeq: YAMLSeq,
  33023. YAMLWarning: YAMLWarning,
  33024. default: YAML,
  33025. isAlias: isAlias,
  33026. isCollection: isCollection$1,
  33027. isDocument: isDocument,
  33028. isMap: isMap,
  33029. isNode: isNode$1,
  33030. isPair: isPair,
  33031. isScalar: isScalar$1,
  33032. isSeq: isSeq,
  33033. parse: parse$a,
  33034. parseAllDocuments: parseAllDocuments,
  33035. parseDocument: parseDocument,
  33036. stringify: stringify,
  33037. visit: visit$1,
  33038. visitAsync: visitAsync
  33039. };
  33040. var require$$3$1 = /*@__PURE__*/getAugmentedNamespace(browser$1);
  33041. // eslint-disable-next-line n/no-deprecated-api
  33042. const { createRequire, createRequireFromPath } = require$$0$8;
  33043. function req$2 (name, rootFile) {
  33044. const create = createRequire || createRequireFromPath;
  33045. const require = create(rootFile);
  33046. return require(name)
  33047. }
  33048. var req_1 = req$2;
  33049. const req$1 = req_1;
  33050. /**
  33051. * Load Options
  33052. *
  33053. * @private
  33054. * @method options
  33055. *
  33056. * @param {Object} config PostCSS Config
  33057. *
  33058. * @return {Object} options PostCSS Options
  33059. */
  33060. const options = (config, file) => {
  33061. if (config.parser && typeof config.parser === 'string') {
  33062. try {
  33063. config.parser = req$1(config.parser, file);
  33064. } catch (err) {
  33065. throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`)
  33066. }
  33067. }
  33068. if (config.syntax && typeof config.syntax === 'string') {
  33069. try {
  33070. config.syntax = req$1(config.syntax, file);
  33071. } catch (err) {
  33072. throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`)
  33073. }
  33074. }
  33075. if (config.stringifier && typeof config.stringifier === 'string') {
  33076. try {
  33077. config.stringifier = req$1(config.stringifier, file);
  33078. } catch (err) {
  33079. throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`)
  33080. }
  33081. }
  33082. if (config.plugins) {
  33083. delete config.plugins;
  33084. }
  33085. return config
  33086. };
  33087. var options_1 = options;
  33088. const req = req_1;
  33089. /**
  33090. * Plugin Loader
  33091. *
  33092. * @private
  33093. * @method load
  33094. *
  33095. * @param {String} plugin PostCSS Plugin Name
  33096. * @param {Object} options PostCSS Plugin Options
  33097. *
  33098. * @return {Function} PostCSS Plugin
  33099. */
  33100. const load = (plugin, options, file) => {
  33101. try {
  33102. if (
  33103. options === null ||
  33104. options === undefined ||
  33105. Object.keys(options).length === 0
  33106. ) {
  33107. return req(plugin, file)
  33108. } else {
  33109. return req(plugin, file)(options)
  33110. }
  33111. } catch (err) {
  33112. throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`)
  33113. }
  33114. };
  33115. /**
  33116. * Load Plugins
  33117. *
  33118. * @private
  33119. * @method plugins
  33120. *
  33121. * @param {Object} config PostCSS Config Plugins
  33122. *
  33123. * @return {Array} plugins PostCSS Plugins
  33124. */
  33125. const plugins = (config, file) => {
  33126. let plugins = [];
  33127. if (Array.isArray(config.plugins)) {
  33128. plugins = config.plugins.filter(Boolean);
  33129. } else {
  33130. plugins = Object.keys(config.plugins)
  33131. .filter((plugin) => {
  33132. return config.plugins[plugin] !== false ? plugin : ''
  33133. })
  33134. .map((plugin) => {
  33135. return load(plugin, config.plugins[plugin], file)
  33136. });
  33137. }
  33138. if (plugins.length && plugins.length > 0) {
  33139. plugins.forEach((plugin, i) => {
  33140. if (plugin.default) {
  33141. plugin = plugin.default;
  33142. }
  33143. if (plugin.postcss === true) {
  33144. plugin = plugin();
  33145. } else if (plugin.postcss) {
  33146. plugin = plugin.postcss;
  33147. }
  33148. if (
  33149. // eslint-disable-next-line
  33150. !(
  33151. (typeof plugin === 'object' && Array.isArray(plugin.plugins)) ||
  33152. (typeof plugin === 'object' && plugin.postcssPlugin) ||
  33153. (typeof plugin === 'function')
  33154. )
  33155. ) {
  33156. throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`)
  33157. }
  33158. });
  33159. }
  33160. return plugins
  33161. };
  33162. var plugins_1 = plugins;
  33163. const resolve = require$$0$4.resolve;
  33164. const url$4 = require$$0$9;
  33165. const config$1 = dist;
  33166. const yaml = require$$3$1;
  33167. const loadOptions = options_1;
  33168. const loadPlugins = plugins_1;
  33169. /* istanbul ignore next */
  33170. const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
  33171. /**
  33172. * Process the result from cosmiconfig
  33173. *
  33174. * @param {Object} ctx Config Context
  33175. * @param {Object} result Cosmiconfig result
  33176. *
  33177. * @return {Object} PostCSS Config
  33178. */
  33179. const processResult = (ctx, result) => {
  33180. const file = result.filepath || '';
  33181. let config = interopRequireDefault(result.config).default || {};
  33182. if (typeof config === 'function') {
  33183. config = config(ctx);
  33184. } else {
  33185. config = Object.assign({}, config, ctx);
  33186. }
  33187. if (!config.plugins) {
  33188. config.plugins = [];
  33189. }
  33190. return {
  33191. plugins: loadPlugins(config, file),
  33192. options: loadOptions(config, file),
  33193. file
  33194. }
  33195. };
  33196. /**
  33197. * Builds the Config Context
  33198. *
  33199. * @param {Object} ctx Config Context
  33200. *
  33201. * @return {Object} Config Context
  33202. */
  33203. const createContext = (ctx) => {
  33204. /**
  33205. * @type {Object}
  33206. *
  33207. * @prop {String} cwd=process.cwd() Config search start location
  33208. * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined`
  33209. */
  33210. ctx = Object.assign({
  33211. cwd: process.cwd(),
  33212. env: process.env.NODE_ENV
  33213. }, ctx);
  33214. if (!ctx.env) {
  33215. process.env.NODE_ENV = 'development';
  33216. }
  33217. return ctx
  33218. };
  33219. const importDefault = async filepath => {
  33220. const module = await import(url$4.pathToFileURL(filepath).href);
  33221. return module.default
  33222. };
  33223. const addTypeScriptLoader = (options = {}, loader) => {
  33224. const moduleName = 'postcss';
  33225. return {
  33226. ...options,
  33227. searchPlaces: [
  33228. ...(options.searchPlaces || []),
  33229. 'package.json',
  33230. `.${moduleName}rc`,
  33231. `.${moduleName}rc.json`,
  33232. `.${moduleName}rc.yaml`,
  33233. `.${moduleName}rc.yml`,
  33234. `.${moduleName}rc.ts`,
  33235. `.${moduleName}rc.js`,
  33236. `.${moduleName}rc.cjs`,
  33237. `.${moduleName}rc.mjs`,
  33238. `${moduleName}.config.ts`,
  33239. `${moduleName}.config.js`,
  33240. `${moduleName}.config.cjs`,
  33241. `${moduleName}.config.mjs`
  33242. ],
  33243. loaders: {
  33244. ...options.loaders,
  33245. '.yaml': (filepath, content) => yaml.parse(content),
  33246. '.yml': (filepath, content) => yaml.parse(content),
  33247. '.js': importDefault,
  33248. '.cjs': importDefault,
  33249. '.mjs': importDefault,
  33250. '.ts': loader
  33251. }
  33252. }
  33253. };
  33254. const withTypeScriptLoader = (rcFunc) => {
  33255. return (ctx, path, options) => {
  33256. return rcFunc(ctx, path, addTypeScriptLoader(options, (configFile) => {
  33257. let registerer = { enabled () {} };
  33258. try {
  33259. // Register TypeScript compiler instance
  33260. registerer = __require('ts-node').register();
  33261. return __require(configFile)
  33262. } catch (err) {
  33263. if (err.code === 'MODULE_NOT_FOUND') {
  33264. throw new Error(
  33265. `'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${err.message}`
  33266. )
  33267. }
  33268. throw err
  33269. } finally {
  33270. registerer.enabled(false);
  33271. }
  33272. }))
  33273. }
  33274. };
  33275. /**
  33276. * Load Config
  33277. *
  33278. * @method rc
  33279. *
  33280. * @param {Object} ctx Config Context
  33281. * @param {String} path Config Path
  33282. * @param {Object} options Config Options
  33283. *
  33284. * @return {Promise} config PostCSS Config
  33285. */
  33286. const rc = withTypeScriptLoader((ctx, path, options) => {
  33287. /**
  33288. * @type {Object} The full Config Context
  33289. */
  33290. ctx = createContext(ctx);
  33291. /**
  33292. * @type {String} `process.cwd()`
  33293. */
  33294. path = path ? resolve(path) : process.cwd();
  33295. return config$1.lilconfig('postcss', options)
  33296. .search(path)
  33297. .then((result) => {
  33298. if (!result) {
  33299. throw new Error(`No PostCSS Config found in: ${path}`)
  33300. }
  33301. return processResult(ctx, result)
  33302. })
  33303. });
  33304. /**
  33305. * Autoload Config for PostCSS
  33306. *
  33307. * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
  33308. * @license MIT
  33309. *
  33310. * @module postcss-load-config
  33311. * @version 2.1.0
  33312. *
  33313. * @requires comsiconfig
  33314. * @requires ./options
  33315. * @requires ./plugins
  33316. */
  33317. var src$1 = rc;
  33318. var postcssrc = /*@__PURE__*/getDefaultExportFromCjs(src$1);
  33319. function stripLiteralAcorn(code) {
  33320. const FILL = " ";
  33321. let result = "";
  33322. function fulfill(index) {
  33323. if (index > result.length)
  33324. result += code.slice(result.length, index).replace(/[^\n]/g, FILL);
  33325. }
  33326. const tokens = tokenizer(code, {
  33327. ecmaVersion: "latest",
  33328. sourceType: "module",
  33329. allowHashBang: true,
  33330. allowAwaitOutsideFunction: true,
  33331. allowImportExportEverywhere: true
  33332. });
  33333. const inter = tokens[Symbol.iterator]();
  33334. while (true) {
  33335. const { done, value: token } = inter.next();
  33336. if (done)
  33337. break;
  33338. fulfill(token.start);
  33339. if (token.type.label === "string")
  33340. result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1];
  33341. else if (token.type.label === "template")
  33342. result += FILL.repeat(token.end - token.start);
  33343. else
  33344. result += code.slice(token.start, token.end);
  33345. }
  33346. fulfill(code.length);
  33347. return result;
  33348. }
  33349. const multilineCommentsRE = /\/\*([^*\/])*?\*\//gms;
  33350. const singlelineCommentsRE = /(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/gm;
  33351. const templateLiteralRE = /\$\{(\s*(?:(?!\$\{).|\n|\r)*?\s*)\}/g;
  33352. const quotesRE = [
  33353. /(["'`])((?:\\\1|(?!\1)|.|\r)*?)\1/gm,
  33354. /([`])((?:\\\1|(?!\1)|.|\n|\r)*?)\1/gm
  33355. // multi-line strings (i.e. template literals only)
  33356. ];
  33357. function stripLiteralRegex(code) {
  33358. code = code.replace(multilineCommentsRE, (s) => " ".repeat(s.length)).replace(singlelineCommentsRE, (s) => " ".repeat(s.length));
  33359. let expanded = code;
  33360. for (let i = 0; i < 16; i++) {
  33361. const before = expanded;
  33362. expanded = expanded.replace(templateLiteralRE, "` $1`");
  33363. if (expanded === before)
  33364. break;
  33365. }
  33366. quotesRE.forEach((re) => {
  33367. expanded = expanded.replace(re, (s, quote, body, index) => {
  33368. code = code.slice(0, index + 1) + " ".repeat(s.length - 2) + code.slice(index + s.length - 1);
  33369. return quote + " ".repeat(s.length - 2) + quote;
  33370. });
  33371. });
  33372. return code;
  33373. }
  33374. function stripLiteral(code) {
  33375. try {
  33376. return stripLiteralAcorn(code);
  33377. } catch (e) {
  33378. return stripLiteralRegex(code);
  33379. }
  33380. }
  33381. var main$1 = {exports: {}};
  33382. var name = "dotenv";
  33383. var version$1 = "16.0.3";
  33384. var description = "Loads environment variables from .env file";
  33385. var main = "lib/main.js";
  33386. var types = "lib/main.d.ts";
  33387. var exports = {
  33388. ".": {
  33389. require: "./lib/main.js",
  33390. types: "./lib/main.d.ts",
  33391. "default": "./lib/main.js"
  33392. },
  33393. "./config": "./config.js",
  33394. "./config.js": "./config.js",
  33395. "./lib/env-options": "./lib/env-options.js",
  33396. "./lib/env-options.js": "./lib/env-options.js",
  33397. "./lib/cli-options": "./lib/cli-options.js",
  33398. "./lib/cli-options.js": "./lib/cli-options.js",
  33399. "./package.json": "./package.json"
  33400. };
  33401. var scripts = {
  33402. "dts-check": "tsc --project tests/types/tsconfig.json",
  33403. lint: "standard",
  33404. "lint-readme": "standard-markdown",
  33405. pretest: "npm run lint && npm run dts-check",
  33406. test: "tap tests/*.js --100 -Rspec",
  33407. prerelease: "npm test",
  33408. release: "standard-version"
  33409. };
  33410. var repository = {
  33411. type: "git",
  33412. url: "git://github.com/motdotla/dotenv.git"
  33413. };
  33414. var keywords = [
  33415. "dotenv",
  33416. "env",
  33417. ".env",
  33418. "environment",
  33419. "variables",
  33420. "config",
  33421. "settings"
  33422. ];
  33423. var readmeFilename = "README.md";
  33424. var license = "BSD-2-Clause";
  33425. var devDependencies = {
  33426. "@types/node": "^17.0.9",
  33427. decache: "^4.6.1",
  33428. dtslint: "^3.7.0",
  33429. sinon: "^12.0.1",
  33430. standard: "^16.0.4",
  33431. "standard-markdown": "^7.1.0",
  33432. "standard-version": "^9.3.2",
  33433. tap: "^15.1.6",
  33434. tar: "^6.1.11",
  33435. typescript: "^4.5.4"
  33436. };
  33437. var engines = {
  33438. node: ">=12"
  33439. };
  33440. var require$$3 = {
  33441. name: name,
  33442. version: version$1,
  33443. description: description,
  33444. main: main,
  33445. types: types,
  33446. exports: exports,
  33447. scripts: scripts,
  33448. repository: repository,
  33449. keywords: keywords,
  33450. readmeFilename: readmeFilename,
  33451. license: license,
  33452. devDependencies: devDependencies,
  33453. engines: engines
  33454. };
  33455. const fs$9 = require$$0__default;
  33456. const path$9 = require$$0$4;
  33457. const os$2 = require$$2;
  33458. const packageJson = require$$3;
  33459. const version = packageJson.version;
  33460. const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
  33461. // Parser src into an Object
  33462. function parse$9 (src) {
  33463. const obj = {};
  33464. // Convert buffer to string
  33465. let lines = src.toString();
  33466. // Convert line breaks to same format
  33467. lines = lines.replace(/\r\n?/mg, '\n');
  33468. let match;
  33469. while ((match = LINE.exec(lines)) != null) {
  33470. const key = match[1];
  33471. // Default undefined or null to empty string
  33472. let value = (match[2] || '');
  33473. // Remove whitespace
  33474. value = value.trim();
  33475. // Check if double quoted
  33476. const maybeQuote = value[0];
  33477. // Remove surrounding quotes
  33478. value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2');
  33479. // Expand newlines if double quoted
  33480. if (maybeQuote === '"') {
  33481. value = value.replace(/\\n/g, '\n');
  33482. value = value.replace(/\\r/g, '\r');
  33483. }
  33484. // Add to object
  33485. obj[key] = value;
  33486. }
  33487. return obj
  33488. }
  33489. function _log (message) {
  33490. console.log(`[dotenv@${version}][DEBUG] ${message}`);
  33491. }
  33492. function _resolveHome (envPath) {
  33493. return envPath[0] === '~' ? path$9.join(os$2.homedir(), envPath.slice(1)) : envPath
  33494. }
  33495. // Populates process.env from .env file
  33496. function config (options) {
  33497. let dotenvPath = path$9.resolve(process.cwd(), '.env');
  33498. let encoding = 'utf8';
  33499. const debug = Boolean(options && options.debug);
  33500. const override = Boolean(options && options.override);
  33501. if (options) {
  33502. if (options.path != null) {
  33503. dotenvPath = _resolveHome(options.path);
  33504. }
  33505. if (options.encoding != null) {
  33506. encoding = options.encoding;
  33507. }
  33508. }
  33509. try {
  33510. // Specifying an encoding returns a string instead of a buffer
  33511. const parsed = DotenvModule.parse(fs$9.readFileSync(dotenvPath, { encoding }));
  33512. Object.keys(parsed).forEach(function (key) {
  33513. if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
  33514. process.env[key] = parsed[key];
  33515. } else {
  33516. if (override === true) {
  33517. process.env[key] = parsed[key];
  33518. }
  33519. if (debug) {
  33520. if (override === true) {
  33521. _log(`"${key}" is already defined in \`process.env\` and WAS overwritten`);
  33522. } else {
  33523. _log(`"${key}" is already defined in \`process.env\` and was NOT overwritten`);
  33524. }
  33525. }
  33526. }
  33527. });
  33528. return { parsed }
  33529. } catch (e) {
  33530. if (debug) {
  33531. _log(`Failed to load ${dotenvPath} ${e.message}`);
  33532. }
  33533. return { error: e }
  33534. }
  33535. }
  33536. const DotenvModule = {
  33537. config,
  33538. parse: parse$9
  33539. };
  33540. main$1.exports.config = DotenvModule.config;
  33541. var parse_1$1 = main$1.exports.parse = DotenvModule.parse;
  33542. main$1.exports = DotenvModule;
  33543. function _interpolate (envValue, environment, config) {
  33544. const matches = envValue.match(/(.?\${*[\w]*(?::-[\w/]*)?}*)/g) || [];
  33545. return matches.reduce(function (newEnv, match, index) {
  33546. const parts = /(.?)\${*([\w]*(?::-[\w/]*)?)?}*/g.exec(match);
  33547. if (!parts || parts.length === 0) {
  33548. return newEnv
  33549. }
  33550. const prefix = parts[1];
  33551. let value, replacePart;
  33552. if (prefix === '\\') {
  33553. replacePart = parts[0];
  33554. value = replacePart.replace('\\$', '$');
  33555. } else {
  33556. // PATCH: compatible with env variables ended with unescaped $
  33557. if(!parts[2]) {
  33558. return newEnv
  33559. }
  33560. const keyParts = parts[2].split(':-');
  33561. const key = keyParts[0];
  33562. replacePart = parts[0].substring(prefix.length);
  33563. // process.env value 'wins' over .env file's value
  33564. value = Object.prototype.hasOwnProperty.call(environment, key)
  33565. ? environment[key]
  33566. : (config.parsed[key] || keyParts[1] || '');
  33567. // If the value is found, remove nested expansions.
  33568. if (keyParts.length > 1 && value) {
  33569. const replaceNested = matches[index + 1];
  33570. matches[index + 1] = '';
  33571. newEnv = newEnv.replace(replaceNested, '');
  33572. }
  33573. // Resolve recursive interpolations
  33574. value = _interpolate(value, environment, config);
  33575. }
  33576. return newEnv.replace(replacePart, value)
  33577. }, envValue)
  33578. }
  33579. function expand (config) {
  33580. // if ignoring process.env, use a blank object
  33581. const environment = config.ignoreProcessEnv ? {} : process.env;
  33582. for (const configKey in config.parsed) {
  33583. const value = Object.prototype.hasOwnProperty.call(environment, configKey) ? environment[configKey] : config.parsed[configKey];
  33584. config.parsed[configKey] = _interpolate(value, environment, config);
  33585. }
  33586. // PATCH: don't write to process.env
  33587. // for (const processKey in config.parsed) {
  33588. // environment[processKey] = config.parsed[processKey]
  33589. // }
  33590. return config
  33591. }
  33592. var expand_1 = expand;
  33593. function loadEnv(mode, envDir, prefixes = 'VITE_') {
  33594. if (mode === 'local') {
  33595. throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
  33596. `the .local postfix for .env files.`);
  33597. }
  33598. prefixes = arraify(prefixes);
  33599. const env = {};
  33600. const envFiles = [
  33601. /** default file */ `.env`,
  33602. /** local file */ `.env.local`,
  33603. /** mode file */ `.env.${mode}`,
  33604. /** mode local file */ `.env.${mode}.local`,
  33605. ];
  33606. const parsed = Object.fromEntries(envFiles.flatMap((file) => {
  33607. const filePath = path$o.join(envDir, file);
  33608. if (!tryStatSync(filePath)?.isFile())
  33609. return [];
  33610. return Object.entries(parse_1$1(fs$l.readFileSync(filePath)));
  33611. }));
  33612. // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this
  33613. if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {
  33614. process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
  33615. }
  33616. // support BROWSER and BROWSER_ARGS env variables
  33617. if (parsed.BROWSER && process.env.BROWSER === undefined) {
  33618. process.env.BROWSER = parsed.BROWSER;
  33619. }
  33620. if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) {
  33621. process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
  33622. }
  33623. // let environment variables use each other
  33624. // `expand` patched in patches/dotenv-expand@9.0.0.patch
  33625. expand_1({ parsed });
  33626. // only keys that start with prefix are exposed to client
  33627. for (const [key, value] of Object.entries(parsed)) {
  33628. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  33629. env[key] = value;
  33630. }
  33631. }
  33632. // check if there are actual env variables starting with VITE_*
  33633. // these are typically provided inline and should be prioritized
  33634. for (const key in process.env) {
  33635. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  33636. env[key] = process.env[key];
  33637. }
  33638. }
  33639. return env;
  33640. }
  33641. function resolveEnvPrefix({ envPrefix = 'VITE_', }) {
  33642. envPrefix = arraify(envPrefix);
  33643. if (envPrefix.some((prefix) => prefix === '')) {
  33644. throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
  33645. }
  33646. return envPrefix;
  33647. }
  33648. const modulePreloadPolyfillId = 'vite/modulepreload-polyfill';
  33649. const resolvedModulePreloadPolyfillId = '\0' + modulePreloadPolyfillId;
  33650. function modulePreloadPolyfillPlugin(config) {
  33651. // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis`
  33652. const skip = config.command !== 'build' || config.build.ssr;
  33653. let polyfillString;
  33654. return {
  33655. name: 'vite:modulepreload-polyfill',
  33656. resolveId(id) {
  33657. if (id === modulePreloadPolyfillId) {
  33658. return resolvedModulePreloadPolyfillId;
  33659. }
  33660. },
  33661. load(id) {
  33662. if (id === resolvedModulePreloadPolyfillId) {
  33663. if (skip) {
  33664. return '';
  33665. }
  33666. if (!polyfillString) {
  33667. polyfillString = `${isModernFlag}&&(${polyfill.toString()}());`;
  33668. }
  33669. return polyfillString;
  33670. }
  33671. },
  33672. };
  33673. }
  33674. function polyfill() {
  33675. const relList = document.createElement('link').relList;
  33676. if (relList && relList.supports && relList.supports('modulepreload')) {
  33677. return;
  33678. }
  33679. for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
  33680. processPreload(link);
  33681. }
  33682. new MutationObserver((mutations) => {
  33683. for (const mutation of mutations) {
  33684. if (mutation.type !== 'childList') {
  33685. continue;
  33686. }
  33687. for (const node of mutation.addedNodes) {
  33688. if (node.tagName === 'LINK' && node.rel === 'modulepreload')
  33689. processPreload(node);
  33690. }
  33691. }
  33692. }).observe(document, { childList: true, subtree: true });
  33693. function getFetchOpts(link) {
  33694. const fetchOpts = {};
  33695. if (link.integrity)
  33696. fetchOpts.integrity = link.integrity;
  33697. if (link.referrerPolicy)
  33698. fetchOpts.referrerPolicy = link.referrerPolicy;
  33699. if (link.crossOrigin === 'use-credentials')
  33700. fetchOpts.credentials = 'include';
  33701. else if (link.crossOrigin === 'anonymous')
  33702. fetchOpts.credentials = 'omit';
  33703. else
  33704. fetchOpts.credentials = 'same-origin';
  33705. return fetchOpts;
  33706. }
  33707. function processPreload(link) {
  33708. if (link.ep)
  33709. // ep marker = processed
  33710. return;
  33711. link.ep = true;
  33712. // prepopulate the load record
  33713. const fetchOpts = getFetchOpts(link);
  33714. fetch(link.href, fetchOpts);
  33715. }
  33716. }
  33717. const htmlProxyRE$1 = /\?html-proxy=?(?:&inline-css)?&index=(\d+)\.(js|css)$/;
  33718. const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
  33719. // Do not allow preceding '.', but do allow preceding '...' for spread operations
  33720. const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/g;
  33721. const htmlLangRE = /\.(?:html|htm)$/;
  33722. const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
  33723. const moduleScriptRE = /[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i;
  33724. const modulePreloadLinkRE = /[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i;
  33725. const importMapAppendRE = new RegExp([moduleScriptRE, modulePreloadLinkRE].map((r) => r.source).join('|'), 'i');
  33726. const isHTMLProxy = (id) => htmlProxyRE$1.test(id);
  33727. const isHTMLRequest = (request) => htmlLangRE.test(request);
  33728. // HTML Proxy Caches are stored by config -> filePath -> index
  33729. const htmlProxyMap = new WeakMap();
  33730. // HTML Proxy Transform result are stored by config
  33731. // `${hash(importer)}_${query.index}` -> transformed css code
  33732. // PS: key like `hash(/vite/playground/assets/index.html)_1`)
  33733. const htmlProxyResult = new Map();
  33734. function htmlInlineProxyPlugin(config) {
  33735. // Should do this when `constructor` rather than when `buildStart`,
  33736. // `buildStart` will be triggered multiple times then the cached result will be emptied.
  33737. // https://github.com/vitejs/vite/issues/6372
  33738. htmlProxyMap.set(config, new Map());
  33739. return {
  33740. name: 'vite:html-inline-proxy',
  33741. resolveId(id) {
  33742. if (htmlProxyRE$1.test(id)) {
  33743. return id;
  33744. }
  33745. },
  33746. load(id) {
  33747. const proxyMatch = id.match(htmlProxyRE$1);
  33748. if (proxyMatch) {
  33749. const index = Number(proxyMatch[1]);
  33750. const file = cleanUrl(id);
  33751. const url = file.replace(normalizePath$3(config.root), '');
  33752. const result = htmlProxyMap.get(config).get(url)[index];
  33753. if (result) {
  33754. return result;
  33755. }
  33756. else {
  33757. throw new Error(`No matching HTML proxy module found from ${id}`);
  33758. }
  33759. }
  33760. },
  33761. };
  33762. }
  33763. function addToHTMLProxyCache(config, filePath, index, result) {
  33764. if (!htmlProxyMap.get(config)) {
  33765. htmlProxyMap.set(config, new Map());
  33766. }
  33767. if (!htmlProxyMap.get(config).get(filePath)) {
  33768. htmlProxyMap.get(config).set(filePath, []);
  33769. }
  33770. htmlProxyMap.get(config).get(filePath)[index] = result;
  33771. }
  33772. function addToHTMLProxyTransformResult(hash, code) {
  33773. htmlProxyResult.set(hash, code);
  33774. }
  33775. // this extends the config in @vue/compiler-sfc with <link href>
  33776. const assetAttrsConfig = {
  33777. link: ['href'],
  33778. video: ['src', 'poster'],
  33779. source: ['src', 'srcset'],
  33780. img: ['src', 'srcset'],
  33781. image: ['xlink:href', 'href'],
  33782. use: ['xlink:href', 'href'],
  33783. };
  33784. const isAsyncScriptMap = new WeakMap();
  33785. function nodeIsElement(node) {
  33786. return node.nodeName[0] !== '#';
  33787. }
  33788. function traverseNodes(node, visitor) {
  33789. visitor(node);
  33790. if (nodeIsElement(node) ||
  33791. node.nodeName === '#document' ||
  33792. node.nodeName === '#document-fragment') {
  33793. node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
  33794. }
  33795. }
  33796. async function traverseHtml(html, filePath, visitor) {
  33797. // lazy load compiler
  33798. const { parse } = await import('./dep-f0c7dae0.js');
  33799. const ast = parse(html, {
  33800. scriptingEnabled: false,
  33801. sourceCodeLocationInfo: true,
  33802. onParseError: (e) => {
  33803. handleParseError(e, html, filePath);
  33804. },
  33805. });
  33806. traverseNodes(ast, visitor);
  33807. }
  33808. function getScriptInfo(node) {
  33809. let src;
  33810. let sourceCodeLocation;
  33811. let isModule = false;
  33812. let isAsync = false;
  33813. for (const p of node.attrs) {
  33814. if (p.prefix !== undefined)
  33815. continue;
  33816. if (p.name === 'src') {
  33817. if (!src) {
  33818. src = p;
  33819. sourceCodeLocation = node.sourceCodeLocation?.attrs['src'];
  33820. }
  33821. }
  33822. else if (p.name === 'type' && p.value && p.value === 'module') {
  33823. isModule = true;
  33824. }
  33825. else if (p.name === 'async') {
  33826. isAsync = true;
  33827. }
  33828. }
  33829. return { src, sourceCodeLocation, isModule, isAsync };
  33830. }
  33831. const attrValueStartRE = /=\s*(.)/;
  33832. function overwriteAttrValue(s, sourceCodeLocation, newValue) {
  33833. const srcString = s.slice(sourceCodeLocation.startOffset, sourceCodeLocation.endOffset);
  33834. const valueStart = srcString.match(attrValueStartRE);
  33835. if (!valueStart) {
  33836. // overwrite attr value can only be called for a well-defined value
  33837. throw new Error(`[vite:html] internal error, failed to overwrite attribute value`);
  33838. }
  33839. const wrapOffset = valueStart[1] === '"' || valueStart[1] === "'" ? 1 : 0;
  33840. const valueOffset = valueStart.index + valueStart[0].length - 1;
  33841. s.update(sourceCodeLocation.startOffset + valueOffset + wrapOffset, sourceCodeLocation.endOffset - wrapOffset, newValue);
  33842. return s;
  33843. }
  33844. /**
  33845. * Format parse5 @type {ParserError} to @type {RollupError}
  33846. */
  33847. function formatParseError(parserError, id, html) {
  33848. const formattedError = {
  33849. code: parserError.code,
  33850. message: `parse5 error code ${parserError.code}`,
  33851. frame: generateCodeFrame(html, parserError.startOffset),
  33852. loc: {
  33853. file: id,
  33854. line: parserError.startLine,
  33855. column: parserError.startCol,
  33856. },
  33857. };
  33858. return formattedError;
  33859. }
  33860. function handleParseError(parserError, html, filePath) {
  33861. switch (parserError.code) {
  33862. case 'missing-doctype':
  33863. // ignore missing DOCTYPE
  33864. return;
  33865. case 'abandoned-head-element-child':
  33866. // Accept elements without closing tag in <head>
  33867. return;
  33868. case 'duplicate-attribute':
  33869. // Accept duplicate attributes #9566
  33870. // The first attribute is used, browsers silently ignore duplicates
  33871. return;
  33872. case 'non-void-html-element-start-tag-with-trailing-solidus':
  33873. // Allow self closing on non-void elements #10439
  33874. return;
  33875. }
  33876. const parseError = formatParseError(parserError, filePath, html);
  33877. throw new Error(`Unable to parse HTML; ${parseError.message}\n` +
  33878. ` at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` +
  33879. `${parseError.frame}`);
  33880. }
  33881. /**
  33882. * Compiles index.html into an entry js module
  33883. */
  33884. function buildHtmlPlugin(config) {
  33885. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
  33886. preHooks.unshift(preImportMapHook(config));
  33887. preHooks.push(htmlEnvHook(config));
  33888. postHooks.push(postImportMapHook());
  33889. const processedHtml = new Map();
  33890. const isExcludedUrl = (url) => url[0] === '#' ||
  33891. isExternalUrl(url) ||
  33892. isDataUrl(url) ||
  33893. checkPublicFile(url, config);
  33894. // Same reason with `htmlInlineProxyPlugin`
  33895. isAsyncScriptMap.set(config, new Map());
  33896. return {
  33897. name: 'vite:build-html',
  33898. async transform(html, id) {
  33899. if (id.endsWith('.html')) {
  33900. const relativeUrlPath = path$o.posix.relative(config.root, normalizePath$3(id));
  33901. const publicPath = `/${relativeUrlPath}`;
  33902. const publicBase = getBaseInHTML(relativeUrlPath, config);
  33903. const publicToRelative = (filename, importer) => publicBase + filename;
  33904. const toOutputPublicFilePath = (url) => toOutputFilePathInHtml(url.slice(1), 'public', relativeUrlPath, 'html', config, publicToRelative);
  33905. // pre-transform
  33906. html = await applyHtmlTransforms(html, preHooks, {
  33907. path: publicPath,
  33908. filename: id,
  33909. });
  33910. let js = '';
  33911. const s = new MagicString(html);
  33912. const assetUrls = [];
  33913. const scriptUrls = [];
  33914. const styleUrls = [];
  33915. let inlineModuleIndex = -1;
  33916. let everyScriptIsAsync = true;
  33917. let someScriptsAreAsync = false;
  33918. let someScriptsAreDefer = false;
  33919. await traverseHtml(html, id, (node) => {
  33920. if (!nodeIsElement(node)) {
  33921. return;
  33922. }
  33923. let shouldRemove = false;
  33924. // script tags
  33925. if (node.nodeName === 'script') {
  33926. const { src, sourceCodeLocation, isModule, isAsync } = getScriptInfo(node);
  33927. const url = src && src.value;
  33928. const isPublicFile = !!(url && checkPublicFile(url, config));
  33929. if (isPublicFile) {
  33930. // referencing public dir url, prefix with base
  33931. overwriteAttrValue(s, sourceCodeLocation, toOutputPublicFilePath(url));
  33932. }
  33933. if (isModule) {
  33934. inlineModuleIndex++;
  33935. if (url && !isExcludedUrl(url)) {
  33936. // <script type="module" src="..."/>
  33937. // add it as an import
  33938. js += `\nimport ${JSON.stringify(url)}`;
  33939. shouldRemove = true;
  33940. }
  33941. else if (node.childNodes.length) {
  33942. const scriptNode = node.childNodes.pop();
  33943. const contents = scriptNode.value;
  33944. // <script type="module">...</script>
  33945. const filePath = id.replace(normalizePath$3(config.root), '');
  33946. addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
  33947. code: contents,
  33948. });
  33949. js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
  33950. shouldRemove = true;
  33951. }
  33952. everyScriptIsAsync && (everyScriptIsAsync = isAsync);
  33953. someScriptsAreAsync || (someScriptsAreAsync = isAsync);
  33954. someScriptsAreDefer || (someScriptsAreDefer = !isAsync);
  33955. }
  33956. else if (url && !isPublicFile) {
  33957. if (!isExcludedUrl(url)) {
  33958. config.logger.warn(`<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute`);
  33959. }
  33960. }
  33961. else if (node.childNodes.length) {
  33962. const scriptNode = node.childNodes.pop();
  33963. const cleanCode = stripLiteral(scriptNode.value);
  33964. let match;
  33965. inlineImportRE.lastIndex = 0;
  33966. while ((match = inlineImportRE.exec(cleanCode))) {
  33967. const { 1: url, index } = match;
  33968. const startUrl = cleanCode.indexOf(url, index);
  33969. const start = startUrl + 1;
  33970. const end = start + url.length - 2;
  33971. const startOffset = scriptNode.sourceCodeLocation.startOffset;
  33972. scriptUrls.push({
  33973. start: start + startOffset,
  33974. end: end + startOffset,
  33975. url: scriptNode.value.slice(start, end),
  33976. });
  33977. }
  33978. }
  33979. }
  33980. // For asset references in index.html, also generate an import
  33981. // statement for each - this will be handled by the asset plugin
  33982. const assetAttrs = assetAttrsConfig[node.nodeName];
  33983. if (assetAttrs) {
  33984. for (const p of node.attrs) {
  33985. const attrKey = getAttrKey(p);
  33986. if (p.value && assetAttrs.includes(attrKey)) {
  33987. const attrSourceCodeLocation = node.sourceCodeLocation.attrs[attrKey];
  33988. // assetsUrl may be encodeURI
  33989. const url = decodeURI(p.value);
  33990. if (!isExcludedUrl(url)) {
  33991. if (node.nodeName === 'link' &&
  33992. isCSSRequest(url) &&
  33993. // should not be converted if following attributes are present (#6748)
  33994. !node.attrs.some((p) => p.prefix === undefined &&
  33995. (p.name === 'media' || p.name === 'disabled'))) {
  33996. // CSS references, convert to import
  33997. const importExpression = `\nimport ${JSON.stringify(url)}`;
  33998. styleUrls.push({
  33999. url,
  34000. start: node.sourceCodeLocation.startOffset,
  34001. end: node.sourceCodeLocation.endOffset,
  34002. });
  34003. js += importExpression;
  34004. }
  34005. else {
  34006. assetUrls.push({
  34007. attr: p,
  34008. sourceCodeLocation: attrSourceCodeLocation,
  34009. });
  34010. }
  34011. }
  34012. else if (checkPublicFile(url, config)) {
  34013. overwriteAttrValue(s, attrSourceCodeLocation, toOutputPublicFilePath(url));
  34014. }
  34015. }
  34016. }
  34017. }
  34018. // <tag style="... url(...) ..."></tag>
  34019. // extract inline styles as virtual css and add class attribute to tag for selecting
  34020. const inlineStyle = node.attrs.find((prop) => prop.prefix === undefined &&
  34021. prop.name === 'style' &&
  34022. prop.value.includes('url('));
  34023. if (inlineStyle) {
  34024. inlineModuleIndex++;
  34025. // replace `inline style` to class
  34026. // and import css in js code
  34027. const code = inlineStyle.value;
  34028. const filePath = id.replace(normalizePath$3(config.root), '');
  34029. addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code });
  34030. // will transform with css plugin and cache result with css-post plugin
  34031. js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
  34032. const hash = getHash(cleanUrl(id));
  34033. // will transform in `applyHtmlTransforms`
  34034. const sourceCodeLocation = node.sourceCodeLocation.attrs['style'];
  34035. overwriteAttrValue(s, sourceCodeLocation, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
  34036. }
  34037. // <style>...</style>
  34038. if (node.nodeName === 'style' && node.childNodes.length) {
  34039. const styleNode = node.childNodes.pop();
  34040. const filePath = id.replace(normalizePath$3(config.root), '');
  34041. inlineModuleIndex++;
  34042. addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
  34043. code: styleNode.value,
  34044. });
  34045. js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
  34046. const hash = getHash(cleanUrl(id));
  34047. // will transform in `applyHtmlTransforms`
  34048. s.update(styleNode.sourceCodeLocation.startOffset, styleNode.sourceCodeLocation.endOffset, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
  34049. }
  34050. if (shouldRemove) {
  34051. // remove the script tag from the html. we are going to inject new
  34052. // ones in the end.
  34053. s.remove(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset);
  34054. }
  34055. });
  34056. isAsyncScriptMap.get(config).set(id, everyScriptIsAsync);
  34057. if (someScriptsAreAsync && someScriptsAreDefer) {
  34058. config.logger.warn(`\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`);
  34059. }
  34060. // for each encountered asset url, rewrite original html so that it
  34061. // references the post-build location, ignoring empty attributes and
  34062. // attributes that directly reference named output.
  34063. const namedOutput = Object.keys(config?.build?.rollupOptions?.input || {});
  34064. for (const { attr, sourceCodeLocation } of assetUrls) {
  34065. // assetsUrl may be encodeURI
  34066. const content = decodeURI(attr.value);
  34067. if (content !== '' && // Empty attribute
  34068. !namedOutput.includes(content) && // Direct reference to named output
  34069. !namedOutput.includes(removeLeadingSlash(content)) // Allow for absolute references as named output can't be an absolute path
  34070. ) {
  34071. try {
  34072. const url = attr.prefix === undefined && attr.name === 'srcset'
  34073. ? await processSrcSet(content, ({ url }) => urlToBuiltUrl(url, id, config, this))
  34074. : await urlToBuiltUrl(content, id, config, this);
  34075. overwriteAttrValue(s, sourceCodeLocation, url);
  34076. }
  34077. catch (e) {
  34078. if (e.code !== 'ENOENT') {
  34079. throw e;
  34080. }
  34081. }
  34082. }
  34083. }
  34084. // emit <script>import("./aaa")</script> asset
  34085. for (const { start, end, url } of scriptUrls) {
  34086. if (!isExcludedUrl(url)) {
  34087. s.update(start, end, await urlToBuiltUrl(url, id, config, this));
  34088. }
  34089. else if (checkPublicFile(url, config)) {
  34090. s.update(start, end, toOutputPublicFilePath(url));
  34091. }
  34092. }
  34093. // ignore <link rel="stylesheet"> if its url can't be resolved
  34094. const resolvedStyleUrls = await Promise.all(styleUrls.map(async (styleUrl) => ({
  34095. ...styleUrl,
  34096. resolved: await this.resolve(styleUrl.url, id),
  34097. })));
  34098. for (const { start, end, url, resolved } of resolvedStyleUrls) {
  34099. if (resolved == null) {
  34100. config.logger.warnOnce(`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
  34101. const importExpression = `\nimport ${JSON.stringify(url)}`;
  34102. js = js.replace(importExpression, '');
  34103. }
  34104. else {
  34105. s.remove(start, end);
  34106. }
  34107. }
  34108. processedHtml.set(id, s.toString());
  34109. // inject module preload polyfill only when configured and needed
  34110. const { modulePreload } = config.build;
  34111. if ((modulePreload === true ||
  34112. (typeof modulePreload === 'object' && modulePreload.polyfill)) &&
  34113. (someScriptsAreAsync || someScriptsAreDefer)) {
  34114. js = `import "${modulePreloadPolyfillId}";\n${js}`;
  34115. }
  34116. return js;
  34117. }
  34118. },
  34119. async generateBundle(options, bundle) {
  34120. const analyzedChunk = new Map();
  34121. const getImportedChunks = (chunk, seen = new Set()) => {
  34122. const chunks = [];
  34123. chunk.imports.forEach((file) => {
  34124. const importee = bundle[file];
  34125. if (importee?.type === 'chunk' && !seen.has(file)) {
  34126. seen.add(file);
  34127. // post-order traversal
  34128. chunks.push(...getImportedChunks(importee, seen));
  34129. chunks.push(importee);
  34130. }
  34131. });
  34132. return chunks;
  34133. };
  34134. const toScriptTag = (chunk, toOutputPath, isAsync) => ({
  34135. tag: 'script',
  34136. attrs: {
  34137. ...(isAsync ? { async: true } : {}),
  34138. type: 'module',
  34139. crossorigin: true,
  34140. src: toOutputPath(chunk.fileName),
  34141. },
  34142. });
  34143. const toPreloadTag = (filename, toOutputPath) => ({
  34144. tag: 'link',
  34145. attrs: {
  34146. rel: 'modulepreload',
  34147. crossorigin: true,
  34148. href: toOutputPath(filename),
  34149. },
  34150. });
  34151. const getCssTagsForChunk = (chunk, toOutputPath, seen = new Set()) => {
  34152. const tags = [];
  34153. if (!analyzedChunk.has(chunk)) {
  34154. analyzedChunk.set(chunk, 1);
  34155. chunk.imports.forEach((file) => {
  34156. const importee = bundle[file];
  34157. if (importee?.type === 'chunk') {
  34158. tags.push(...getCssTagsForChunk(importee, toOutputPath, seen));
  34159. }
  34160. });
  34161. }
  34162. chunk.viteMetadata.importedCss.forEach((file) => {
  34163. if (!seen.has(file)) {
  34164. seen.add(file);
  34165. tags.push({
  34166. tag: 'link',
  34167. attrs: {
  34168. rel: 'stylesheet',
  34169. href: toOutputPath(file),
  34170. },
  34171. });
  34172. }
  34173. });
  34174. return tags;
  34175. };
  34176. for (const [id, html] of processedHtml) {
  34177. const relativeUrlPath = path$o.posix.relative(config.root, normalizePath$3(id));
  34178. const assetsBase = getBaseInHTML(relativeUrlPath, config);
  34179. const toOutputFilePath = (filename, type) => {
  34180. if (isExternalUrl(filename)) {
  34181. return filename;
  34182. }
  34183. else {
  34184. return toOutputFilePathInHtml(filename, type, relativeUrlPath, 'html', config, (filename, importer) => assetsBase + filename);
  34185. }
  34186. };
  34187. const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, 'asset');
  34188. const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, 'public');
  34189. const isAsync = isAsyncScriptMap.get(config).get(id);
  34190. let result = html;
  34191. // find corresponding entry chunk
  34192. const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' &&
  34193. chunk.isEntry &&
  34194. chunk.facadeModuleId === id);
  34195. let canInlineEntry = false;
  34196. // inject chunk asset links
  34197. if (chunk) {
  34198. // an entry chunk can be inlined if
  34199. // - it's an ES module (e.g. not generated by the legacy plugin)
  34200. // - it contains no meaningful code other than import statements
  34201. if (options.format === 'es' && isEntirelyImport(chunk.code)) {
  34202. canInlineEntry = true;
  34203. }
  34204. // when not inlined, inject <script> for entry and modulepreload its dependencies
  34205. // when inlined, discard entry chunk and inject <script> for everything in post-order
  34206. const imports = getImportedChunks(chunk);
  34207. let assetTags;
  34208. if (canInlineEntry) {
  34209. assetTags = imports.map((chunk) => toScriptTag(chunk, toOutputAssetFilePath, isAsync));
  34210. }
  34211. else {
  34212. assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)];
  34213. const { modulePreload } = config.build;
  34214. if (modulePreload !== false) {
  34215. const resolveDependencies = typeof modulePreload === 'object' &&
  34216. modulePreload.resolveDependencies;
  34217. const importsFileNames = imports.map((chunk) => chunk.fileName);
  34218. const resolvedDeps = resolveDependencies
  34219. ? resolveDependencies(chunk.fileName, importsFileNames, {
  34220. hostId: relativeUrlPath,
  34221. hostType: 'html',
  34222. })
  34223. : importsFileNames;
  34224. assetTags.push(...resolvedDeps.map((i) => toPreloadTag(i, toOutputAssetFilePath)));
  34225. }
  34226. }
  34227. assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath));
  34228. result = injectToHead(result, assetTags);
  34229. }
  34230. // inject css link when cssCodeSplit is false
  34231. if (!config.build.cssCodeSplit) {
  34232. const cssChunk = Object.values(bundle).find((chunk) => chunk.type === 'asset' && chunk.name === 'style.css');
  34233. if (cssChunk) {
  34234. result = injectToHead(result, [
  34235. {
  34236. tag: 'link',
  34237. attrs: {
  34238. rel: 'stylesheet',
  34239. href: toOutputAssetFilePath(cssChunk.fileName),
  34240. },
  34241. },
  34242. ]);
  34243. }
  34244. }
  34245. // no use assets plugin because it will emit file
  34246. let match;
  34247. let s;
  34248. inlineCSSRE$1.lastIndex = 0;
  34249. while ((match = inlineCSSRE$1.exec(result))) {
  34250. s || (s = new MagicString(result));
  34251. const { 0: full, 1: scopedName } = match;
  34252. const cssTransformedCode = htmlProxyResult.get(scopedName);
  34253. s.update(match.index, match.index + full.length, cssTransformedCode);
  34254. }
  34255. if (s) {
  34256. result = s.toString();
  34257. }
  34258. result = await applyHtmlTransforms(result, [...normalHooks, ...postHooks], {
  34259. path: '/' + relativeUrlPath,
  34260. filename: id,
  34261. bundle,
  34262. chunk,
  34263. });
  34264. // resolve asset url references
  34265. result = result.replace(assetUrlRE, (_, fileHash, postfix = '') => {
  34266. return toOutputAssetFilePath(this.getFileName(fileHash)) + postfix;
  34267. });
  34268. result = result.replace(publicAssetUrlRE, (_, fileHash) => {
  34269. const publicAssetPath = toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config));
  34270. return isUrl(publicAssetPath)
  34271. ? publicAssetPath
  34272. : normalizePath$3(publicAssetPath);
  34273. });
  34274. if (chunk && canInlineEntry) {
  34275. // all imports from entry have been inlined to html, prevent rollup from outputting it
  34276. delete bundle[chunk.fileName];
  34277. }
  34278. const shortEmitName = normalizePath$3(path$o.relative(config.root, id));
  34279. this.emitFile({
  34280. type: 'asset',
  34281. fileName: shortEmitName,
  34282. source: result,
  34283. });
  34284. }
  34285. },
  34286. };
  34287. }
  34288. function preImportMapHook(config) {
  34289. return (html, ctx) => {
  34290. const importMapIndex = html.match(importMapRE)?.index;
  34291. if (importMapIndex === undefined)
  34292. return;
  34293. const importMapAppendIndex = html.match(importMapAppendRE)?.index;
  34294. if (importMapAppendIndex === undefined)
  34295. return;
  34296. if (importMapAppendIndex < importMapIndex) {
  34297. const relativeHtml = normalizePath$3(path$o.relative(config.root, ctx.filename));
  34298. config.logger.warnOnce(colors$1.yellow(colors$1.bold(`(!) <script type="importmap"> should come before <script type="module"> and <link rel="modulepreload"> in /${relativeHtml}`)));
  34299. }
  34300. };
  34301. }
  34302. /**
  34303. * Move importmap before the first module script and modulepreload link
  34304. */
  34305. function postImportMapHook() {
  34306. return (html) => {
  34307. if (!importMapAppendRE.test(html))
  34308. return;
  34309. let importMap;
  34310. html = html.replace(importMapRE, (match) => {
  34311. importMap = match;
  34312. return '';
  34313. });
  34314. if (importMap) {
  34315. html = html.replace(importMapAppendRE, (match) => `${importMap}\n${match}`);
  34316. }
  34317. return html;
  34318. };
  34319. }
  34320. /**
  34321. * Support `%ENV_NAME%` syntax in html files
  34322. */
  34323. function htmlEnvHook(config) {
  34324. const pattern = /%(\S+?)%/g;
  34325. const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
  34326. const env = { ...config.env };
  34327. // account for user env defines
  34328. for (const key in config.define) {
  34329. if (key.startsWith(`import.meta.env.`)) {
  34330. const val = config.define[key];
  34331. env[key.slice(16)] = typeof val === 'string' ? val : JSON.stringify(val);
  34332. }
  34333. }
  34334. return (html, ctx) => {
  34335. return html.replace(pattern, (text, key) => {
  34336. if (key in env) {
  34337. return env[key];
  34338. }
  34339. else {
  34340. if (envPrefix.some((prefix) => key.startsWith(prefix))) {
  34341. const relativeHtml = normalizePath$3(path$o.relative(config.root, ctx.filename));
  34342. config.logger.warn(colors$1.yellow(colors$1.bold(`(!) ${text} is not defined in env variables found in /${relativeHtml}. ` +
  34343. `Is the variable mistyped?`)));
  34344. }
  34345. return text;
  34346. }
  34347. });
  34348. };
  34349. }
  34350. function resolveHtmlTransforms(plugins) {
  34351. const preHooks = [];
  34352. const normalHooks = [];
  34353. const postHooks = [];
  34354. for (const plugin of plugins) {
  34355. const hook = plugin.transformIndexHtml;
  34356. if (!hook)
  34357. continue;
  34358. if (typeof hook === 'function') {
  34359. normalHooks.push(hook);
  34360. }
  34361. else {
  34362. // `enforce` had only two possible values for the `transformIndexHtml` hook
  34363. // `'pre'` and `'post'` (the default). `order` now works with three values
  34364. // to align with other hooks (`'pre'`, normal, and `'post'`). We map
  34365. // both `enforce: 'post'` to `order: undefined` to avoid a breaking change
  34366. const order = hook.order ?? (hook.enforce === 'pre' ? 'pre' : undefined);
  34367. // @ts-expect-error union type
  34368. const handler = hook.handler ?? hook.transform;
  34369. if (order === 'pre') {
  34370. preHooks.push(handler);
  34371. }
  34372. else if (order === 'post') {
  34373. postHooks.push(handler);
  34374. }
  34375. else {
  34376. normalHooks.push(handler);
  34377. }
  34378. }
  34379. }
  34380. return [preHooks, normalHooks, postHooks];
  34381. }
  34382. async function applyHtmlTransforms(html, hooks, ctx) {
  34383. for (const hook of hooks) {
  34384. const res = await hook(html, ctx);
  34385. if (!res) {
  34386. continue;
  34387. }
  34388. if (typeof res === 'string') {
  34389. html = res;
  34390. }
  34391. else {
  34392. let tags;
  34393. if (Array.isArray(res)) {
  34394. tags = res;
  34395. }
  34396. else {
  34397. html = res.html || html;
  34398. tags = res.tags;
  34399. }
  34400. const headTags = [];
  34401. const headPrependTags = [];
  34402. const bodyTags = [];
  34403. const bodyPrependTags = [];
  34404. for (const tag of tags) {
  34405. if (tag.injectTo === 'body') {
  34406. bodyTags.push(tag);
  34407. }
  34408. else if (tag.injectTo === 'body-prepend') {
  34409. bodyPrependTags.push(tag);
  34410. }
  34411. else if (tag.injectTo === 'head') {
  34412. headTags.push(tag);
  34413. }
  34414. else {
  34415. headPrependTags.push(tag);
  34416. }
  34417. }
  34418. html = injectToHead(html, headPrependTags, true);
  34419. html = injectToHead(html, headTags);
  34420. html = injectToBody(html, bodyPrependTags, true);
  34421. html = injectToBody(html, bodyTags);
  34422. }
  34423. }
  34424. return html;
  34425. }
  34426. const importRE = /\bimport\s*("[^"]*[^\\]"|'[^']*[^\\]');*/g;
  34427. const commentRE$1 = /\/\*[\s\S]*?\*\/|\/\/.*$/gm;
  34428. function isEntirelyImport(code) {
  34429. // only consider "side-effect" imports, which match <script type=module> semantics exactly
  34430. // the regexes will remove too little in some exotic cases, but false-negatives are alright
  34431. return !code.replace(importRE, '').replace(commentRE$1, '').trim().length;
  34432. }
  34433. function getBaseInHTML(urlRelativePath, config) {
  34434. // Prefer explicit URL if defined for linking to assets and public files from HTML,
  34435. // even when base relative is specified
  34436. return config.base === './' || config.base === ''
  34437. ? path$o.posix.join(path$o.posix.relative(urlRelativePath, '').slice(0, -2), './')
  34438. : config.base;
  34439. }
  34440. const headInjectRE = /([ \t]*)<\/head>/i;
  34441. const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
  34442. const htmlInjectRE = /<\/html>/i;
  34443. const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
  34444. const bodyInjectRE = /([ \t]*)<\/body>/i;
  34445. const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
  34446. const doctypePrependInjectRE = /<!doctype html>/i;
  34447. function injectToHead(html, tags, prepend = false) {
  34448. if (tags.length === 0)
  34449. return html;
  34450. if (prepend) {
  34451. // inject as the first element of head
  34452. if (headPrependInjectRE.test(html)) {
  34453. return html.replace(headPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  34454. }
  34455. }
  34456. else {
  34457. // inject before head close
  34458. if (headInjectRE.test(html)) {
  34459. // respect indentation of head tag
  34460. return html.replace(headInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  34461. }
  34462. // try to inject before the body tag
  34463. if (bodyPrependInjectRE.test(html)) {
  34464. return html.replace(bodyPrependInjectRE, (match, p1) => `${serializeTags(tags, p1)}\n${match}`);
  34465. }
  34466. }
  34467. // if no head tag is present, we prepend the tag for both prepend and append
  34468. return prependInjectFallback(html, tags);
  34469. }
  34470. function injectToBody(html, tags, prepend = false) {
  34471. if (tags.length === 0)
  34472. return html;
  34473. if (prepend) {
  34474. // inject after body open
  34475. if (bodyPrependInjectRE.test(html)) {
  34476. return html.replace(bodyPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  34477. }
  34478. // if no there is no body tag, inject after head or fallback to prepend in html
  34479. if (headInjectRE.test(html)) {
  34480. return html.replace(headInjectRE, (match, p1) => `${match}\n${serializeTags(tags, p1)}`);
  34481. }
  34482. return prependInjectFallback(html, tags);
  34483. }
  34484. else {
  34485. // inject before body close
  34486. if (bodyInjectRE.test(html)) {
  34487. return html.replace(bodyInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  34488. }
  34489. // if no body tag is present, append to the html tag, or at the end of the file
  34490. if (htmlInjectRE.test(html)) {
  34491. return html.replace(htmlInjectRE, `${serializeTags(tags)}\n$&`);
  34492. }
  34493. return html + `\n` + serializeTags(tags);
  34494. }
  34495. }
  34496. function prependInjectFallback(html, tags) {
  34497. // prepend to the html tag, append after doctype, or the document start
  34498. if (htmlPrependInjectRE.test(html)) {
  34499. return html.replace(htmlPrependInjectRE, `$&\n${serializeTags(tags)}`);
  34500. }
  34501. if (doctypePrependInjectRE.test(html)) {
  34502. return html.replace(doctypePrependInjectRE, `$&\n${serializeTags(tags)}`);
  34503. }
  34504. return serializeTags(tags) + html;
  34505. }
  34506. const unaryTags = new Set(['link', 'meta', 'base']);
  34507. function serializeTag({ tag, attrs, children }, indent = '') {
  34508. if (unaryTags.has(tag)) {
  34509. return `<${tag}${serializeAttrs(attrs)}>`;
  34510. }
  34511. else {
  34512. return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children, incrementIndent(indent))}</${tag}>`;
  34513. }
  34514. }
  34515. function serializeTags(tags, indent = '') {
  34516. if (typeof tags === 'string') {
  34517. return tags;
  34518. }
  34519. else if (tags && tags.length) {
  34520. return tags.map((tag) => `${indent}${serializeTag(tag, indent)}\n`).join('');
  34521. }
  34522. return '';
  34523. }
  34524. function serializeAttrs(attrs) {
  34525. let res = '';
  34526. for (const key in attrs) {
  34527. if (typeof attrs[key] === 'boolean') {
  34528. res += attrs[key] ? ` ${key}` : ``;
  34529. }
  34530. else {
  34531. res += ` ${key}=${JSON.stringify(attrs[key])}`;
  34532. }
  34533. }
  34534. return res;
  34535. }
  34536. function incrementIndent(indent = '') {
  34537. return `${indent}${indent[0] === '\t' ? '\t' : ' '}`;
  34538. }
  34539. function getAttrKey(attr) {
  34540. return attr.prefix === undefined ? attr.name : `${attr.prefix}:${attr.name}`;
  34541. }
  34542. const cssModuleRE = new RegExp(`\\.module${CSS_LANGS_RE.source}`);
  34543. const directRequestRE = /(?:\?|&)direct\b/;
  34544. const htmlProxyRE = /(?:\?|&)html-proxy\b/;
  34545. const commonjsProxyRE = /\?commonjs-proxy/;
  34546. const inlineRE = /(?:\?|&)inline\b/;
  34547. const inlineCSSRE = /(?:\?|&)inline-css\b/;
  34548. const usedRE = /(?:\?|&)used\b/;
  34549. const varRE = /^var\(/i;
  34550. const cssBundleName = 'style.css';
  34551. const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
  34552. const isModuleCSSRequest = (request) => cssModuleRE.test(request);
  34553. const isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequestRE.test(request);
  34554. const isDirectRequest = (request) => directRequestRE.test(request);
  34555. const cssModulesCache = new WeakMap();
  34556. const removedPureCssFilesCache = new WeakMap();
  34557. const postcssConfigCache = new WeakMap();
  34558. function encodePublicUrlsInCSS(config) {
  34559. return config.command === 'build';
  34560. }
  34561. /**
  34562. * Plugin applied before user plugins
  34563. */
  34564. function cssPlugin(config) {
  34565. let server;
  34566. let moduleCache;
  34567. const resolveUrl = config.createResolver({
  34568. preferRelative: true,
  34569. tryIndex: false,
  34570. extensions: [],
  34571. });
  34572. // warm up cache for resolved postcss config
  34573. resolvePostcssConfig(config);
  34574. return {
  34575. name: 'vite:css',
  34576. configureServer(_server) {
  34577. server = _server;
  34578. },
  34579. buildStart() {
  34580. // Ensure a new cache for every build (i.e. rebuilding in watch mode)
  34581. moduleCache = new Map();
  34582. cssModulesCache.set(config, moduleCache);
  34583. removedPureCssFilesCache.set(config, new Map());
  34584. },
  34585. async transform(raw, id, options) {
  34586. if (!isCSSRequest(id) ||
  34587. commonjsProxyRE.test(id) ||
  34588. SPECIAL_QUERY_RE.test(id)) {
  34589. return;
  34590. }
  34591. const ssr = options?.ssr === true;
  34592. const urlReplacer = async (url, importer) => {
  34593. if (checkPublicFile(url, config)) {
  34594. if (encodePublicUrlsInCSS(config)) {
  34595. return publicFileToBuiltUrl(url, config);
  34596. }
  34597. else {
  34598. return joinUrlSegments(config.base, url);
  34599. }
  34600. }
  34601. const resolved = await resolveUrl(url, importer);
  34602. if (resolved) {
  34603. return fileToUrl(resolved, config, this);
  34604. }
  34605. if (config.command === 'build') {
  34606. const isExternal = config.build.rollupOptions.external
  34607. ? resolveUserExternal(config.build.rollupOptions.external, url, // use URL as id since id could not be resolved
  34608. id, false)
  34609. : false;
  34610. if (!isExternal) {
  34611. // #9800 If we cannot resolve the css url, leave a warning.
  34612. config.logger.warnOnce(`\n${url} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
  34613. }
  34614. }
  34615. return url;
  34616. };
  34617. const { code: css, modules, deps, map, } = await compileCSS(id, raw, config, urlReplacer);
  34618. if (modules) {
  34619. moduleCache.set(id, modules);
  34620. }
  34621. // track deps for build watch mode
  34622. if (config.command === 'build' && config.build.watch && deps) {
  34623. for (const file of deps) {
  34624. this.addWatchFile(file);
  34625. }
  34626. }
  34627. // dev
  34628. if (server) {
  34629. // server only logic for handling CSS @import dependency hmr
  34630. const { moduleGraph } = server;
  34631. const thisModule = moduleGraph.getModuleById(id);
  34632. if (thisModule) {
  34633. // CSS modules cannot self-accept since it exports values
  34634. const isSelfAccepting = !modules && !inlineRE.test(id) && !htmlProxyRE.test(id);
  34635. if (deps) {
  34636. // record deps in the module graph so edits to @import css can trigger
  34637. // main import to hot update
  34638. const depModules = new Set();
  34639. const devBase = config.base;
  34640. for (const file of deps) {
  34641. depModules.add(isCSSRequest(file)
  34642. ? moduleGraph.createFileOnlyEntry(file)
  34643. : await moduleGraph.ensureEntryFromUrl(stripBase(await fileToUrl(file, config, this), (config.server?.origin ?? '') + devBase), ssr));
  34644. }
  34645. moduleGraph.updateModuleInfo(thisModule, depModules, null,
  34646. // The root CSS proxy module is self-accepting and should not
  34647. // have an explicit accept list
  34648. new Set(), null, isSelfAccepting, ssr);
  34649. for (const file of deps) {
  34650. this.addWatchFile(file);
  34651. }
  34652. }
  34653. else {
  34654. thisModule.isSelfAccepting = isSelfAccepting;
  34655. }
  34656. }
  34657. }
  34658. return {
  34659. code: css,
  34660. map,
  34661. };
  34662. },
  34663. };
  34664. }
  34665. /**
  34666. * Plugin applied after user plugins
  34667. */
  34668. function cssPostPlugin(config) {
  34669. // styles initialization in buildStart causes a styling loss in watch
  34670. const styles = new Map();
  34671. // list of css emit tasks to guarantee the files are emitted in a deterministic order
  34672. let emitTasks = [];
  34673. let pureCssChunks;
  34674. // when there are multiple rollup outputs and extracting CSS, only emit once,
  34675. // since output formats have no effect on the generated CSS.
  34676. let outputToExtractedCSSMap;
  34677. let hasEmitted = false;
  34678. const rollupOptionsOutput = config.build.rollupOptions.output;
  34679. const assetFileNames = (Array.isArray(rollupOptionsOutput)
  34680. ? rollupOptionsOutput[0]
  34681. : rollupOptionsOutput)?.assetFileNames;
  34682. const getCssAssetDirname = (cssAssetName) => {
  34683. if (!assetFileNames) {
  34684. return config.build.assetsDir;
  34685. }
  34686. else if (typeof assetFileNames === 'string') {
  34687. return path$o.dirname(assetFileNames);
  34688. }
  34689. else {
  34690. return path$o.dirname(assetFileNames({
  34691. name: cssAssetName,
  34692. type: 'asset',
  34693. source: '/* vite internal call, ignore */',
  34694. }));
  34695. }
  34696. };
  34697. return {
  34698. name: 'vite:css-post',
  34699. buildStart() {
  34700. // Ensure new caches for every build (i.e. rebuilding in watch mode)
  34701. pureCssChunks = new Set();
  34702. outputToExtractedCSSMap = new Map();
  34703. hasEmitted = false;
  34704. emitTasks = [];
  34705. },
  34706. async transform(css, id, options) {
  34707. if (!isCSSRequest(id) ||
  34708. commonjsProxyRE.test(id) ||
  34709. SPECIAL_QUERY_RE.test(id)) {
  34710. return;
  34711. }
  34712. css = stripBomTag(css);
  34713. const inlined = inlineRE.test(id);
  34714. const modules = cssModulesCache.get(config).get(id);
  34715. // #6984, #7552
  34716. // `foo.module.css` => modulesCode
  34717. // `foo.module.css?inline` => cssContent
  34718. const modulesCode = modules &&
  34719. !inlined &&
  34720. dataToEsm(modules, { namedExports: true, preferConst: true });
  34721. if (config.command === 'serve') {
  34722. const getContentWithSourcemap = async (content) => {
  34723. if (config.css?.devSourcemap) {
  34724. const sourcemap = this.getCombinedSourcemap();
  34725. if (sourcemap.mappings && !sourcemap.sourcesContent) {
  34726. await injectSourcesContent(sourcemap, cleanUrl(id), config.logger);
  34727. }
  34728. return getCodeWithSourcemap('css', content, sourcemap);
  34729. }
  34730. return content;
  34731. };
  34732. if (isDirectCSSRequest(id)) {
  34733. return await getContentWithSourcemap(css);
  34734. }
  34735. // server only
  34736. if (options?.ssr) {
  34737. return modulesCode || `export default ${JSON.stringify(css)}`;
  34738. }
  34739. if (inlined) {
  34740. return `export default ${JSON.stringify(css)}`;
  34741. }
  34742. const cssContent = await getContentWithSourcemap(css);
  34743. const code = [
  34744. `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(path$o.posix.join(config.base, CLIENT_PUBLIC_PATH))}`,
  34745. `const __vite__id = ${JSON.stringify(id)}`,
  34746. `const __vite__css = ${JSON.stringify(cssContent)}`,
  34747. `__vite__updateStyle(__vite__id, __vite__css)`,
  34748. // css modules exports change on edit so it can't self accept
  34749. `${modulesCode ||
  34750. `import.meta.hot.accept()\nexport default __vite__css`}`,
  34751. `import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`,
  34752. ].join('\n');
  34753. return { code, map: { mappings: '' } };
  34754. }
  34755. // build CSS handling ----------------------------------------------------
  34756. // record css
  34757. // cache css compile result to map
  34758. // and then use the cache replace inline-style-flag when `generateBundle` in vite:build-html plugin
  34759. const inlineCSS = inlineCSSRE.test(id);
  34760. const isHTMLProxy = htmlProxyRE.test(id);
  34761. const query = parseRequest(id);
  34762. if (inlineCSS && isHTMLProxy) {
  34763. addToHTMLProxyTransformResult(`${getHash(cleanUrl(id))}_${Number.parseInt(query.index)}`, css);
  34764. return `export default ''`;
  34765. }
  34766. if (!inlined) {
  34767. styles.set(id, css);
  34768. }
  34769. let code;
  34770. if (usedRE.test(id)) {
  34771. if (modulesCode) {
  34772. code = modulesCode;
  34773. }
  34774. else {
  34775. let content = css;
  34776. if (config.build.cssMinify) {
  34777. content = await minifyCSS(content, config);
  34778. }
  34779. code = `export default ${JSON.stringify(content)}`;
  34780. }
  34781. }
  34782. else {
  34783. // if moduleCode exists return it **even if** it does not have `?used`
  34784. // this will disable tree-shake to work with `import './foo.module.css'` but this usually does not happen
  34785. // this is a limitation of the current approach by `?used` to make tree-shake work
  34786. // See #8936 for more details
  34787. code = modulesCode || `export default ''`;
  34788. }
  34789. return {
  34790. code,
  34791. map: { mappings: '' },
  34792. // avoid the css module from being tree-shaken so that we can retrieve
  34793. // it in renderChunk()
  34794. moduleSideEffects: inlined ? false : 'no-treeshake',
  34795. };
  34796. },
  34797. async renderChunk(code, chunk, opts) {
  34798. let chunkCSS = '';
  34799. let isPureCssChunk = true;
  34800. const ids = Object.keys(chunk.modules);
  34801. for (const id of ids) {
  34802. if (styles.has(id)) {
  34803. chunkCSS += styles.get(id);
  34804. // a css module contains JS, so it makes this not a pure css chunk
  34805. if (cssModuleRE.test(id)) {
  34806. isPureCssChunk = false;
  34807. }
  34808. }
  34809. else {
  34810. // if the module does not have a style, then it's not a pure css chunk.
  34811. // this is true because in the `transform` hook above, only modules
  34812. // that are css gets added to the `styles` map.
  34813. isPureCssChunk = false;
  34814. }
  34815. }
  34816. if (!chunkCSS) {
  34817. return null;
  34818. }
  34819. const publicAssetUrlMap = publicAssetUrlCache.get(config);
  34820. // resolve asset URL placeholders to their built file URLs
  34821. const resolveAssetUrlsInCss = (chunkCSS, cssAssetName) => {
  34822. const encodedPublicUrls = encodePublicUrlsInCSS(config);
  34823. const relative = config.base === './' || config.base === '';
  34824. const cssAssetDirname = encodedPublicUrls || relative
  34825. ? getCssAssetDirname(cssAssetName)
  34826. : undefined;
  34827. const toRelative = (filename, importer) => {
  34828. // relative base + extracted CSS
  34829. const relativePath = path$o.posix.relative(cssAssetDirname, filename);
  34830. return relativePath[0] === '.' ? relativePath : './' + relativePath;
  34831. };
  34832. // replace asset url references with resolved url.
  34833. chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = '') => {
  34834. const filename = this.getFileName(fileHash) + postfix;
  34835. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  34836. return toOutputFilePathInCss(filename, 'asset', cssAssetName, 'css', config, toRelative);
  34837. });
  34838. // resolve public URL from CSS paths
  34839. if (encodedPublicUrls) {
  34840. const relativePathToPublicFromCSS = path$o.posix.relative(cssAssetDirname, '');
  34841. chunkCSS = chunkCSS.replace(publicAssetUrlRE, (_, hash) => {
  34842. const publicUrl = publicAssetUrlMap.get(hash).slice(1);
  34843. return toOutputFilePathInCss(publicUrl, 'public', cssAssetName, 'css', config, () => `${relativePathToPublicFromCSS}/${publicUrl}`);
  34844. });
  34845. }
  34846. return chunkCSS;
  34847. };
  34848. function ensureFileExt(name, ext) {
  34849. return normalizePath$3(path$o.format({ ...path$o.parse(name), base: undefined, ext }));
  34850. }
  34851. if (config.build.cssCodeSplit) {
  34852. if (isPureCssChunk) {
  34853. // this is a shared CSS-only chunk that is empty.
  34854. pureCssChunks.add(chunk);
  34855. }
  34856. if (opts.format === 'es' || opts.format === 'cjs') {
  34857. const cssAssetName = chunk.facadeModuleId
  34858. ? normalizePath$3(path$o.relative(config.root, chunk.facadeModuleId))
  34859. : chunk.name;
  34860. const lang = path$o.extname(cssAssetName).slice(1);
  34861. const cssFileName = ensureFileExt(cssAssetName, '.css');
  34862. chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
  34863. const previousTask = emitTasks[emitTasks.length - 1];
  34864. // finalizeCss is async which makes `emitFile` non-deterministic, so
  34865. // we use a `.then` to wait for previous tasks before finishing this
  34866. const thisTask = finalizeCss(chunkCSS, true, config).then((css) => {
  34867. chunkCSS = css;
  34868. // make sure the previous task is also finished, this works recursively
  34869. return previousTask;
  34870. });
  34871. // push this task so the next task can wait for this one
  34872. emitTasks.push(thisTask);
  34873. const emitTasksLength = emitTasks.length;
  34874. // wait for this and previous tasks to finish
  34875. await thisTask;
  34876. // emit corresponding css file
  34877. const referenceId = this.emitFile({
  34878. name: path$o.basename(cssFileName),
  34879. type: 'asset',
  34880. source: chunkCSS,
  34881. });
  34882. const originalName = isPreProcessor(lang) ? cssAssetName : cssFileName;
  34883. const isEntry = chunk.isEntry && isPureCssChunk;
  34884. generatedAssets
  34885. .get(config)
  34886. .set(referenceId, { originalName, isEntry });
  34887. chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
  34888. if (emitTasksLength === emitTasks.length) {
  34889. // this is the last task, clear `emitTasks` to free up memory
  34890. emitTasks = [];
  34891. }
  34892. }
  34893. else if (!config.build.ssr) {
  34894. // legacy build and inline css
  34895. // Entry chunk CSS will be collected into `chunk.viteMetadata.importedCss`
  34896. // and injected later by the `'vite:build-html'` plugin into the `index.html`
  34897. // so it will be duplicated. (https://github.com/vitejs/vite/issues/2062#issuecomment-782388010)
  34898. // But because entry chunk can be imported by dynamic import,
  34899. // we shouldn't remove the inlined CSS. (#10285)
  34900. chunkCSS = await finalizeCss(chunkCSS, true, config);
  34901. let cssString = JSON.stringify(chunkCSS);
  34902. cssString =
  34903. renderAssetUrlInJS(this, config, chunk, opts, cssString)?.toString() || cssString;
  34904. const style = `__vite_style__`;
  34905. const injectCode = `var ${style} = document.createElement('style');` +
  34906. `${style}.textContent = ${cssString};` +
  34907. `document.head.appendChild(${style});`;
  34908. const wrapIdx = code.indexOf('System.register');
  34909. const insertMark = "'use strict';";
  34910. const insertIdx = code.indexOf(insertMark, wrapIdx);
  34911. const s = new MagicString(code);
  34912. s.appendLeft(insertIdx + insertMark.length, injectCode);
  34913. if (config.build.sourcemap) {
  34914. // resolve public URL from CSS paths, we need to use absolute paths
  34915. return {
  34916. code: s.toString(),
  34917. map: s.generateMap({ hires: true }),
  34918. };
  34919. }
  34920. else {
  34921. return { code: s.toString() };
  34922. }
  34923. }
  34924. }
  34925. else {
  34926. chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssBundleName);
  34927. // finalizeCss is called for the aggregated chunk in generateBundle
  34928. outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS);
  34929. }
  34930. return null;
  34931. },
  34932. augmentChunkHash(chunk) {
  34933. if (chunk.viteMetadata?.importedCss.size) {
  34934. let hash = '';
  34935. for (const id of chunk.viteMetadata.importedCss) {
  34936. hash += id;
  34937. }
  34938. return hash;
  34939. }
  34940. },
  34941. async generateBundle(opts, bundle) {
  34942. // @ts-expect-error asset emits are skipped in legacy bundle
  34943. if (opts.__vite_skip_asset_emit__) {
  34944. return;
  34945. }
  34946. // remove empty css chunks and their imports
  34947. if (pureCssChunks.size) {
  34948. // map each pure css chunk (rendered chunk) to it's corresponding bundle
  34949. // chunk. we check that by comparing the `moduleIds` as they have different
  34950. // filenames (rendered chunk has the !~{XXX}~ placeholder)
  34951. const pureCssChunkNames = [];
  34952. for (const pureCssChunk of pureCssChunks) {
  34953. for (const key in bundle) {
  34954. const bundleChunk = bundle[key];
  34955. if (bundleChunk.type === 'chunk' &&
  34956. arrayEqual(bundleChunk.moduleIds, pureCssChunk.moduleIds)) {
  34957. pureCssChunkNames.push(key);
  34958. break;
  34959. }
  34960. }
  34961. }
  34962. const emptyChunkFiles = pureCssChunkNames
  34963. .map((file) => path$o.basename(file))
  34964. .join('|')
  34965. .replace(/\./g, '\\.');
  34966. const emptyChunkRE = new RegExp(opts.format === 'es'
  34967. ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];\n?`
  34968. : `\\brequire\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\);\n?`, 'g');
  34969. for (const file in bundle) {
  34970. const chunk = bundle[file];
  34971. if (chunk.type === 'chunk') {
  34972. // remove pure css chunk from other chunk's imports,
  34973. // and also register the emitted CSS files under the importer
  34974. // chunks instead.
  34975. chunk.imports = chunk.imports.filter((file) => {
  34976. if (pureCssChunkNames.includes(file)) {
  34977. const { importedCss } = bundle[file]
  34978. .viteMetadata;
  34979. importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
  34980. return false;
  34981. }
  34982. return true;
  34983. });
  34984. chunk.code = chunk.code.replace(emptyChunkRE,
  34985. // remove css import while preserving source map location
  34986. (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`);
  34987. }
  34988. }
  34989. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  34990. pureCssChunkNames.forEach((fileName) => {
  34991. removedPureCssFiles.set(fileName, bundle[fileName]);
  34992. delete bundle[fileName];
  34993. });
  34994. }
  34995. let extractedCss = outputToExtractedCSSMap.get(opts);
  34996. if (extractedCss && !hasEmitted) {
  34997. hasEmitted = true;
  34998. extractedCss = await finalizeCss(extractedCss, true, config);
  34999. this.emitFile({
  35000. name: cssBundleName,
  35001. type: 'asset',
  35002. source: extractedCss,
  35003. });
  35004. }
  35005. },
  35006. };
  35007. }
  35008. function createCSSResolvers(config) {
  35009. let cssResolve;
  35010. let sassResolve;
  35011. let lessResolve;
  35012. return {
  35013. get css() {
  35014. return (cssResolve ||
  35015. (cssResolve = config.createResolver({
  35016. extensions: ['.css'],
  35017. mainFields: ['style'],
  35018. conditions: ['style'],
  35019. tryIndex: false,
  35020. preferRelative: true,
  35021. })));
  35022. },
  35023. get sass() {
  35024. return (sassResolve ||
  35025. (sassResolve = config.createResolver({
  35026. extensions: ['.scss', '.sass', '.css'],
  35027. mainFields: ['sass', 'style'],
  35028. conditions: ['sass', 'style'],
  35029. tryIndex: true,
  35030. tryPrefix: '_',
  35031. preferRelative: true,
  35032. })));
  35033. },
  35034. get less() {
  35035. return (lessResolve ||
  35036. (lessResolve = config.createResolver({
  35037. extensions: ['.less', '.css'],
  35038. mainFields: ['less', 'style'],
  35039. conditions: ['less', 'style'],
  35040. tryIndex: false,
  35041. preferRelative: true,
  35042. })));
  35043. },
  35044. };
  35045. }
  35046. function getCssResolversKeys(resolvers) {
  35047. return Object.keys(resolvers);
  35048. }
  35049. const configToAtImportResolvers = new WeakMap();
  35050. async function compileCSS(id, code, config, urlReplacer) {
  35051. const { modules: modulesOptions, preprocessorOptions, devSourcemap, } = config.css || {};
  35052. const isModule = modulesOptions !== false && cssModuleRE.test(id);
  35053. // although at serve time it can work without processing, we do need to
  35054. // crawl them in order to register watch dependencies.
  35055. const needInlineImport = code.includes('@import');
  35056. const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
  35057. const lang = id.match(CSS_LANGS_RE)?.[1];
  35058. const postcssConfig = await resolvePostcssConfig(config);
  35059. // 1. plain css that needs no processing
  35060. if (lang === 'css' &&
  35061. !postcssConfig &&
  35062. !isModule &&
  35063. !needInlineImport &&
  35064. !hasUrl) {
  35065. return { code, map: null };
  35066. }
  35067. let preprocessorMap;
  35068. let modules;
  35069. const deps = new Set();
  35070. let atImportResolvers = configToAtImportResolvers.get(config);
  35071. if (!atImportResolvers) {
  35072. atImportResolvers = createCSSResolvers(config);
  35073. configToAtImportResolvers.set(config, atImportResolvers);
  35074. }
  35075. // 2. pre-processors: sass etc.
  35076. if (isPreProcessor(lang)) {
  35077. const preProcessor = preProcessors[lang];
  35078. let opts = (preprocessorOptions && preprocessorOptions[lang]) || {};
  35079. // support @import from node dependencies by default
  35080. switch (lang) {
  35081. case "scss" /* PreprocessLang.scss */:
  35082. case "sass" /* PreprocessLang.sass */:
  35083. opts = {
  35084. includePaths: ['node_modules'],
  35085. alias: config.resolve.alias,
  35086. ...opts,
  35087. };
  35088. break;
  35089. case "less" /* PreprocessLang.less */:
  35090. case "styl" /* PreprocessLang.styl */:
  35091. case "stylus" /* PreprocessLang.stylus */:
  35092. opts = {
  35093. paths: ['node_modules'],
  35094. alias: config.resolve.alias,
  35095. ...opts,
  35096. };
  35097. }
  35098. // important: set this for relative import resolving
  35099. opts.filename = cleanUrl(id);
  35100. opts.enableSourcemap = devSourcemap ?? false;
  35101. const preprocessResult = await preProcessor(code, config.root, opts, atImportResolvers);
  35102. if (preprocessResult.error) {
  35103. throw preprocessResult.error;
  35104. }
  35105. code = preprocessResult.code;
  35106. preprocessorMap = combineSourcemapsIfExists(opts.filename, preprocessResult.map, preprocessResult.additionalMap);
  35107. if (preprocessResult.deps) {
  35108. preprocessResult.deps.forEach((dep) => {
  35109. // sometimes sass registers the file itself as a dep
  35110. if (normalizePath$3(dep) !== normalizePath$3(opts.filename)) {
  35111. deps.add(dep);
  35112. }
  35113. });
  35114. }
  35115. }
  35116. // 3. postcss
  35117. const postcssOptions = (postcssConfig && postcssConfig.options) || {};
  35118. const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
  35119. if (needInlineImport) {
  35120. postcssPlugins.unshift((await importPostcssImport()).default({
  35121. async resolve(id, basedir) {
  35122. const publicFile = checkPublicFile(id, config);
  35123. if (publicFile) {
  35124. return publicFile;
  35125. }
  35126. const resolved = await atImportResolvers.css(id, path$o.join(basedir, '*'));
  35127. if (resolved) {
  35128. return path$o.resolve(resolved);
  35129. }
  35130. // postcss-import falls back to `resolve` dep if this is unresolved,
  35131. // but we've shimmed to remove the `resolve` dep to cut on bundle size.
  35132. // warn here to provide a better error message.
  35133. if (!path$o.isAbsolute(id)) {
  35134. config.logger.error(colors$1.red(`Unable to resolve \`@import "${id}"\` from ${basedir}`));
  35135. }
  35136. return id;
  35137. },
  35138. nameLayer(index) {
  35139. return `vite--anon-layer-${getHash(id)}-${index}`;
  35140. },
  35141. }));
  35142. }
  35143. if (urlReplacer) {
  35144. postcssPlugins.push(UrlRewritePostcssPlugin({
  35145. replacer: urlReplacer,
  35146. logger: config.logger,
  35147. }));
  35148. }
  35149. if (isModule) {
  35150. postcssPlugins.unshift((await importPostcssModules()).default({
  35151. ...modulesOptions,
  35152. localsConvention: modulesOptions?.localsConvention,
  35153. getJSON(cssFileName, _modules, outputFileName) {
  35154. modules = _modules;
  35155. if (modulesOptions && typeof modulesOptions.getJSON === 'function') {
  35156. modulesOptions.getJSON(cssFileName, _modules, outputFileName);
  35157. }
  35158. },
  35159. async resolve(id, importer) {
  35160. for (const key of getCssResolversKeys(atImportResolvers)) {
  35161. const resolved = await atImportResolvers[key](id, importer);
  35162. if (resolved) {
  35163. return path$o.resolve(resolved);
  35164. }
  35165. }
  35166. return id;
  35167. },
  35168. }));
  35169. }
  35170. if (!postcssPlugins.length) {
  35171. return {
  35172. code,
  35173. map: preprocessorMap,
  35174. };
  35175. }
  35176. let postcssResult;
  35177. try {
  35178. const source = removeDirectQuery(id);
  35179. const postcss = await importPostcss();
  35180. // postcss is an unbundled dep and should be lazy imported
  35181. postcssResult = await postcss.default(postcssPlugins).process(code, {
  35182. ...postcssOptions,
  35183. parser: lang === 'sss'
  35184. ? loadPreprocessor("sugarss" /* PostCssDialectLang.sss */, config.root)
  35185. : postcssOptions.parser,
  35186. to: source,
  35187. from: source,
  35188. ...(devSourcemap
  35189. ? {
  35190. map: {
  35191. inline: false,
  35192. annotation: false,
  35193. // postcss may return virtual files
  35194. // we cannot obtain content of them, so this needs to be enabled
  35195. sourcesContent: true,
  35196. // when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
  35197. // prev: preprocessorMap,
  35198. },
  35199. }
  35200. : {}),
  35201. });
  35202. // record CSS dependencies from @imports
  35203. for (const message of postcssResult.messages) {
  35204. if (message.type === 'dependency') {
  35205. deps.add(normalizePath$3(message.file));
  35206. }
  35207. else if (message.type === 'dir-dependency') {
  35208. // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
  35209. const { dir, glob: globPattern = '**' } = message;
  35210. const pattern = glob.escapePath(normalizePath$3(path$o.resolve(path$o.dirname(id), dir))) +
  35211. `/` +
  35212. globPattern;
  35213. const files = glob.sync(pattern, {
  35214. ignore: ['**/node_modules/**'],
  35215. });
  35216. for (let i = 0; i < files.length; i++) {
  35217. deps.add(files[i]);
  35218. }
  35219. }
  35220. else if (message.type === 'warning') {
  35221. let msg = `[vite:css] ${message.text}`;
  35222. if (message.line && message.column) {
  35223. msg += `\n${generateCodeFrame(code, {
  35224. line: message.line,
  35225. column: message.column,
  35226. })}`;
  35227. }
  35228. config.logger.warn(colors$1.yellow(msg));
  35229. }
  35230. }
  35231. }
  35232. catch (e) {
  35233. e.message = `[postcss] ${e.message}`;
  35234. e.code = code;
  35235. e.loc = {
  35236. column: e.column,
  35237. line: e.line,
  35238. };
  35239. throw e;
  35240. }
  35241. if (!devSourcemap) {
  35242. return {
  35243. ast: postcssResult,
  35244. code: postcssResult.css,
  35245. map: { mappings: '' },
  35246. modules,
  35247. deps,
  35248. };
  35249. }
  35250. const rawPostcssMap = postcssResult.map.toJSON();
  35251. const postcssMap = await formatPostcssSourceMap(
  35252. // version property of rawPostcssMap is declared as string
  35253. // but actually it is a number
  35254. rawPostcssMap, cleanUrl(id));
  35255. return {
  35256. ast: postcssResult,
  35257. code: postcssResult.css,
  35258. map: combineSourcemapsIfExists(cleanUrl(id), postcssMap, preprocessorMap),
  35259. modules,
  35260. deps,
  35261. };
  35262. }
  35263. function createCachedImport(imp) {
  35264. let cached;
  35265. return () => {
  35266. if (!cached) {
  35267. cached = imp().then((module) => {
  35268. cached = module;
  35269. return module;
  35270. });
  35271. }
  35272. return cached;
  35273. };
  35274. }
  35275. const importPostcssImport = createCachedImport(() => import('./dep-5673ffe5.js').then(function (n) { return n.i; }));
  35276. const importPostcssModules = createCachedImport(() => import('./dep-8989cf2a.js').then(function (n) { return n.i; }));
  35277. const importPostcss = createCachedImport(() => import('postcss'));
  35278. /**
  35279. * @experimental
  35280. */
  35281. async function preprocessCSS(code, filename, config) {
  35282. return await compileCSS(filename, code, config);
  35283. }
  35284. const postcssReturnsVirtualFilesRE = /^<.+>$/;
  35285. async function formatPostcssSourceMap(rawMap, file) {
  35286. const inputFileDir = path$o.dirname(file);
  35287. const sources = rawMap.sources.map((source) => {
  35288. const cleanSource = cleanUrl(decodeURIComponent(source));
  35289. if (postcssReturnsVirtualFilesRE.test(cleanSource)) {
  35290. return `\0${cleanSource}`;
  35291. }
  35292. return normalizePath$3(path$o.resolve(inputFileDir, cleanSource));
  35293. });
  35294. return {
  35295. file,
  35296. mappings: rawMap.mappings,
  35297. names: rawMap.names,
  35298. sources,
  35299. sourcesContent: rawMap.sourcesContent,
  35300. version: rawMap.version,
  35301. };
  35302. }
  35303. function combineSourcemapsIfExists(filename, map1, map2) {
  35304. return map1 && map2
  35305. ? combineSourcemaps(filename, [
  35306. // type of version property of ExistingRawSourceMap is number
  35307. // but it is always 3
  35308. map1,
  35309. map2,
  35310. ])
  35311. : map1;
  35312. }
  35313. async function finalizeCss(css, minify, config) {
  35314. // hoist external @imports and @charset to the top of the CSS chunk per spec (#1845 and #6333)
  35315. if (css.includes('@import') || css.includes('@charset')) {
  35316. css = await hoistAtRules(css);
  35317. }
  35318. if (minify && config.build.cssMinify) {
  35319. css = await minifyCSS(css, config);
  35320. }
  35321. return css;
  35322. }
  35323. async function resolvePostcssConfig(config) {
  35324. let result = postcssConfigCache.get(config);
  35325. if (result !== undefined) {
  35326. return await result;
  35327. }
  35328. // inline postcss config via vite config
  35329. const inlineOptions = config.css?.postcss;
  35330. if (isObject$2(inlineOptions)) {
  35331. const options = { ...inlineOptions };
  35332. delete options.plugins;
  35333. result = {
  35334. options,
  35335. plugins: inlineOptions.plugins || [],
  35336. };
  35337. }
  35338. else {
  35339. const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
  35340. result = postcssrc({}, searchPath).catch((e) => {
  35341. if (!/No PostCSS Config found/.test(e.message)) {
  35342. if (e instanceof Error) {
  35343. const { name, message, stack } = e;
  35344. e.name = 'Failed to load PostCSS config';
  35345. e.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name}] ${message}\n${stack}`;
  35346. e.stack = ''; // add stack to message to retain stack
  35347. throw e;
  35348. }
  35349. else {
  35350. throw new Error(`Failed to load PostCSS config: ${e}`);
  35351. }
  35352. }
  35353. return null;
  35354. });
  35355. // replace cached promise to result object when finished
  35356. result.then((resolved) => {
  35357. postcssConfigCache.set(config, resolved);
  35358. });
  35359. }
  35360. postcssConfigCache.set(config, result);
  35361. return result;
  35362. }
  35363. // https://drafts.csswg.org/css-syntax-3/#identifier-code-point
  35364. const cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
  35365. const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
  35366. const importCssRE = /@import ('[^']+\.css'|"[^"]+\.css"|[^'")]+\.css)/;
  35367. // Assuming a function name won't be longer than 256 chars
  35368. // eslint-disable-next-line regexp/no-unused-capturing-group -- doesn't detect asyncReplace usage
  35369. const cssImageSetRE = /(?<=image-set\()((?:[\w\-]{1,256}\([^)]*\)|[^)])*)(?=\))/;
  35370. const UrlRewritePostcssPlugin = (opts) => {
  35371. if (!opts) {
  35372. throw new Error('base or replace is required');
  35373. }
  35374. return {
  35375. postcssPlugin: 'vite-url-rewrite',
  35376. Once(root) {
  35377. const promises = [];
  35378. root.walkDecls((declaration) => {
  35379. const importer = declaration.source?.input.file;
  35380. if (!importer) {
  35381. opts.logger.warnOnce('\nA PostCSS plugin did not pass the `from` option to `postcss.parse`. ' +
  35382. 'This may cause imported assets to be incorrectly transformed. ' +
  35383. "If you've recently added a PostCSS plugin that raised this warning, " +
  35384. 'please contact the package author to fix the issue.');
  35385. }
  35386. const isCssUrl = cssUrlRE.test(declaration.value);
  35387. const isCssImageSet = cssImageSetRE.test(declaration.value);
  35388. if (isCssUrl || isCssImageSet) {
  35389. const replacerForDeclaration = (rawUrl) => {
  35390. return opts.replacer(rawUrl, importer);
  35391. };
  35392. const rewriterToUse = isCssImageSet
  35393. ? rewriteCssImageSet
  35394. : rewriteCssUrls;
  35395. promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => {
  35396. declaration.value = url;
  35397. }));
  35398. }
  35399. });
  35400. if (promises.length) {
  35401. return Promise.all(promises);
  35402. }
  35403. },
  35404. };
  35405. };
  35406. UrlRewritePostcssPlugin.postcss = true;
  35407. function rewriteCssUrls(css, replacer) {
  35408. return asyncReplace(css, cssUrlRE, async (match) => {
  35409. const [matched, rawUrl] = match;
  35410. return await doUrlReplace(rawUrl.trim(), matched, replacer);
  35411. });
  35412. }
  35413. function rewriteCssDataUris(css, replacer) {
  35414. return asyncReplace(css, cssDataUriRE, async (match) => {
  35415. const [matched, rawUrl] = match;
  35416. return await doUrlReplace(rawUrl.trim(), matched, replacer, 'data-uri');
  35417. });
  35418. }
  35419. function rewriteImportCss(css, replacer) {
  35420. return asyncReplace(css, importCssRE, async (match) => {
  35421. const [matched, rawUrl] = match;
  35422. return await doImportCSSReplace(rawUrl, matched, replacer);
  35423. });
  35424. }
  35425. // TODO: image and cross-fade could contain a "url" that needs to be processed
  35426. // https://drafts.csswg.org/css-images-4/#image-notation
  35427. // https://drafts.csswg.org/css-images-4/#cross-fade-function
  35428. const cssNotProcessedRE = /(?:gradient|element|cross-fade|image)\(/;
  35429. async function rewriteCssImageSet(css, replacer) {
  35430. return await asyncReplace(css, cssImageSetRE, async (match) => {
  35431. const [, rawUrl] = match;
  35432. const url = await processSrcSet(rawUrl, async ({ url }) => {
  35433. // the url maybe url(...)
  35434. if (cssUrlRE.test(url)) {
  35435. return await rewriteCssUrls(url, replacer);
  35436. }
  35437. if (!cssNotProcessedRE.test(url)) {
  35438. return await doUrlReplace(url, url, replacer);
  35439. }
  35440. return url;
  35441. });
  35442. return url;
  35443. });
  35444. }
  35445. async function doUrlReplace(rawUrl, matched, replacer, funcName = 'url') {
  35446. let wrap = '';
  35447. const first = rawUrl[0];
  35448. if (first === `"` || first === `'`) {
  35449. wrap = first;
  35450. rawUrl = rawUrl.slice(1, -1);
  35451. }
  35452. if (isExternalUrl(rawUrl) ||
  35453. isDataUrl(rawUrl) ||
  35454. rawUrl[0] === '#' ||
  35455. varRE.test(rawUrl)) {
  35456. return matched;
  35457. }
  35458. const newUrl = await replacer(rawUrl);
  35459. if (wrap === '' && newUrl !== encodeURI(newUrl)) {
  35460. // The new url might need wrapping even if the original did not have it, e.g. if a space was added during replacement
  35461. wrap = "'";
  35462. }
  35463. return `${funcName}(${wrap}${newUrl}${wrap})`;
  35464. }
  35465. async function doImportCSSReplace(rawUrl, matched, replacer) {
  35466. let wrap = '';
  35467. const first = rawUrl[0];
  35468. if (first === `"` || first === `'`) {
  35469. wrap = first;
  35470. rawUrl = rawUrl.slice(1, -1);
  35471. }
  35472. if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === '#') {
  35473. return matched;
  35474. }
  35475. return `@import ${wrap}${await replacer(rawUrl)}${wrap}`;
  35476. }
  35477. async function minifyCSS(css, config) {
  35478. try {
  35479. const { code, warnings } = await transform$2(css, {
  35480. loader: 'css',
  35481. target: config.build.cssTarget || undefined,
  35482. charset: 'utf8',
  35483. ...resolveEsbuildMinifyOptions(config.esbuild || {}),
  35484. });
  35485. if (warnings.length) {
  35486. const msgs = await formatMessages(warnings, { kind: 'warning' });
  35487. config.logger.warn(colors$1.yellow(`warnings when minifying css:\n${msgs.join('\n')}`));
  35488. }
  35489. return code;
  35490. }
  35491. catch (e) {
  35492. if (e.errors) {
  35493. e.message = '[esbuild css minify] ' + e.message;
  35494. const msgs = await formatMessages(e.errors, { kind: 'error' });
  35495. e.frame = '\n' + msgs.join('\n');
  35496. e.loc = e.errors[0].location;
  35497. }
  35498. throw e;
  35499. }
  35500. }
  35501. function resolveEsbuildMinifyOptions(options) {
  35502. const base = {
  35503. logLevel: options.logLevel,
  35504. logLimit: options.logLimit,
  35505. logOverride: options.logOverride,
  35506. };
  35507. if (options.minifyIdentifiers != null ||
  35508. options.minifySyntax != null ||
  35509. options.minifyWhitespace != null) {
  35510. return {
  35511. ...base,
  35512. minifyIdentifiers: options.minifyIdentifiers ?? true,
  35513. minifySyntax: options.minifySyntax ?? true,
  35514. minifyWhitespace: options.minifyWhitespace ?? true,
  35515. };
  35516. }
  35517. else {
  35518. return { ...base, minify: true };
  35519. }
  35520. }
  35521. async function hoistAtRules(css) {
  35522. const s = new MagicString(css);
  35523. const cleanCss = emptyCssComments(css);
  35524. let match;
  35525. // #1845
  35526. // CSS @import can only appear at top of the file. We need to hoist all @import
  35527. // to top when multiple files are concatenated.
  35528. // match until semicolon that's not in quotes
  35529. const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  35530. while ((match = atImportRE.exec(cleanCss))) {
  35531. s.remove(match.index, match.index + match[0].length);
  35532. // Use `appendLeft` instead of `prepend` to preserve original @import order
  35533. s.appendLeft(0, match[0]);
  35534. }
  35535. // #6333
  35536. // CSS @charset must be the top-first in the file, hoist the first to top
  35537. const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  35538. let foundCharset = false;
  35539. while ((match = atCharsetRE.exec(cleanCss))) {
  35540. s.remove(match.index, match.index + match[0].length);
  35541. if (!foundCharset) {
  35542. s.prepend(match[0]);
  35543. foundCharset = true;
  35544. }
  35545. }
  35546. return s.toString();
  35547. }
  35548. const loadedPreprocessors = {};
  35549. // TODO: use dynamic import
  35550. const _require$1 = createRequire$1(import.meta.url);
  35551. function loadPreprocessor(lang, root) {
  35552. if (lang in loadedPreprocessors) {
  35553. return loadedPreprocessors[lang];
  35554. }
  35555. try {
  35556. const resolved = requireResolveFromRootWithFallback(root, lang);
  35557. return (loadedPreprocessors[lang] = _require$1(resolved));
  35558. }
  35559. catch (e) {
  35560. if (e.code === 'MODULE_NOT_FOUND') {
  35561. throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it?`);
  35562. }
  35563. else {
  35564. const message = new Error(`Preprocessor dependency "${lang}" failed to load:\n${e.message}`);
  35565. message.stack = e.stack + '\n' + message.stack;
  35566. throw message;
  35567. }
  35568. }
  35569. }
  35570. // in unix, scss might append `location.href` in environments that shim `location`
  35571. // see https://github.com/sass/dart-sass/issues/710
  35572. function cleanScssBugUrl(url) {
  35573. if (
  35574. // check bug via `window` and `location` global
  35575. typeof window !== 'undefined' &&
  35576. typeof location !== 'undefined' &&
  35577. typeof location?.href === 'string') {
  35578. const prefix = location.href.replace(/\/$/, '');
  35579. return url.replace(prefix, '');
  35580. }
  35581. else {
  35582. return url;
  35583. }
  35584. }
  35585. function fixScssBugImportValue(data) {
  35586. // the scss bug doesn't load files properly so we have to load it ourselves
  35587. // to prevent internal error when it loads itself
  35588. if (
  35589. // check bug via `window` and `location` global
  35590. typeof window !== 'undefined' &&
  35591. typeof location !== 'undefined' &&
  35592. data &&
  35593. 'file' in data &&
  35594. (!('contents' in data) || data.contents == null)) {
  35595. // @ts-expect-error we need to preserve file property for HMR
  35596. data.contents = fs$l.readFileSync(data.file, 'utf-8');
  35597. }
  35598. return data;
  35599. }
  35600. // .scss/.sass processor
  35601. const scss = async (source, root, options, resolvers) => {
  35602. const render = loadPreprocessor("sass" /* PreprocessLang.sass */, root).render;
  35603. // NOTE: `sass` always runs it's own importer first, and only falls back to
  35604. // the `importer` option when it can't resolve a path
  35605. const internalImporter = (url, importer, done) => {
  35606. importer = cleanScssBugUrl(importer);
  35607. resolvers.sass(url, importer).then((resolved) => {
  35608. if (resolved) {
  35609. rebaseUrls(resolved, options.filename, options.alias, '$')
  35610. .then((data) => done?.(fixScssBugImportValue(data)))
  35611. .catch((data) => done?.(data));
  35612. }
  35613. else {
  35614. done?.(null);
  35615. }
  35616. });
  35617. };
  35618. const importer = [internalImporter];
  35619. if (options.importer) {
  35620. Array.isArray(options.importer)
  35621. ? importer.unshift(...options.importer)
  35622. : importer.unshift(options.importer);
  35623. }
  35624. const { content: data, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  35625. const finalOptions = {
  35626. ...options,
  35627. data,
  35628. file: options.filename,
  35629. outFile: options.filename,
  35630. importer,
  35631. ...(options.enableSourcemap
  35632. ? {
  35633. sourceMap: true,
  35634. omitSourceMapUrl: true,
  35635. sourceMapRoot: path$o.dirname(options.filename),
  35636. }
  35637. : {}),
  35638. };
  35639. try {
  35640. const result = await new Promise((resolve, reject) => {
  35641. render(finalOptions, (err, res) => {
  35642. if (err) {
  35643. reject(err);
  35644. }
  35645. else {
  35646. resolve(res);
  35647. }
  35648. });
  35649. });
  35650. const deps = result.stats.includedFiles.map((f) => cleanScssBugUrl(f));
  35651. const map = result.map
  35652. ? JSON.parse(result.map.toString())
  35653. : undefined;
  35654. return {
  35655. code: result.css.toString(),
  35656. map,
  35657. additionalMap,
  35658. deps,
  35659. };
  35660. }
  35661. catch (e) {
  35662. // normalize SASS error
  35663. e.message = `[sass] ${e.message}`;
  35664. e.id = e.file;
  35665. e.frame = e.formatted;
  35666. return { code: '', error: e, deps: [] };
  35667. }
  35668. };
  35669. const sass = (source, root, options, aliasResolver) => scss(source, root, {
  35670. ...options,
  35671. indentedSyntax: true,
  35672. }, aliasResolver);
  35673. /**
  35674. * relative url() inside \@imported sass and less files must be rebased to use
  35675. * root file as base.
  35676. */
  35677. async function rebaseUrls(file, rootFile, alias, variablePrefix) {
  35678. file = path$o.resolve(file); // ensure os-specific flashes
  35679. // in the same dir, no need to rebase
  35680. const fileDir = path$o.dirname(file);
  35681. const rootDir = path$o.dirname(rootFile);
  35682. if (fileDir === rootDir) {
  35683. return { file };
  35684. }
  35685. const content = await fsp.readFile(file, 'utf-8');
  35686. // no url()
  35687. const hasUrls = cssUrlRE.test(content);
  35688. // data-uri() calls
  35689. const hasDataUris = cssDataUriRE.test(content);
  35690. // no @import xxx.css
  35691. const hasImportCss = importCssRE.test(content);
  35692. if (!hasUrls && !hasDataUris && !hasImportCss) {
  35693. return { file };
  35694. }
  35695. let rebased;
  35696. const rebaseFn = (url) => {
  35697. if (url[0] === '/')
  35698. return url;
  35699. // ignore url's starting with variable
  35700. if (url.startsWith(variablePrefix))
  35701. return url;
  35702. // match alias, no need to rewrite
  35703. for (const { find } of alias) {
  35704. const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
  35705. if (matches) {
  35706. return url;
  35707. }
  35708. }
  35709. const absolute = path$o.resolve(fileDir, url);
  35710. const relative = path$o.relative(rootDir, absolute);
  35711. return normalizePath$3(relative);
  35712. };
  35713. // fix css imports in less such as `@import "foo.css"`
  35714. if (hasImportCss) {
  35715. rebased = await rewriteImportCss(content, rebaseFn);
  35716. }
  35717. if (hasUrls) {
  35718. rebased = await rewriteCssUrls(rebased || content, rebaseFn);
  35719. }
  35720. if (hasDataUris) {
  35721. rebased = await rewriteCssDataUris(rebased || content, rebaseFn);
  35722. }
  35723. return {
  35724. file,
  35725. contents: rebased,
  35726. };
  35727. }
  35728. // .less
  35729. const less = async (source, root, options, resolvers) => {
  35730. const nodeLess = loadPreprocessor("less" /* PreprocessLang.less */, root);
  35731. const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers);
  35732. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  35733. let result;
  35734. try {
  35735. result = await nodeLess.render(content, {
  35736. ...options,
  35737. plugins: [viteResolverPlugin, ...(options.plugins || [])],
  35738. ...(options.enableSourcemap
  35739. ? {
  35740. sourceMap: {
  35741. outputSourceFiles: true,
  35742. sourceMapFileInline: false,
  35743. },
  35744. }
  35745. : {}),
  35746. });
  35747. }
  35748. catch (e) {
  35749. const error = e;
  35750. // normalize error info
  35751. const normalizedError = new Error(`[less] ${error.message || error.type}`);
  35752. normalizedError.loc = {
  35753. file: error.filename || options.filename,
  35754. line: error.line,
  35755. column: error.column,
  35756. };
  35757. return { code: '', error: normalizedError, deps: [] };
  35758. }
  35759. const map = result.map && JSON.parse(result.map);
  35760. if (map) {
  35761. delete map.sourcesContent;
  35762. }
  35763. return {
  35764. code: result.css.toString(),
  35765. map,
  35766. additionalMap,
  35767. deps: result.imports,
  35768. };
  35769. };
  35770. /**
  35771. * Less manager, lazy initialized
  35772. */
  35773. let ViteLessManager;
  35774. function createViteLessPlugin(less, rootFile, alias, resolvers) {
  35775. if (!ViteLessManager) {
  35776. ViteLessManager = class ViteManager extends less.FileManager {
  35777. constructor(rootFile, resolvers, alias) {
  35778. super();
  35779. this.rootFile = rootFile;
  35780. this.resolvers = resolvers;
  35781. this.alias = alias;
  35782. }
  35783. supports(filename) {
  35784. return !isExternalUrl(filename);
  35785. }
  35786. supportsSync() {
  35787. return false;
  35788. }
  35789. async loadFile(filename, dir, opts, env) {
  35790. const resolved = await this.resolvers.less(filename, path$o.join(dir, '*'));
  35791. if (resolved) {
  35792. const result = await rebaseUrls(resolved, this.rootFile, this.alias, '@');
  35793. let contents;
  35794. if (result && 'contents' in result) {
  35795. contents = result.contents;
  35796. }
  35797. else {
  35798. contents = await fsp.readFile(resolved, 'utf-8');
  35799. }
  35800. return {
  35801. filename: path$o.resolve(resolved),
  35802. contents,
  35803. };
  35804. }
  35805. else {
  35806. return super.loadFile(filename, dir, opts, env);
  35807. }
  35808. }
  35809. };
  35810. }
  35811. return {
  35812. install(_, pluginManager) {
  35813. pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias));
  35814. },
  35815. minVersion: [3, 0, 0],
  35816. };
  35817. }
  35818. // .styl
  35819. const styl = async (source, root, options) => {
  35820. const nodeStylus = loadPreprocessor("stylus" /* PreprocessLang.stylus */, root);
  35821. // Get source with preprocessor options.additionalData. Make sure a new line separator
  35822. // is added to avoid any render error, as added stylus content may not have semi-colon separators
  35823. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap, '\n');
  35824. // Get preprocessor options.imports dependencies as stylus
  35825. // does not return them with its builtin `.deps()` method
  35826. const importsDeps = (options.imports ?? []).map((dep) => path$o.resolve(dep));
  35827. try {
  35828. const ref = nodeStylus(content, options);
  35829. if (options.define) {
  35830. for (const key in options.define) {
  35831. ref.define(key, options.define[key]);
  35832. }
  35833. }
  35834. if (options.enableSourcemap) {
  35835. ref.set('sourcemap', {
  35836. comment: false,
  35837. inline: false,
  35838. basePath: root,
  35839. });
  35840. }
  35841. const result = ref.render();
  35842. // Concat imports deps with computed deps
  35843. const deps = [...ref.deps(), ...importsDeps];
  35844. // @ts-expect-error sourcemap exists
  35845. const map = ref.sourcemap;
  35846. return {
  35847. code: result,
  35848. map: formatStylusSourceMap(map, root),
  35849. additionalMap,
  35850. deps,
  35851. };
  35852. }
  35853. catch (e) {
  35854. e.message = `[stylus] ${e.message}`;
  35855. return { code: '', error: e, deps: [] };
  35856. }
  35857. };
  35858. function formatStylusSourceMap(mapBefore, root) {
  35859. if (!mapBefore)
  35860. return undefined;
  35861. const map = { ...mapBefore };
  35862. const resolveFromRoot = (p) => normalizePath$3(path$o.resolve(root, p));
  35863. if (map.file) {
  35864. map.file = resolveFromRoot(map.file);
  35865. }
  35866. map.sources = map.sources.map(resolveFromRoot);
  35867. return map;
  35868. }
  35869. async function getSource(source, filename, additionalData, enableSourcemap, sep = '') {
  35870. if (!additionalData)
  35871. return { content: source };
  35872. if (typeof additionalData === 'function') {
  35873. const newContent = await additionalData(source, filename);
  35874. if (typeof newContent === 'string') {
  35875. return { content: newContent };
  35876. }
  35877. return newContent;
  35878. }
  35879. if (!enableSourcemap) {
  35880. return { content: additionalData + sep + source };
  35881. }
  35882. const ms = new MagicString(source);
  35883. ms.appendLeft(0, sep);
  35884. ms.appendLeft(0, additionalData);
  35885. const map = ms.generateMap({ hires: true });
  35886. map.file = filename;
  35887. map.sources = [filename];
  35888. return {
  35889. content: ms.toString(),
  35890. map,
  35891. };
  35892. }
  35893. const preProcessors = Object.freeze({
  35894. ["less" /* PreprocessLang.less */]: less,
  35895. ["sass" /* PreprocessLang.sass */]: sass,
  35896. ["scss" /* PreprocessLang.scss */]: scss,
  35897. ["styl" /* PreprocessLang.styl */]: styl,
  35898. ["stylus" /* PreprocessLang.stylus */]: styl,
  35899. });
  35900. function isPreProcessor(lang) {
  35901. return lang && lang in preProcessors;
  35902. }
  35903. // AST walker module for Mozilla Parser API compatible trees
  35904. function makeTest(test) {
  35905. if (typeof test === "string")
  35906. { return function (type) { return type === test; } }
  35907. else if (!test)
  35908. { return function () { return true; } }
  35909. else
  35910. { return test }
  35911. }
  35912. var Found = function Found(node, state) { this.node = node; this.state = state; };
  35913. // Find a node with a given start, end, and type (all are optional,
  35914. // null can be used as wildcard). Returns a {node, state} object, or
  35915. // undefined when it doesn't find a matching node.
  35916. function findNodeAt(node, start, end, test, baseVisitor, state) {
  35917. if (!baseVisitor) { baseVisitor = base; }
  35918. test = makeTest(test);
  35919. try {
  35920. (function c(node, st, override) {
  35921. var type = override || node.type;
  35922. if ((start == null || node.start <= start) &&
  35923. (end == null || node.end >= end))
  35924. { baseVisitor[type](node, st, c); }
  35925. if ((start == null || node.start === start) &&
  35926. (end == null || node.end === end) &&
  35927. test(type, node))
  35928. { throw new Found(node, st) }
  35929. })(node, state);
  35930. } catch (e) {
  35931. if (e instanceof Found) { return e }
  35932. throw e
  35933. }
  35934. }
  35935. function skipThrough(node, st, c) { c(node, st); }
  35936. function ignore(_node, _st, _c) {}
  35937. // Node walkers.
  35938. var base = {};
  35939. base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
  35940. for (var i = 0, list = node.body; i < list.length; i += 1)
  35941. {
  35942. var stmt = list[i];
  35943. c(stmt, st, "Statement");
  35944. }
  35945. };
  35946. base.Statement = skipThrough;
  35947. base.EmptyStatement = ignore;
  35948. base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
  35949. function (node, st, c) { return c(node.expression, st, "Expression"); };
  35950. base.IfStatement = function (node, st, c) {
  35951. c(node.test, st, "Expression");
  35952. c(node.consequent, st, "Statement");
  35953. if (node.alternate) { c(node.alternate, st, "Statement"); }
  35954. };
  35955. base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  35956. base.BreakStatement = base.ContinueStatement = ignore;
  35957. base.WithStatement = function (node, st, c) {
  35958. c(node.object, st, "Expression");
  35959. c(node.body, st, "Statement");
  35960. };
  35961. base.SwitchStatement = function (node, st, c) {
  35962. c(node.discriminant, st, "Expression");
  35963. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  35964. var cs = list$1[i$1];
  35965. if (cs.test) { c(cs.test, st, "Expression"); }
  35966. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  35967. {
  35968. var cons = list[i];
  35969. c(cons, st, "Statement");
  35970. }
  35971. }
  35972. };
  35973. base.SwitchCase = function (node, st, c) {
  35974. if (node.test) { c(node.test, st, "Expression"); }
  35975. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  35976. {
  35977. var cons = list[i];
  35978. c(cons, st, "Statement");
  35979. }
  35980. };
  35981. base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
  35982. if (node.argument) { c(node.argument, st, "Expression"); }
  35983. };
  35984. base.ThrowStatement = base.SpreadElement =
  35985. function (node, st, c) { return c(node.argument, st, "Expression"); };
  35986. base.TryStatement = function (node, st, c) {
  35987. c(node.block, st, "Statement");
  35988. if (node.handler) { c(node.handler, st); }
  35989. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  35990. };
  35991. base.CatchClause = function (node, st, c) {
  35992. if (node.param) { c(node.param, st, "Pattern"); }
  35993. c(node.body, st, "Statement");
  35994. };
  35995. base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
  35996. c(node.test, st, "Expression");
  35997. c(node.body, st, "Statement");
  35998. };
  35999. base.ForStatement = function (node, st, c) {
  36000. if (node.init) { c(node.init, st, "ForInit"); }
  36001. if (node.test) { c(node.test, st, "Expression"); }
  36002. if (node.update) { c(node.update, st, "Expression"); }
  36003. c(node.body, st, "Statement");
  36004. };
  36005. base.ForInStatement = base.ForOfStatement = function (node, st, c) {
  36006. c(node.left, st, "ForInit");
  36007. c(node.right, st, "Expression");
  36008. c(node.body, st, "Statement");
  36009. };
  36010. base.ForInit = function (node, st, c) {
  36011. if (node.type === "VariableDeclaration") { c(node, st); }
  36012. else { c(node, st, "Expression"); }
  36013. };
  36014. base.DebuggerStatement = ignore;
  36015. base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  36016. base.VariableDeclaration = function (node, st, c) {
  36017. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  36018. {
  36019. var decl = list[i];
  36020. c(decl, st);
  36021. }
  36022. };
  36023. base.VariableDeclarator = function (node, st, c) {
  36024. c(node.id, st, "Pattern");
  36025. if (node.init) { c(node.init, st, "Expression"); }
  36026. };
  36027. base.Function = function (node, st, c) {
  36028. if (node.id) { c(node.id, st, "Pattern"); }
  36029. for (var i = 0, list = node.params; i < list.length; i += 1)
  36030. {
  36031. var param = list[i];
  36032. c(param, st, "Pattern");
  36033. }
  36034. c(node.body, st, node.expression ? "Expression" : "Statement");
  36035. };
  36036. base.Pattern = function (node, st, c) {
  36037. if (node.type === "Identifier")
  36038. { c(node, st, "VariablePattern"); }
  36039. else if (node.type === "MemberExpression")
  36040. { c(node, st, "MemberPattern"); }
  36041. else
  36042. { c(node, st); }
  36043. };
  36044. base.VariablePattern = ignore;
  36045. base.MemberPattern = skipThrough;
  36046. base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  36047. base.ArrayPattern = function (node, st, c) {
  36048. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  36049. var elt = list[i];
  36050. if (elt) { c(elt, st, "Pattern"); }
  36051. }
  36052. };
  36053. base.ObjectPattern = function (node, st, c) {
  36054. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  36055. var prop = list[i];
  36056. if (prop.type === "Property") {
  36057. if (prop.computed) { c(prop.key, st, "Expression"); }
  36058. c(prop.value, st, "Pattern");
  36059. } else if (prop.type === "RestElement") {
  36060. c(prop.argument, st, "Pattern");
  36061. }
  36062. }
  36063. };
  36064. base.Expression = skipThrough;
  36065. base.ThisExpression = base.Super = base.MetaProperty = ignore;
  36066. base.ArrayExpression = function (node, st, c) {
  36067. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  36068. var elt = list[i];
  36069. if (elt) { c(elt, st, "Expression"); }
  36070. }
  36071. };
  36072. base.ObjectExpression = function (node, st, c) {
  36073. for (var i = 0, list = node.properties; i < list.length; i += 1)
  36074. {
  36075. var prop = list[i];
  36076. c(prop, st);
  36077. }
  36078. };
  36079. base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
  36080. base.SequenceExpression = function (node, st, c) {
  36081. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  36082. {
  36083. var expr = list[i];
  36084. c(expr, st, "Expression");
  36085. }
  36086. };
  36087. base.TemplateLiteral = function (node, st, c) {
  36088. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  36089. {
  36090. var quasi = list[i];
  36091. c(quasi, st);
  36092. }
  36093. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  36094. {
  36095. var expr = list$1[i$1];
  36096. c(expr, st, "Expression");
  36097. }
  36098. };
  36099. base.TemplateElement = ignore;
  36100. base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
  36101. c(node.argument, st, "Expression");
  36102. };
  36103. base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
  36104. c(node.left, st, "Expression");
  36105. c(node.right, st, "Expression");
  36106. };
  36107. base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
  36108. c(node.left, st, "Pattern");
  36109. c(node.right, st, "Expression");
  36110. };
  36111. base.ConditionalExpression = function (node, st, c) {
  36112. c(node.test, st, "Expression");
  36113. c(node.consequent, st, "Expression");
  36114. c(node.alternate, st, "Expression");
  36115. };
  36116. base.NewExpression = base.CallExpression = function (node, st, c) {
  36117. c(node.callee, st, "Expression");
  36118. if (node.arguments)
  36119. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  36120. {
  36121. var arg = list[i];
  36122. c(arg, st, "Expression");
  36123. } }
  36124. };
  36125. base.MemberExpression = function (node, st, c) {
  36126. c(node.object, st, "Expression");
  36127. if (node.computed) { c(node.property, st, "Expression"); }
  36128. };
  36129. base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
  36130. if (node.declaration)
  36131. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  36132. if (node.source) { c(node.source, st, "Expression"); }
  36133. };
  36134. base.ExportAllDeclaration = function (node, st, c) {
  36135. if (node.exported)
  36136. { c(node.exported, st); }
  36137. c(node.source, st, "Expression");
  36138. };
  36139. base.ImportDeclaration = function (node, st, c) {
  36140. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  36141. {
  36142. var spec = list[i];
  36143. c(spec, st);
  36144. }
  36145. c(node.source, st, "Expression");
  36146. };
  36147. base.ImportExpression = function (node, st, c) {
  36148. c(node.source, st, "Expression");
  36149. };
  36150. base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
  36151. base.TaggedTemplateExpression = function (node, st, c) {
  36152. c(node.tag, st, "Expression");
  36153. c(node.quasi, st, "Expression");
  36154. };
  36155. base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  36156. base.Class = function (node, st, c) {
  36157. if (node.id) { c(node.id, st, "Pattern"); }
  36158. if (node.superClass) { c(node.superClass, st, "Expression"); }
  36159. c(node.body, st);
  36160. };
  36161. base.ClassBody = function (node, st, c) {
  36162. for (var i = 0, list = node.body; i < list.length; i += 1)
  36163. {
  36164. var elt = list[i];
  36165. c(elt, st);
  36166. }
  36167. };
  36168. base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
  36169. if (node.computed) { c(node.key, st, "Expression"); }
  36170. if (node.value) { c(node.value, st, "Expression"); }
  36171. };
  36172. const { isMatch: isMatch$1, scan } = micromatch$2;
  36173. function getAffectedGlobModules(file, server) {
  36174. const modules = [];
  36175. for (const [id, allGlobs] of server._importGlobMap) {
  36176. if (allGlobs.some((glob) => isMatch$1(file, glob)))
  36177. modules.push(...(server.moduleGraph.getModulesByFile(id) || []));
  36178. }
  36179. modules.forEach((i) => {
  36180. if (i?.file)
  36181. server.moduleGraph.onFileChange(i.file);
  36182. });
  36183. return modules;
  36184. }
  36185. function importGlobPlugin(config) {
  36186. let server;
  36187. return {
  36188. name: 'vite:import-glob',
  36189. configureServer(_server) {
  36190. server = _server;
  36191. server._importGlobMap.clear();
  36192. },
  36193. async transform(code, id) {
  36194. if (!code.includes('import.meta.glob'))
  36195. return;
  36196. const result = await transformGlobImport(code, id, config.root, (im) => this.resolve(im, id).then((i) => i?.id || im), config.isProduction, config.experimental.importGlobRestoreExtension);
  36197. if (result) {
  36198. if (server) {
  36199. const allGlobs = result.matches.map((i) => i.globsResolved);
  36200. server._importGlobMap.set(id, allGlobs);
  36201. }
  36202. return transformStableResult(result.s, id, config);
  36203. }
  36204. },
  36205. };
  36206. }
  36207. const importGlobRE = /\bimport\.meta\.(glob|globEager|globEagerDefault)(?:<\w+>)?\s*\(/g;
  36208. const knownOptions = {
  36209. as: ['string'],
  36210. eager: ['boolean'],
  36211. import: ['string'],
  36212. exhaustive: ['boolean'],
  36213. query: ['object', 'string'],
  36214. };
  36215. const forceDefaultAs = ['raw', 'url'];
  36216. function err$1(e, pos) {
  36217. const error = new Error(e);
  36218. error.pos = pos;
  36219. return error;
  36220. }
  36221. function parseGlobOptions(rawOpts, optsStartIndex) {
  36222. let opts = {};
  36223. try {
  36224. opts = evalValue(rawOpts);
  36225. }
  36226. catch {
  36227. throw err$1('Vite is unable to parse the glob options as the value is not static', optsStartIndex);
  36228. }
  36229. if (opts == null) {
  36230. return {};
  36231. }
  36232. for (const key in opts) {
  36233. if (!(key in knownOptions)) {
  36234. throw err$1(`Unknown glob option "${key}"`, optsStartIndex);
  36235. }
  36236. const allowedTypes = knownOptions[key];
  36237. const valueType = typeof opts[key];
  36238. if (!allowedTypes.includes(valueType)) {
  36239. throw err$1(`Expected glob option "${key}" to be of type ${allowedTypes.join(' or ')}, but got ${valueType}`, optsStartIndex);
  36240. }
  36241. }
  36242. if (typeof opts.query === 'object') {
  36243. for (const key in opts.query) {
  36244. const value = opts.query[key];
  36245. if (!['string', 'number', 'boolean'].includes(typeof value)) {
  36246. throw err$1(`Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value}`, optsStartIndex);
  36247. }
  36248. }
  36249. }
  36250. if (opts.as && forceDefaultAs.includes(opts.as)) {
  36251. if (opts.import && opts.import !== 'default' && opts.import !== '*')
  36252. throw err$1(`Option "import" can only be "default" or "*" when "as" is "${opts.as}", but got "${opts.import}"`, optsStartIndex);
  36253. opts.import = opts.import || 'default';
  36254. }
  36255. if (opts.as && opts.query)
  36256. throw err$1('Options "as" and "query" cannot be used together', optsStartIndex);
  36257. if (opts.as)
  36258. opts.query = opts.as;
  36259. return opts;
  36260. }
  36261. async function parseImportGlob(code, importer, root, resolveId) {
  36262. let cleanCode;
  36263. try {
  36264. cleanCode = stripLiteral(code);
  36265. }
  36266. catch (e) {
  36267. // skip invalid js code
  36268. return [];
  36269. }
  36270. const matches = Array.from(cleanCode.matchAll(importGlobRE));
  36271. const tasks = matches.map(async (match, index) => {
  36272. const type = match[1];
  36273. const start = match.index;
  36274. const err = (msg) => {
  36275. const e = new Error(`Invalid glob import syntax: ${msg}`);
  36276. e.pos = start;
  36277. return e;
  36278. };
  36279. let ast;
  36280. let lastTokenPos;
  36281. try {
  36282. ast = parseExpressionAt(code, start, {
  36283. ecmaVersion: 'latest',
  36284. sourceType: 'module',
  36285. ranges: true,
  36286. onToken: (token) => {
  36287. lastTokenPos = token.end;
  36288. },
  36289. });
  36290. }
  36291. catch (e) {
  36292. const _e = e;
  36293. if (_e.message && _e.message.startsWith('Unterminated string constant'))
  36294. return undefined;
  36295. if (lastTokenPos == null || lastTokenPos <= start)
  36296. throw _e;
  36297. // tailing comma in object or array will make the parser think it's a comma operation
  36298. // we try to parse again removing the comma
  36299. try {
  36300. const statement = code.slice(start, lastTokenPos).replace(/[,\s]*$/, '');
  36301. ast = parseExpressionAt(' '.repeat(start) + statement, // to keep the ast position
  36302. start, {
  36303. ecmaVersion: 'latest',
  36304. sourceType: 'module',
  36305. ranges: true,
  36306. });
  36307. }
  36308. catch {
  36309. throw _e;
  36310. }
  36311. }
  36312. const found = findNodeAt(ast, start, undefined, 'CallExpression');
  36313. if (!found)
  36314. throw err(`Expect CallExpression, got ${ast.type}`);
  36315. ast = found.node;
  36316. if (ast.arguments.length < 1 || ast.arguments.length > 2)
  36317. throw err(`Expected 1-2 arguments, but got ${ast.arguments.length}`);
  36318. const arg1 = ast.arguments[0];
  36319. const arg2 = ast.arguments[1];
  36320. const globs = [];
  36321. const validateLiteral = (element) => {
  36322. if (!element)
  36323. return;
  36324. if (element.type === 'Literal') {
  36325. if (typeof element.value !== 'string')
  36326. throw err(`Expected glob to be a string, but got "${typeof element.value}"`);
  36327. globs.push(element.value);
  36328. }
  36329. else if (element.type === 'TemplateLiteral') {
  36330. if (element.expressions.length !== 0) {
  36331. throw err(`Expected glob to be a string, but got dynamic template literal`);
  36332. }
  36333. globs.push(element.quasis[0].value.raw);
  36334. }
  36335. else {
  36336. throw err('Could only use literals');
  36337. }
  36338. };
  36339. if (arg1.type === 'ArrayExpression') {
  36340. for (const element of arg1.elements) {
  36341. validateLiteral(element);
  36342. }
  36343. }
  36344. else {
  36345. validateLiteral(arg1);
  36346. }
  36347. // arg2
  36348. let options = {};
  36349. if (arg2) {
  36350. if (arg2.type !== 'ObjectExpression')
  36351. throw err(`Expected the second argument to be an object literal, but got "${arg2.type}"`);
  36352. options = parseGlobOptions(code.slice(arg2.range[0], arg2.range[1]), arg2.range[0]);
  36353. }
  36354. const end = ast.range[1];
  36355. const globsResolved = await Promise.all(globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId)));
  36356. const isRelative = globs.every((i) => '.!'.includes(i[0]));
  36357. return {
  36358. match,
  36359. index,
  36360. globs,
  36361. globsResolved,
  36362. isRelative,
  36363. options,
  36364. type,
  36365. start,
  36366. end,
  36367. };
  36368. });
  36369. return (await Promise.all(tasks)).filter(Boolean);
  36370. }
  36371. const importPrefix = '__vite_glob_';
  36372. const { basename, dirname, relative, join } = posix$1;
  36373. const warnedCSSDefaultImportVarName = '__vite_warned_css_default_import';
  36374. const jsonStringifyInOneline = (input) => JSON.stringify(input).replace(/[{,:]/g, '$& ').replace(/\}/g, ' }');
  36375. const createCssDefaultImportWarning = (globs, options) => `if (!${warnedCSSDefaultImportVarName}) {` +
  36376. `${warnedCSSDefaultImportVarName} = true;` +
  36377. `console.warn(${JSON.stringify('Default import of CSS without `?inline` is deprecated. ' +
  36378. "Add the `{ query: '?inline' }` glob option to fix this.\n" +
  36379. `For example: \`import.meta.glob(${jsonStringifyInOneline(globs.length === 1 ? globs[0] : globs)}, ${jsonStringifyInOneline({ ...options, query: '?inline' })})\``)});` +
  36380. `}`;
  36381. /**
  36382. * @param optimizeExport for dynamicImportVar plugin don't need to optimize export.
  36383. */
  36384. async function transformGlobImport(code, id, root, resolveId, isProduction, restoreQueryExtension = false) {
  36385. id = slash$1(id);
  36386. root = slash$1(root);
  36387. const isVirtual = isVirtualModule(id);
  36388. const dir = isVirtual ? undefined : dirname(id);
  36389. const matches = await parseImportGlob(code, isVirtual ? undefined : id, root, resolveId);
  36390. const matchedFiles = new Set();
  36391. // TODO: backwards compatibility
  36392. matches.forEach((i) => {
  36393. if (i.type === 'globEager')
  36394. i.options.eager = true;
  36395. if (i.type === 'globEagerDefault') {
  36396. i.options.eager = true;
  36397. i.options.import = 'default';
  36398. }
  36399. });
  36400. if (!matches.length)
  36401. return null;
  36402. const s = new MagicString(code);
  36403. const staticImports = (await Promise.all(matches.map(async ({ globs, globsResolved, isRelative, options, index, start, end, }) => {
  36404. const cwd = getCommonBase(globsResolved) ?? root;
  36405. const files = (await glob(globsResolved, {
  36406. cwd,
  36407. absolute: true,
  36408. dot: !!options.exhaustive,
  36409. ignore: options.exhaustive
  36410. ? []
  36411. : [join(cwd, '**/node_modules/**')],
  36412. }))
  36413. .filter((file) => file !== id)
  36414. .sort();
  36415. const objectProps = [];
  36416. const staticImports = [];
  36417. let query = !options.query
  36418. ? ''
  36419. : typeof options.query === 'string'
  36420. ? options.query
  36421. : stringifyQuery(options.query);
  36422. if (query && query[0] !== '?')
  36423. query = `?${query}`;
  36424. const resolvePaths = (file) => {
  36425. if (!dir) {
  36426. if (isRelative)
  36427. throw new Error("In virtual modules, all globs must start with '/'");
  36428. const filePath = `/${relative(root, file)}`;
  36429. return { filePath, importPath: filePath };
  36430. }
  36431. let importPath = relative(dir, file);
  36432. if (importPath[0] !== '.')
  36433. importPath = `./${importPath}`;
  36434. let filePath;
  36435. if (isRelative) {
  36436. filePath = importPath;
  36437. }
  36438. else {
  36439. filePath = relative(root, file);
  36440. if (filePath[0] !== '.')
  36441. filePath = `/${filePath}`;
  36442. }
  36443. return { filePath, importPath };
  36444. };
  36445. let includesCSS = false;
  36446. files.forEach((file, i) => {
  36447. const paths = resolvePaths(file);
  36448. const filePath = paths.filePath;
  36449. let importPath = paths.importPath;
  36450. let importQuery = query;
  36451. if (importQuery && importQuery !== '?raw') {
  36452. const fileExtension = basename(file).split('.').slice(-1)[0];
  36453. if (fileExtension && restoreQueryExtension)
  36454. importQuery = `${importQuery}&lang.${fileExtension}`;
  36455. }
  36456. importPath = `${importPath}${importQuery}`;
  36457. const isCSS = !query && isCSSRequest(file) && !isModuleCSSRequest(file);
  36458. includesCSS || (includesCSS = isCSS);
  36459. const importKey = options.import && options.import !== '*'
  36460. ? options.import
  36461. : undefined;
  36462. if (options.eager) {
  36463. const variableName = `${importPrefix}${index}_${i}`;
  36464. const expression = importKey
  36465. ? `{ ${importKey} as ${variableName} }`
  36466. : `* as ${variableName}`;
  36467. staticImports.push(`import ${expression} from ${JSON.stringify(importPath)}`);
  36468. if (!isProduction && isCSS) {
  36469. objectProps.push(`get ${JSON.stringify(filePath)}() { ${createCssDefaultImportWarning(globs, options)} return ${variableName} }`);
  36470. }
  36471. else {
  36472. objectProps.push(`${JSON.stringify(filePath)}: ${variableName}`);
  36473. }
  36474. }
  36475. else {
  36476. let importStatement = `import(${JSON.stringify(importPath)})`;
  36477. if (importKey)
  36478. importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
  36479. if (!isProduction && isCSS) {
  36480. objectProps.push(`${JSON.stringify(filePath)}: () => { ${createCssDefaultImportWarning(globs, options)} return ${importStatement}}`);
  36481. }
  36482. else {
  36483. objectProps.push(`${JSON.stringify(filePath)}: () => ${importStatement}`);
  36484. }
  36485. }
  36486. });
  36487. files.forEach((i) => matchedFiles.add(i));
  36488. const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0;
  36489. const lineBreaks = originalLineBreakCount > 0
  36490. ? '\n'.repeat(originalLineBreakCount)
  36491. : '';
  36492. let replacement;
  36493. if (!isProduction && includesCSS) {
  36494. replacement =
  36495. '/* #__PURE__ */ Object.assign(' +
  36496. '(() => {' +
  36497. `let ${warnedCSSDefaultImportVarName} = false;` +
  36498. `return {${objectProps.join(',')}${lineBreaks}};` +
  36499. '})()' +
  36500. ')';
  36501. }
  36502. else {
  36503. replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(',')}${lineBreaks}})`;
  36504. }
  36505. s.overwrite(start, end, replacement);
  36506. return staticImports;
  36507. }))).flat();
  36508. if (staticImports.length)
  36509. s.prepend(`${staticImports.join(';')};`);
  36510. return {
  36511. s,
  36512. matches,
  36513. files: matchedFiles,
  36514. };
  36515. }
  36516. function globSafePath(path) {
  36517. // slash path to ensure \ is converted to / as \ could lead to a double escape scenario
  36518. // see https://github.com/mrmlnc/fast-glob#advanced-syntax
  36519. return glob.escapePath(normalizePath$3(path));
  36520. }
  36521. function lastNthChar(str, n) {
  36522. return str.charAt(str.length - 1 - n);
  36523. }
  36524. function globSafeResolvedPath(resolved, glob) {
  36525. // we have to escape special glob characters in the resolved path, but keep the user specified globby suffix
  36526. // walk back both strings until a character difference is found
  36527. // then slice up the resolved path at that pos and escape the first part
  36528. let numEqual = 0;
  36529. const maxEqual = Math.min(resolved.length, glob.length);
  36530. while (numEqual < maxEqual &&
  36531. lastNthChar(resolved, numEqual) === lastNthChar(glob, numEqual)) {
  36532. numEqual += 1;
  36533. }
  36534. const staticPartEnd = resolved.length - numEqual;
  36535. const staticPart = resolved.slice(0, staticPartEnd);
  36536. const dynamicPart = resolved.slice(staticPartEnd);
  36537. return globSafePath(staticPart) + dynamicPart;
  36538. }
  36539. async function toAbsoluteGlob(glob, root, importer, resolveId) {
  36540. let pre = '';
  36541. if (glob[0] === '!') {
  36542. pre = '!';
  36543. glob = glob.slice(1);
  36544. }
  36545. root = globSafePath(root);
  36546. const dir = importer ? globSafePath(dirname(importer)) : root;
  36547. if (glob[0] === '/')
  36548. return pre + posix$1.join(root, glob.slice(1));
  36549. if (glob.startsWith('./'))
  36550. return pre + posix$1.join(dir, glob.slice(2));
  36551. if (glob.startsWith('../'))
  36552. return pre + posix$1.join(dir, glob);
  36553. if (glob.startsWith('**'))
  36554. return pre + glob;
  36555. const resolved = normalizePath$3((await resolveId(glob, importer)) || glob);
  36556. if (isAbsolute$2(resolved)) {
  36557. return pre + globSafeResolvedPath(resolved, glob);
  36558. }
  36559. throw new Error(`Invalid glob: "${glob}" (resolved: "${resolved}"). It must start with '/' or './'`);
  36560. }
  36561. function getCommonBase(globsResolved) {
  36562. const bases = globsResolved
  36563. .filter((g) => g[0] !== '!')
  36564. .map((glob) => {
  36565. let { base } = scan(glob);
  36566. // `scan('a/foo.js')` returns `base: 'a/foo.js'`
  36567. if (posix$1.basename(base).includes('.'))
  36568. base = posix$1.dirname(base);
  36569. return base;
  36570. });
  36571. if (!bases.length)
  36572. return null;
  36573. let commonAncestor = '';
  36574. const dirS = bases[0].split('/');
  36575. for (let i = 0; i < dirS.length; i++) {
  36576. const candidate = dirS.slice(0, i + 1).join('/');
  36577. if (bases.every((base) => base.startsWith(candidate)))
  36578. commonAncestor = candidate;
  36579. else
  36580. break;
  36581. }
  36582. if (!commonAncestor)
  36583. commonAncestor = '/';
  36584. return commonAncestor;
  36585. }
  36586. function isVirtualModule(id) {
  36587. // https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention
  36588. return id.startsWith('virtual:') || id[0] === '\0' || !id.includes('/');
  36589. }
  36590. const debugHmr = createDebugger('vite:hmr');
  36591. const whitespaceRE = /\s/;
  36592. const normalizedClientDir = normalizePath$3(CLIENT_DIR);
  36593. function getShortName(file, root) {
  36594. return file.startsWith(root + '/') ? path$o.posix.relative(root, file) : file;
  36595. }
  36596. async function handleHMRUpdate(file, server, configOnly) {
  36597. const { ws, config, moduleGraph } = server;
  36598. const shortFile = getShortName(file, config.root);
  36599. const fileName = path$o.basename(file);
  36600. const isConfig = file === config.configFile;
  36601. const isConfigDependency = config.configFileDependencies.some((name) => file === name);
  36602. const isEnv = config.inlineConfig.envFile !== false &&
  36603. (fileName === '.env' || fileName.startsWith('.env.'));
  36604. if (isConfig || isConfigDependency || isEnv) {
  36605. // auto restart server
  36606. debugHmr?.(`[config change] ${colors$1.dim(shortFile)}`);
  36607. config.logger.info(colors$1.green(`${path$o.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true });
  36608. try {
  36609. await server.restart();
  36610. }
  36611. catch (e) {
  36612. config.logger.error(colors$1.red(e));
  36613. }
  36614. return;
  36615. }
  36616. if (configOnly) {
  36617. return;
  36618. }
  36619. debugHmr?.(`[file change] ${colors$1.dim(shortFile)}`);
  36620. // (dev only) the client itself cannot be hot updated.
  36621. if (file.startsWith(normalizedClientDir)) {
  36622. ws.send({
  36623. type: 'full-reload',
  36624. path: '*',
  36625. });
  36626. return;
  36627. }
  36628. const mods = moduleGraph.getModulesByFile(file);
  36629. // check if any plugin wants to perform custom HMR handling
  36630. const timestamp = Date.now();
  36631. const hmrContext = {
  36632. file,
  36633. timestamp,
  36634. modules: mods ? [...mods] : [],
  36635. read: () => readModifiedFile(file),
  36636. server,
  36637. };
  36638. for (const hook of config.getSortedPluginHooks('handleHotUpdate')) {
  36639. const filteredModules = await hook(hmrContext);
  36640. if (filteredModules) {
  36641. hmrContext.modules = filteredModules;
  36642. }
  36643. }
  36644. if (!hmrContext.modules.length) {
  36645. // html file cannot be hot updated
  36646. if (file.endsWith('.html')) {
  36647. config.logger.info(colors$1.green(`page reload `) + colors$1.dim(shortFile), {
  36648. clear: true,
  36649. timestamp: true,
  36650. });
  36651. ws.send({
  36652. type: 'full-reload',
  36653. path: config.server.middlewareMode
  36654. ? '*'
  36655. : '/' + normalizePath$3(path$o.relative(config.root, file)),
  36656. });
  36657. }
  36658. else {
  36659. // loaded but not in the module graph, probably not js
  36660. debugHmr?.(`[no modules matched] ${colors$1.dim(shortFile)}`);
  36661. }
  36662. return;
  36663. }
  36664. updateModules(shortFile, hmrContext.modules, timestamp, server);
  36665. }
  36666. function updateModules(file, modules, timestamp, { config, ws, moduleGraph }, afterInvalidation) {
  36667. const updates = [];
  36668. const invalidatedModules = new Set();
  36669. const traversedModules = new Set();
  36670. let needFullReload = false;
  36671. for (const mod of modules) {
  36672. moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true);
  36673. if (needFullReload) {
  36674. continue;
  36675. }
  36676. const boundaries = [];
  36677. const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries);
  36678. if (hasDeadEnd) {
  36679. needFullReload = true;
  36680. continue;
  36681. }
  36682. updates.push(...boundaries.map(({ boundary, acceptedVia }) => ({
  36683. type: `${boundary.type}-update`,
  36684. timestamp,
  36685. path: normalizeHmrUrl(boundary.url),
  36686. explicitImportRequired: boundary.type === 'js'
  36687. ? isExplicitImportRequired(acceptedVia.url)
  36688. : undefined,
  36689. acceptedPath: normalizeHmrUrl(acceptedVia.url),
  36690. })));
  36691. }
  36692. if (needFullReload) {
  36693. config.logger.info(colors$1.green(`page reload `) + colors$1.dim(file), {
  36694. clear: !afterInvalidation,
  36695. timestamp: true,
  36696. });
  36697. ws.send({
  36698. type: 'full-reload',
  36699. });
  36700. return;
  36701. }
  36702. if (updates.length === 0) {
  36703. debugHmr?.(colors$1.yellow(`no update happened `) + colors$1.dim(file));
  36704. return;
  36705. }
  36706. config.logger.info(colors$1.green(`hmr update `) +
  36707. colors$1.dim([...new Set(updates.map((u) => u.path))].join(', ')), { clear: !afterInvalidation, timestamp: true });
  36708. ws.send({
  36709. type: 'update',
  36710. updates,
  36711. });
  36712. }
  36713. async function handleFileAddUnlink(file, server) {
  36714. const modules = [...(server.moduleGraph.getModulesByFile(file) || [])];
  36715. modules.push(...getAffectedGlobModules(file, server));
  36716. if (modules.length > 0) {
  36717. updateModules(getShortName(file, server.config.root), unique(modules), Date.now(), server);
  36718. }
  36719. }
  36720. function areAllImportsAccepted(importedBindings, acceptedExports) {
  36721. for (const binding of importedBindings) {
  36722. if (!acceptedExports.has(binding)) {
  36723. return false;
  36724. }
  36725. }
  36726. return true;
  36727. }
  36728. function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) {
  36729. if (traversedModules.has(node)) {
  36730. return false;
  36731. }
  36732. traversedModules.add(node);
  36733. // #7561
  36734. // if the imports of `node` have not been analyzed, then `node` has not
  36735. // been loaded in the browser and we should stop propagation.
  36736. if (node.id && node.isSelfAccepting === undefined) {
  36737. debugHmr?.(`[propagate update] stop propagation because not analyzed: ${colors$1.dim(node.id)}`);
  36738. return false;
  36739. }
  36740. if (node.isSelfAccepting) {
  36741. boundaries.push({ boundary: node, acceptedVia: node });
  36742. // additionally check for CSS importers, since a PostCSS plugin like
  36743. // Tailwind JIT may register any file as a dependency to a CSS file.
  36744. for (const importer of node.importers) {
  36745. if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
  36746. propagateUpdate(importer, traversedModules, boundaries, currentChain.concat(importer));
  36747. }
  36748. }
  36749. return false;
  36750. }
  36751. // A partially accepted module with no importers is considered self accepting,
  36752. // because the deal is "there are parts of myself I can't self accept if they
  36753. // are used outside of me".
  36754. // Also, the imported module (this one) must be updated before the importers,
  36755. // so that they do get the fresh imported module when/if they are reloaded.
  36756. if (node.acceptedHmrExports) {
  36757. boundaries.push({ boundary: node, acceptedVia: node });
  36758. }
  36759. else {
  36760. if (!node.importers.size) {
  36761. return true;
  36762. }
  36763. // #3716, #3913
  36764. // For a non-CSS file, if all of its importers are CSS files (registered via
  36765. // PostCSS plugins) it should be considered a dead end and force full reload.
  36766. if (!isCSSRequest(node.url) &&
  36767. [...node.importers].every((i) => isCSSRequest(i.url))) {
  36768. return true;
  36769. }
  36770. }
  36771. for (const importer of node.importers) {
  36772. const subChain = currentChain.concat(importer);
  36773. if (importer.acceptedHmrDeps.has(node)) {
  36774. boundaries.push({ boundary: importer, acceptedVia: node });
  36775. continue;
  36776. }
  36777. if (node.id && node.acceptedHmrExports && importer.importedBindings) {
  36778. const importedBindingsFromNode = importer.importedBindings.get(node.id);
  36779. if (importedBindingsFromNode &&
  36780. areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) {
  36781. continue;
  36782. }
  36783. }
  36784. if (currentChain.includes(importer)) {
  36785. // circular deps is considered dead end
  36786. return true;
  36787. }
  36788. if (propagateUpdate(importer, traversedModules, boundaries, subChain)) {
  36789. return true;
  36790. }
  36791. }
  36792. return false;
  36793. }
  36794. function handlePrunedModules(mods, { ws }) {
  36795. // update the disposed modules' hmr timestamp
  36796. // since if it's re-imported, it should re-apply side effects
  36797. // and without the timestamp the browser will not re-import it!
  36798. const t = Date.now();
  36799. mods.forEach((mod) => {
  36800. mod.lastHMRTimestamp = t;
  36801. debugHmr?.(`[dispose] ${colors$1.dim(mod.file)}`);
  36802. });
  36803. ws.send({
  36804. type: 'prune',
  36805. paths: [...mods].map((m) => m.url),
  36806. });
  36807. }
  36808. /**
  36809. * Lex import.meta.hot.accept() for accepted deps.
  36810. * Since hot.accept() can only accept string literals or array of string
  36811. * literals, we don't really need a heavy @babel/parse call on the entire source.
  36812. *
  36813. * @returns selfAccepts
  36814. */
  36815. function lexAcceptedHmrDeps(code, start, urls) {
  36816. let state = 0 /* LexerState.inCall */;
  36817. // the state can only be 2 levels deep so no need for a stack
  36818. let prevState = 0 /* LexerState.inCall */;
  36819. let currentDep = '';
  36820. function addDep(index) {
  36821. urls.add({
  36822. url: currentDep,
  36823. start: index - currentDep.length - 1,
  36824. end: index + 1,
  36825. });
  36826. currentDep = '';
  36827. }
  36828. for (let i = start; i < code.length; i++) {
  36829. const char = code.charAt(i);
  36830. switch (state) {
  36831. case 0 /* LexerState.inCall */:
  36832. case 4 /* LexerState.inArray */:
  36833. if (char === `'`) {
  36834. prevState = state;
  36835. state = 1 /* LexerState.inSingleQuoteString */;
  36836. }
  36837. else if (char === `"`) {
  36838. prevState = state;
  36839. state = 2 /* LexerState.inDoubleQuoteString */;
  36840. }
  36841. else if (char === '`') {
  36842. prevState = state;
  36843. state = 3 /* LexerState.inTemplateString */;
  36844. }
  36845. else if (whitespaceRE.test(char)) {
  36846. continue;
  36847. }
  36848. else {
  36849. if (state === 0 /* LexerState.inCall */) {
  36850. if (char === `[`) {
  36851. state = 4 /* LexerState.inArray */;
  36852. }
  36853. else {
  36854. // reaching here means the first arg is neither a string literal
  36855. // nor an Array literal (direct callback) or there is no arg
  36856. // in both case this indicates a self-accepting module
  36857. return true; // done
  36858. }
  36859. }
  36860. else if (state === 4 /* LexerState.inArray */) {
  36861. if (char === `]`) {
  36862. return false; // done
  36863. }
  36864. else if (char === ',') {
  36865. continue;
  36866. }
  36867. else {
  36868. error$1(i);
  36869. }
  36870. }
  36871. }
  36872. break;
  36873. case 1 /* LexerState.inSingleQuoteString */:
  36874. if (char === `'`) {
  36875. addDep(i);
  36876. if (prevState === 0 /* LexerState.inCall */) {
  36877. // accept('foo', ...)
  36878. return false;
  36879. }
  36880. else {
  36881. state = prevState;
  36882. }
  36883. }
  36884. else {
  36885. currentDep += char;
  36886. }
  36887. break;
  36888. case 2 /* LexerState.inDoubleQuoteString */:
  36889. if (char === `"`) {
  36890. addDep(i);
  36891. if (prevState === 0 /* LexerState.inCall */) {
  36892. // accept('foo', ...)
  36893. return false;
  36894. }
  36895. else {
  36896. state = prevState;
  36897. }
  36898. }
  36899. else {
  36900. currentDep += char;
  36901. }
  36902. break;
  36903. case 3 /* LexerState.inTemplateString */:
  36904. if (char === '`') {
  36905. addDep(i);
  36906. if (prevState === 0 /* LexerState.inCall */) {
  36907. // accept('foo', ...)
  36908. return false;
  36909. }
  36910. else {
  36911. state = prevState;
  36912. }
  36913. }
  36914. else if (char === '$' && code.charAt(i + 1) === '{') {
  36915. error$1(i);
  36916. }
  36917. else {
  36918. currentDep += char;
  36919. }
  36920. break;
  36921. default:
  36922. throw new Error('unknown import.meta.hot lexer state');
  36923. }
  36924. }
  36925. return false;
  36926. }
  36927. function lexAcceptedHmrExports(code, start, exportNames) {
  36928. const urls = new Set();
  36929. lexAcceptedHmrDeps(code, start, urls);
  36930. for (const { url } of urls) {
  36931. exportNames.add(url);
  36932. }
  36933. return urls.size > 0;
  36934. }
  36935. function normalizeHmrUrl(url) {
  36936. if (url[0] !== '.' && url[0] !== '/') {
  36937. url = wrapId(url);
  36938. }
  36939. return url;
  36940. }
  36941. function error$1(pos) {
  36942. const err = new Error(`import.meta.hot.accept() can only accept string literals or an ` +
  36943. `Array of string literals.`);
  36944. err.pos = pos;
  36945. throw err;
  36946. }
  36947. // vitejs/vite#610 when hot-reloading Vue files, we read immediately on file
  36948. // change event and sometimes this can be too early and get an empty buffer.
  36949. // Poll until the file's modified time has changed before reading again.
  36950. async function readModifiedFile(file) {
  36951. const content = await fsp.readFile(file, 'utf-8');
  36952. if (!content) {
  36953. const mtime = (await fsp.stat(file)).mtimeMs;
  36954. await new Promise((r) => {
  36955. let n = 0;
  36956. const poll = async () => {
  36957. n++;
  36958. const newMtime = (await fsp.stat(file)).mtimeMs;
  36959. if (newMtime !== mtime || n > 10) {
  36960. r(0);
  36961. }
  36962. else {
  36963. setTimeout(poll, 10);
  36964. }
  36965. };
  36966. setTimeout(poll, 10);
  36967. });
  36968. return await fsp.readFile(file, 'utf-8');
  36969. }
  36970. else {
  36971. return content;
  36972. }
  36973. }
  36974. const debug$a = createDebugger('vite:import-analysis');
  36975. const clientDir = normalizePath$3(CLIENT_DIR);
  36976. const skipRE = /\.(?:map|json)(?:$|\?)/;
  36977. const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
  36978. const optimizedDepChunkRE$1 = /\/chunk-[A-Z\d]{8}\.js/;
  36979. const optimizedDepDynamicRE$1 = /-[A-Z\d]{8}\.js/;
  36980. const hasImportInQueryParamsRE = /[?&]import=?\b/;
  36981. const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
  36982. const cleanUpRawUrlRE = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm;
  36983. const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
  36984. function isExplicitImportRequired(url) {
  36985. return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url);
  36986. }
  36987. function markExplicitImport(url) {
  36988. if (isExplicitImportRequired(url)) {
  36989. return injectQuery(url, 'import');
  36990. }
  36991. return url;
  36992. }
  36993. function extractImportedBindings(id, source, importSpec, importedBindings) {
  36994. let bindings = importedBindings.get(id);
  36995. if (!bindings) {
  36996. bindings = new Set();
  36997. importedBindings.set(id, bindings);
  36998. }
  36999. const isDynamic = importSpec.d > -1;
  37000. const isMeta = importSpec.d === -2;
  37001. if (isDynamic || isMeta) {
  37002. // this basically means the module will be impacted by any change in its dep
  37003. bindings.add('*');
  37004. return;
  37005. }
  37006. const exp = source.slice(importSpec.ss, importSpec.se);
  37007. const [match0] = findStaticImports(exp);
  37008. if (!match0) {
  37009. return;
  37010. }
  37011. const parsed = parseStaticImport(match0);
  37012. if (!parsed) {
  37013. return;
  37014. }
  37015. if (parsed.namespacedImport) {
  37016. bindings.add('*');
  37017. }
  37018. if (parsed.defaultImport) {
  37019. bindings.add('default');
  37020. }
  37021. if (parsed.namedImports) {
  37022. for (const name of Object.keys(parsed.namedImports)) {
  37023. bindings.add(name);
  37024. }
  37025. }
  37026. }
  37027. /**
  37028. * Server-only plugin that lexes, resolves, rewrites and analyzes url imports.
  37029. *
  37030. * - Imports are resolved to ensure they exist on disk
  37031. *
  37032. * - Lexes HMR accept calls and updates import relationships in the module graph
  37033. *
  37034. * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
  37035. * absolute file paths, e.g.
  37036. *
  37037. * ```js
  37038. * import 'foo'
  37039. * ```
  37040. * is rewritten to
  37041. * ```js
  37042. * import '/@fs//project/node_modules/foo/dist/foo.js'
  37043. * ```
  37044. *
  37045. * - CSS imports are appended with `.js` since both the js module and the actual
  37046. * css (referenced via `<link>`) may go through the transform pipeline:
  37047. *
  37048. * ```js
  37049. * import './style.css'
  37050. * ```
  37051. * is rewritten to
  37052. * ```js
  37053. * import './style.css.js'
  37054. * ```
  37055. */
  37056. function importAnalysisPlugin(config) {
  37057. const { root, base } = config;
  37058. const clientPublicPath = path$o.posix.join(base, CLIENT_PUBLIC_PATH);
  37059. const enablePartialAccept = config.experimental?.hmrPartialAccept;
  37060. let server;
  37061. let _env;
  37062. function getEnv(ssr) {
  37063. if (!_env) {
  37064. _env = `import.meta.env = ${JSON.stringify({
  37065. ...config.env,
  37066. SSR: '__vite__ssr__',
  37067. })};`;
  37068. // account for user env defines
  37069. for (const key in config.define) {
  37070. if (key.startsWith(`import.meta.env.`)) {
  37071. const val = config.define[key];
  37072. _env += `${key} = ${typeof val === 'string' ? val : JSON.stringify(val)};`;
  37073. }
  37074. }
  37075. }
  37076. return _env.replace('"__vite__ssr__"', ssr + '');
  37077. }
  37078. return {
  37079. name: 'vite:import-analysis',
  37080. configureServer(_server) {
  37081. server = _server;
  37082. },
  37083. async transform(source, importer, options) {
  37084. // In a real app `server` is always defined, but it is undefined when
  37085. // running src/node/server/__tests__/pluginContainer.spec.ts
  37086. if (!server) {
  37087. return null;
  37088. }
  37089. const ssr = options?.ssr === true;
  37090. const prettyImporter = prettifyUrl(importer, root);
  37091. if (canSkipImportAnalysis(importer)) {
  37092. debug$a?.(colors$1.dim(`[skipped] ${prettyImporter}`));
  37093. return null;
  37094. }
  37095. const start = performance$1.now();
  37096. await init;
  37097. let imports;
  37098. let exports;
  37099. source = stripBomTag(source);
  37100. try {
  37101. [imports, exports] = parse$e(source);
  37102. }
  37103. catch (e) {
  37104. const isVue = importer.endsWith('.vue');
  37105. const isJsx = importer.endsWith('.jsx') || importer.endsWith('.tsx');
  37106. const maybeJSX = !isVue && isJSRequest(importer);
  37107. const msg = isVue
  37108. ? `Install @vitejs/plugin-vue to handle .vue files.`
  37109. : maybeJSX
  37110. ? isJsx
  37111. ? `If you use tsconfig.json, make sure to not set jsx to preserve.`
  37112. : `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.`
  37113. : `You may need to install appropriate plugins to handle the ${path$o.extname(importer)} file format, or if it's an asset, add "**/*${path$o.extname(importer)}" to \`assetsInclude\` in your configuration.`;
  37114. this.error(`Failed to parse source for import analysis because the content ` +
  37115. `contains invalid JS syntax. ` +
  37116. msg, e.idx);
  37117. }
  37118. const depsOptimizer = getDepsOptimizer(config, ssr);
  37119. const { moduleGraph } = server;
  37120. // since we are already in the transform phase of the importer, it must
  37121. // have been loaded so its entry is guaranteed in the module graph.
  37122. const importerModule = moduleGraph.getModuleById(importer);
  37123. if (!importerModule && depsOptimizer?.isOptimizedDepFile(importer)) {
  37124. // Ids of optimized deps could be invalidated and removed from the graph
  37125. // Return without transforming, this request is no longer valid, a full reload
  37126. // is going to request this id again. Throwing an outdated error so we
  37127. // properly finish the request with a 504 sent to the browser.
  37128. throwOutdatedRequest(importer);
  37129. }
  37130. if (!imports.length && !this._addedImports) {
  37131. importerModule.isSelfAccepting = false;
  37132. debug$a?.(`${timeFrom(start)} ${colors$1.dim(`[no imports] ${prettyImporter}`)}`);
  37133. return source;
  37134. }
  37135. let hasHMR = false;
  37136. let isSelfAccepting = false;
  37137. let hasEnv = false;
  37138. let needQueryInjectHelper = false;
  37139. let s;
  37140. const str = () => s || (s = new MagicString(source));
  37141. const importedUrls = new Set();
  37142. let isPartiallySelfAccepting = false;
  37143. const importedBindings = enablePartialAccept
  37144. ? new Map()
  37145. : null;
  37146. const toAbsoluteUrl = (url) => path$o.posix.resolve(path$o.posix.dirname(importerModule.url), url);
  37147. const normalizeUrl = async (url, pos, forceSkipImportAnalysis = false) => {
  37148. url = stripBase(url, base);
  37149. let importerFile = importer;
  37150. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  37151. if (moduleListContains(optimizeDeps?.exclude, url)) {
  37152. if (depsOptimizer) {
  37153. await depsOptimizer.scanProcessing;
  37154. // if the dependency encountered in the optimized file was excluded from the optimization
  37155. // the dependency needs to be resolved starting from the original source location of the optimized file
  37156. // because starting from node_modules/.vite will not find the dependency if it was not hoisted
  37157. // (that is, if it is under node_modules directory in the package source of the optimized file)
  37158. for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
  37159. if (!optimizedModule.src)
  37160. continue; // Ignore chunks
  37161. if (optimizedModule.file === importerModule.file) {
  37162. importerFile = optimizedModule.src;
  37163. }
  37164. }
  37165. }
  37166. }
  37167. const resolved = await this.resolve(url, importerFile);
  37168. if (!resolved) {
  37169. // in ssr, we should let node handle the missing modules
  37170. if (ssr) {
  37171. return [url, url];
  37172. }
  37173. // fix#9534, prevent the importerModuleNode being stopped from propagating updates
  37174. importerModule.isSelfAccepting = false;
  37175. return this.error(`Failed to resolve import "${url}" from "${path$o.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
  37176. }
  37177. const isRelative = url[0] === '.';
  37178. const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
  37179. // normalize all imports into resolved URLs
  37180. // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
  37181. if (resolved.id.startsWith(root + '/')) {
  37182. // in root: infer short absolute path from root
  37183. url = resolved.id.slice(root.length);
  37184. }
  37185. else if (depsOptimizer?.isOptimizedDepFile(resolved.id) ||
  37186. fs$l.existsSync(cleanUrl(resolved.id))) {
  37187. // an optimized deps may not yet exists in the filesystem, or
  37188. // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
  37189. url = path$o.posix.join(FS_PREFIX, resolved.id);
  37190. }
  37191. else {
  37192. url = resolved.id;
  37193. }
  37194. if (isExternalUrl(url)) {
  37195. return [url, url];
  37196. }
  37197. // if the resolved id is not a valid browser import specifier,
  37198. // prefix it to make it valid. We will strip this before feeding it
  37199. // back into the transform pipeline
  37200. if (url[0] !== '.' && url[0] !== '/') {
  37201. url = wrapId(resolved.id);
  37202. }
  37203. // make the URL browser-valid if not SSR
  37204. if (!ssr) {
  37205. // mark non-js/css imports with `?import`
  37206. url = markExplicitImport(url);
  37207. // If the url isn't a request for a pre-bundled common chunk,
  37208. // for relative js/css imports, or self-module virtual imports
  37209. // (e.g. vue blocks), inherit importer's version query
  37210. // do not do this for unknown type imports, otherwise the appended
  37211. // query can break 3rd party plugin's extension checks.
  37212. if ((isRelative || isSelfImport) &&
  37213. !hasImportInQueryParamsRE.test(url) &&
  37214. !url.match(DEP_VERSION_RE)) {
  37215. const versionMatch = importer.match(DEP_VERSION_RE);
  37216. if (versionMatch) {
  37217. url = injectQuery(url, versionMatch[1]);
  37218. }
  37219. }
  37220. // check if the dep has been hmr updated. If yes, we need to attach
  37221. // its last updated timestamp to force the browser to fetch the most
  37222. // up-to-date version of this module.
  37223. try {
  37224. // delay setting `isSelfAccepting` until the file is actually used (#7870)
  37225. // We use an internal function to avoid resolving the url again
  37226. const depModule = await moduleGraph._ensureEntryFromUrl(unwrapId(url), ssr, canSkipImportAnalysis(url) || forceSkipImportAnalysis, resolved);
  37227. if (depModule.lastHMRTimestamp > 0) {
  37228. url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
  37229. }
  37230. }
  37231. catch (e) {
  37232. // it's possible that the dep fails to resolve (non-existent import)
  37233. // attach location to the missing import
  37234. e.pos = pos;
  37235. throw e;
  37236. }
  37237. // prepend base
  37238. url = joinUrlSegments(base, url);
  37239. }
  37240. return [url, resolved.id];
  37241. };
  37242. const orderedAcceptedUrls = new Array(imports.length);
  37243. const orderedAcceptedExports = new Array(imports.length);
  37244. await Promise.all(imports.map(async (importSpecifier, index) => {
  37245. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex,
  37246. // #2083 User may use escape path,
  37247. // so use imports[index].n to get the unescaped string
  37248. n: specifier, a: assertIndex, } = importSpecifier;
  37249. const rawUrl = source.slice(start, end);
  37250. // check import.meta usage
  37251. if (rawUrl === 'import.meta') {
  37252. const prop = source.slice(end, end + 4);
  37253. if (prop === '.hot') {
  37254. hasHMR = true;
  37255. const endHot = end + 4 + (source[end + 4] === '?' ? 1 : 0);
  37256. if (source.slice(endHot, endHot + 7) === '.accept') {
  37257. // further analyze accepted modules
  37258. if (source.slice(endHot, endHot + 14) === '.acceptExports') {
  37259. const importAcceptedExports = (orderedAcceptedExports[index] =
  37260. new Set());
  37261. lexAcceptedHmrExports(source, source.indexOf('(', endHot + 14) + 1, importAcceptedExports);
  37262. isPartiallySelfAccepting = true;
  37263. }
  37264. else {
  37265. const importAcceptedUrls = (orderedAcceptedUrls[index] =
  37266. new Set());
  37267. if (lexAcceptedHmrDeps(source, source.indexOf('(', endHot + 7) + 1, importAcceptedUrls)) {
  37268. isSelfAccepting = true;
  37269. }
  37270. }
  37271. }
  37272. }
  37273. else if (prop === '.env') {
  37274. hasEnv = true;
  37275. }
  37276. return;
  37277. }
  37278. const isDynamicImport = dynamicIndex > -1;
  37279. // strip import assertions as we can process them ourselves
  37280. if (!isDynamicImport && assertIndex > -1) {
  37281. str().remove(end + 1, expEnd);
  37282. }
  37283. // static import or valid string in dynamic import
  37284. // If resolvable, let's resolve it
  37285. if (specifier) {
  37286. // skip external / data uri
  37287. if (isExternalUrl(specifier) || isDataUrl(specifier)) {
  37288. return;
  37289. }
  37290. // skip ssr external
  37291. if (ssr) {
  37292. if (config.legacy?.buildSsrCjsExternalHeuristics) {
  37293. if (cjsShouldExternalizeForSSR(specifier, server._ssrExternals)) {
  37294. return;
  37295. }
  37296. }
  37297. else if (shouldExternalizeForSSR(specifier, config)) {
  37298. return;
  37299. }
  37300. if (isBuiltin(specifier)) {
  37301. return;
  37302. }
  37303. }
  37304. // skip client
  37305. if (specifier === clientPublicPath) {
  37306. return;
  37307. }
  37308. // warn imports to non-asset /public files
  37309. if (specifier[0] === '/' &&
  37310. !config.assetsInclude(cleanUrl(specifier)) &&
  37311. !specifier.endsWith('.json') &&
  37312. checkPublicFile(specifier, config)) {
  37313. throw new Error(`Cannot import non-asset file ${specifier} which is inside /public.` +
  37314. `JS/CSS files inside /public are copied as-is on build and ` +
  37315. `can only be referenced via <script src> or <link href> in html.`);
  37316. }
  37317. // normalize
  37318. const [url, resolvedId] = await normalizeUrl(specifier, start);
  37319. if (!isDynamicImport &&
  37320. specifier &&
  37321. !specifier.includes('?') && // ignore custom queries
  37322. isCSSRequest(resolvedId) &&
  37323. !isModuleCSSRequest(resolvedId)) {
  37324. const sourceExp = source.slice(expStart, start);
  37325. if (sourceExp.includes('from') && // check default and named imports
  37326. !sourceExp.includes('__vite_glob_') // glob handles deprecation message itself
  37327. ) {
  37328. const newImport = sourceExp + specifier + `?inline` + source.slice(end, expEnd);
  37329. this.warn(`\n` +
  37330. colors$1.cyan(importerModule.file) +
  37331. `\n` +
  37332. colors$1.reset(generateCodeFrame(source, start)) +
  37333. `\n` +
  37334. colors$1.yellow(`Default and named imports from CSS files are deprecated. ` +
  37335. `Use the ?inline query instead. ` +
  37336. `For example: ${newImport}`));
  37337. }
  37338. }
  37339. // record as safe modules
  37340. server?.moduleGraph.safeModulesPath.add(fsPathFromUrl(url));
  37341. if (url !== specifier) {
  37342. let rewriteDone = false;
  37343. if (depsOptimizer?.isOptimizedDepFile(resolvedId) &&
  37344. !resolvedId.match(optimizedDepChunkRE$1)) {
  37345. // for optimized cjs deps, support named imports by rewriting named imports to const assignments.
  37346. // internal optimized chunks don't need es interop and are excluded
  37347. // The browserHash in resolvedId could be stale in which case there will be a full
  37348. // page reload. We could return a 404 in that case but it is safe to return the request
  37349. const file = cleanUrl(resolvedId); // Remove ?v={hash}
  37350. const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata, file, config, ssr);
  37351. if (needsInterop === undefined) {
  37352. // Non-entry dynamic imports from dependencies will reach here as there isn't
  37353. // optimize info for them, but they don't need es interop. If the request isn't
  37354. // a dynamic import, then it is an internal Vite error
  37355. if (!file.match(optimizedDepDynamicRE$1)) {
  37356. config.logger.error(colors$1.red(`Vite Error, ${url} optimized info should be defined`));
  37357. }
  37358. }
  37359. else if (needsInterop) {
  37360. debug$a?.(`${url} needs interop`);
  37361. interopNamedImports(str(), importSpecifier, url, index, importer, config);
  37362. rewriteDone = true;
  37363. }
  37364. }
  37365. // If source code imports builtin modules via named imports, the stub proxy export
  37366. // would fail as it's `export default` only. Apply interop for builtin modules to
  37367. // correctly throw the error message.
  37368. else if (url.includes(browserExternalId) &&
  37369. source.slice(expStart, start).includes('{')) {
  37370. interopNamedImports(str(), importSpecifier, url, index, importer, config);
  37371. rewriteDone = true;
  37372. }
  37373. if (!rewriteDone) {
  37374. const rewrittenUrl = JSON.stringify(url);
  37375. const s = isDynamicImport ? start : start - 1;
  37376. const e = isDynamicImport ? end : end + 1;
  37377. str().overwrite(s, e, rewrittenUrl, {
  37378. contentOnly: true,
  37379. });
  37380. }
  37381. }
  37382. // record for HMR import chain analysis
  37383. // make sure to unwrap and normalize away base
  37384. const hmrUrl = unwrapId(stripBase(url, base));
  37385. const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
  37386. if (isLocalImport) {
  37387. importedUrls.add(hmrUrl);
  37388. }
  37389. if (enablePartialAccept && importedBindings) {
  37390. extractImportedBindings(resolvedId, source, importSpecifier, importedBindings);
  37391. }
  37392. if (!isDynamicImport &&
  37393. isLocalImport &&
  37394. config.server.preTransformRequests) {
  37395. // pre-transform known direct imports
  37396. // These requests will also be registered in transformRequest to be awaited
  37397. // by the deps optimizer
  37398. const url = removeImportQuery(hmrUrl);
  37399. server.transformRequest(url, { ssr }).catch((e) => {
  37400. if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
  37401. // This are expected errors
  37402. return;
  37403. }
  37404. // Unexpected error, log the issue but avoid an unhandled exception
  37405. config.logger.error(e.message);
  37406. });
  37407. }
  37408. }
  37409. else if (!importer.startsWith(clientDir)) {
  37410. if (!isInNodeModules(importer)) {
  37411. // check @vite-ignore which suppresses dynamic import warning
  37412. const hasViteIgnore = hasViteIgnoreRE.test(
  37413. // complete expression inside parens
  37414. source.slice(dynamicIndex + 1, end));
  37415. if (!hasViteIgnore) {
  37416. this.warn(`\n` +
  37417. colors$1.cyan(importerModule.file) +
  37418. `\n` +
  37419. colors$1.reset(generateCodeFrame(source, start)) +
  37420. colors$1.yellow(`\nThe above dynamic import cannot be analyzed by Vite.\n` +
  37421. `See ${colors$1.blue(`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`)} ` +
  37422. `for supported dynamic import formats. ` +
  37423. `If this is intended to be left as-is, you can use the ` +
  37424. `/* @vite-ignore */ comment inside the import() call to suppress this warning.\n`));
  37425. }
  37426. }
  37427. if (!ssr) {
  37428. const url = rawUrl.replace(cleanUpRawUrlRE, '').trim();
  37429. if (!urlIsStringRE.test(url) ||
  37430. isExplicitImportRequired(url.slice(1, -1))) {
  37431. needQueryInjectHelper = true;
  37432. str().overwrite(start, end, `__vite__injectQuery(${url}, 'import')`, { contentOnly: true });
  37433. }
  37434. }
  37435. }
  37436. }));
  37437. const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
  37438. const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
  37439. if (hasEnv) {
  37440. // inject import.meta.env
  37441. str().prepend(getEnv(ssr));
  37442. }
  37443. if (hasHMR && !ssr) {
  37444. debugHmr?.(`${isSelfAccepting
  37445. ? `[self-accepts]`
  37446. : isPartiallySelfAccepting
  37447. ? `[accepts-exports]`
  37448. : acceptedUrls.size
  37449. ? `[accepts-deps]`
  37450. : `[detected api usage]`} ${prettyImporter}`);
  37451. // inject hot context
  37452. str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";` +
  37453. `import.meta.hot = __vite__createHotContext(${JSON.stringify(normalizeHmrUrl(importerModule.url))});`);
  37454. }
  37455. if (needQueryInjectHelper) {
  37456. str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
  37457. }
  37458. // normalize and rewrite accepted urls
  37459. const normalizedAcceptedUrls = new Set();
  37460. for (const { url, start, end } of acceptedUrls) {
  37461. const [normalized] = await moduleGraph.resolveUrl(toAbsoluteUrl(url), ssr);
  37462. normalizedAcceptedUrls.add(normalized);
  37463. str().overwrite(start, end, JSON.stringify(normalized), {
  37464. contentOnly: true,
  37465. });
  37466. }
  37467. // update the module graph for HMR analysis.
  37468. // node CSS imports does its own graph update in the css plugin so we
  37469. // only handle js graph updates here.
  37470. if (!isCSSRequest(importer)) {
  37471. // attached by pluginContainer.addWatchFile
  37472. const pluginImports = this._addedImports;
  37473. if (pluginImports) {
  37474. (await Promise.all([...pluginImports].map((id) => normalizeUrl(id, 0, true)))).forEach(([url]) => importedUrls.add(url));
  37475. }
  37476. // HMR transforms are no-ops in SSR, so an `accept` call will
  37477. // never be injected. Avoid updating the `isSelfAccepting`
  37478. // property for our module node in that case.
  37479. if (ssr && importerModule.isSelfAccepting) {
  37480. isSelfAccepting = true;
  37481. }
  37482. // a partially accepted module that accepts all its exports
  37483. // behaves like a self-accepted module in practice
  37484. if (!isSelfAccepting &&
  37485. isPartiallySelfAccepting &&
  37486. acceptedExports.size >= exports.length &&
  37487. exports.every((e) => acceptedExports.has(e.n))) {
  37488. isSelfAccepting = true;
  37489. }
  37490. const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, importedBindings, normalizedAcceptedUrls, isPartiallySelfAccepting ? acceptedExports : null, isSelfAccepting, ssr);
  37491. if (hasHMR && prunedImports) {
  37492. handlePrunedModules(prunedImports, server);
  37493. }
  37494. }
  37495. debug$a?.(`${timeFrom(start)} ${colors$1.dim(`[${importedUrls.size} imports rewritten] ${prettyImporter}`)}`);
  37496. if (s) {
  37497. return transformStableResult(s, importer, config);
  37498. }
  37499. else {
  37500. return source;
  37501. }
  37502. },
  37503. };
  37504. }
  37505. function mergeAcceptedUrls(orderedUrls) {
  37506. const acceptedUrls = new Set();
  37507. for (const urls of orderedUrls) {
  37508. if (!urls)
  37509. continue;
  37510. for (const url of urls)
  37511. acceptedUrls.add(url);
  37512. }
  37513. return acceptedUrls;
  37514. }
  37515. function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config) {
  37516. const source = str.original;
  37517. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = importSpecifier;
  37518. if (dynamicIndex > -1) {
  37519. // rewrite `import('package')` to expose the default directly
  37520. str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))`, { contentOnly: true });
  37521. }
  37522. else {
  37523. const exp = source.slice(expStart, expEnd);
  37524. const rawUrl = source.slice(start, end);
  37525. const rewritten = transformCjsImport(exp, rewrittenUrl, rawUrl, importIndex, importer, config);
  37526. if (rewritten) {
  37527. str.overwrite(expStart, expEnd, rewritten, { contentOnly: true });
  37528. }
  37529. else {
  37530. // #1439 export * from '...'
  37531. str.overwrite(start, end, rewrittenUrl, { contentOnly: true });
  37532. }
  37533. }
  37534. }
  37535. /**
  37536. * Detect import statements to a known optimized CJS dependency and provide
  37537. * ES named imports interop. We do this by rewriting named imports to a variable
  37538. * assignment to the corresponding property on the `module.exports` of the cjs
  37539. * module. Note this doesn't support dynamic re-assignments from within the cjs
  37540. * module.
  37541. *
  37542. * Note that es-module-lexer treats `export * from '...'` as an import as well,
  37543. * so, we may encounter ExportAllDeclaration here, in which case `undefined`
  37544. * will be returned.
  37545. *
  37546. * Credits \@csr632 via #837
  37547. */
  37548. function transformCjsImport(importExp, url, rawUrl, importIndex, importer, config) {
  37549. const node = parse$d(importExp, {
  37550. ecmaVersion: 'latest',
  37551. sourceType: 'module',
  37552. }).body[0];
  37553. // `export * from '...'` may cause unexpected problem, so give it a warning
  37554. if (config.command === 'serve' &&
  37555. node.type === 'ExportAllDeclaration' &&
  37556. !node.exported) {
  37557. config.logger.warn(colors$1.yellow(`\nUnable to interop \`${importExp}\` in ${importer}, this may lose module exports. Please export "${rawUrl}" as ESM or use named exports instead, e.g. \`export { A, B } from "${rawUrl}"\``));
  37558. }
  37559. else if (node.type === 'ImportDeclaration' ||
  37560. node.type === 'ExportNamedDeclaration') {
  37561. if (!node.specifiers.length) {
  37562. return `import "${url}"`;
  37563. }
  37564. const importNames = [];
  37565. const exportNames = [];
  37566. let defaultExports = '';
  37567. for (const spec of node.specifiers) {
  37568. if (spec.type === 'ImportSpecifier' &&
  37569. spec.imported.type === 'Identifier') {
  37570. const importedName = spec.imported.name;
  37571. const localName = spec.local.name;
  37572. importNames.push({ importedName, localName });
  37573. }
  37574. else if (spec.type === 'ImportDefaultSpecifier') {
  37575. importNames.push({
  37576. importedName: 'default',
  37577. localName: spec.local.name,
  37578. });
  37579. }
  37580. else if (spec.type === 'ImportNamespaceSpecifier') {
  37581. importNames.push({ importedName: '*', localName: spec.local.name });
  37582. }
  37583. else if (spec.type === 'ExportSpecifier' &&
  37584. spec.exported.type === 'Identifier') {
  37585. // for ExportSpecifier, local name is same as imported name
  37586. // prefix the variable name to avoid clashing with other local variables
  37587. const importedName = spec.local.name;
  37588. // we want to specify exported name as variable and re-export it
  37589. const exportedName = spec.exported.name;
  37590. if (exportedName === 'default') {
  37591. defaultExports = makeLegalIdentifier(`__vite__cjsExportDefault_${importIndex}`);
  37592. importNames.push({ importedName, localName: defaultExports });
  37593. }
  37594. else {
  37595. const localName = makeLegalIdentifier(`__vite__cjsExport_${exportedName}`);
  37596. importNames.push({ importedName, localName });
  37597. exportNames.push(`${localName} as ${exportedName}`);
  37598. }
  37599. }
  37600. }
  37601. // If there is multiple import for same id in one file,
  37602. // importIndex will prevent the cjsModuleName to be duplicate
  37603. const cjsModuleName = makeLegalIdentifier(`__vite__cjsImport${importIndex}_${rawUrl}`);
  37604. const lines = [`import ${cjsModuleName} from "${url}"`];
  37605. importNames.forEach(({ importedName, localName }) => {
  37606. if (importedName === '*') {
  37607. lines.push(`const ${localName} = ${cjsModuleName}`);
  37608. }
  37609. else if (importedName === 'default') {
  37610. lines.push(`const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`);
  37611. }
  37612. else {
  37613. lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
  37614. }
  37615. });
  37616. if (defaultExports) {
  37617. lines.push(`export default ${defaultExports}`);
  37618. }
  37619. if (exportNames.length) {
  37620. lines.push(`export { ${exportNames.join(', ')} }`);
  37621. }
  37622. return lines.join('; ');
  37623. }
  37624. }
  37625. const process_env_NODE_ENV_RE = /(\bglobal(This)?\.)?\bprocess\.env\.NODE_ENV\b/g;
  37626. // ids in transform are normalized to unix style
  37627. const normalizedClientEntry = normalizePath$3(CLIENT_ENTRY);
  37628. const normalizedEnvEntry = normalizePath$3(ENV_ENTRY);
  37629. /**
  37630. * some values used by the client needs to be dynamically injected by the server
  37631. * @server-only
  37632. */
  37633. function clientInjectionsPlugin(config) {
  37634. let injectConfigValues;
  37635. return {
  37636. name: 'vite:client-inject',
  37637. async buildStart() {
  37638. const resolvedServerHostname = (await resolveHostname(config.server.host))
  37639. .name;
  37640. const resolvedServerPort = config.server.port;
  37641. const devBase = config.base;
  37642. const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
  37643. let hmrConfig = config.server.hmr;
  37644. hmrConfig = isObject$2(hmrConfig) ? hmrConfig : undefined;
  37645. const host = hmrConfig?.host || null;
  37646. const protocol = hmrConfig?.protocol || null;
  37647. const timeout = hmrConfig?.timeout || 30000;
  37648. const overlay = hmrConfig?.overlay !== false;
  37649. const isHmrServerSpecified = !!hmrConfig?.server;
  37650. // hmr.clientPort -> hmr.port
  37651. // -> (24678 if middleware mode and HMR server is not specified) -> new URL(import.meta.url).port
  37652. let port = hmrConfig?.clientPort || hmrConfig?.port || null;
  37653. if (config.server.middlewareMode && !isHmrServerSpecified) {
  37654. port || (port = 24678);
  37655. }
  37656. let directTarget = hmrConfig?.host || resolvedServerHostname;
  37657. directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
  37658. directTarget += devBase;
  37659. let hmrBase = devBase;
  37660. if (hmrConfig?.path) {
  37661. hmrBase = path$o.posix.join(hmrBase, hmrConfig.path);
  37662. }
  37663. const serializedDefines = serializeDefine(config.define || {});
  37664. const modeReplacement = escapeReplacement(config.mode);
  37665. const baseReplacement = escapeReplacement(devBase);
  37666. const definesReplacement = () => serializedDefines;
  37667. const serverHostReplacement = escapeReplacement(serverHost);
  37668. const hmrProtocolReplacement = escapeReplacement(protocol);
  37669. const hmrHostnameReplacement = escapeReplacement(host);
  37670. const hmrPortReplacement = escapeReplacement(port);
  37671. const hmrDirectTargetReplacement = escapeReplacement(directTarget);
  37672. const hmrBaseReplacement = escapeReplacement(hmrBase);
  37673. const hmrTimeoutReplacement = escapeReplacement(timeout);
  37674. const hmrEnableOverlayReplacement = escapeReplacement(overlay);
  37675. injectConfigValues = (code) => {
  37676. return code
  37677. .replace(`__MODE__`, modeReplacement)
  37678. .replace(/__BASE__/g, baseReplacement)
  37679. .replace(`__DEFINES__`, definesReplacement)
  37680. .replace(`__SERVER_HOST__`, serverHostReplacement)
  37681. .replace(`__HMR_PROTOCOL__`, hmrProtocolReplacement)
  37682. .replace(`__HMR_HOSTNAME__`, hmrHostnameReplacement)
  37683. .replace(`__HMR_PORT__`, hmrPortReplacement)
  37684. .replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement)
  37685. .replace(`__HMR_BASE__`, hmrBaseReplacement)
  37686. .replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement)
  37687. .replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement);
  37688. };
  37689. },
  37690. transform(code, id, options) {
  37691. if (id === normalizedClientEntry || id === normalizedEnvEntry) {
  37692. return injectConfigValues(code);
  37693. }
  37694. else if (!options?.ssr && code.includes('process.env.NODE_ENV')) {
  37695. // replace process.env.NODE_ENV instead of defining a global
  37696. // for it to avoid shimming a `process` object during dev,
  37697. // avoiding inconsistencies between dev and build
  37698. return code.replace(process_env_NODE_ENV_RE, config.define?.['process.env.NODE_ENV'] ||
  37699. JSON.stringify(process.env.NODE_ENV || config.mode));
  37700. }
  37701. },
  37702. };
  37703. }
  37704. function escapeReplacement(value) {
  37705. const jsonValue = JSON.stringify(value);
  37706. return () => jsonValue;
  37707. }
  37708. function serializeDefine(define) {
  37709. let res = `{`;
  37710. for (const key in define) {
  37711. const val = define[key];
  37712. res += `${JSON.stringify(key)}: ${typeof val === 'string' ? `(${val})` : JSON.stringify(val)}, `;
  37713. }
  37714. return res + `}`;
  37715. }
  37716. const wasmHelperId = '\0vite/wasm-helper';
  37717. const wasmHelper = async (opts = {}, url) => {
  37718. let result;
  37719. if (url.startsWith('data:')) {
  37720. const urlContent = url.replace(/^data:.*?base64,/, '');
  37721. let bytes;
  37722. if (typeof Buffer === 'function' && typeof Buffer.from === 'function') {
  37723. bytes = Buffer.from(urlContent, 'base64');
  37724. }
  37725. else if (typeof atob === 'function') {
  37726. const binaryString = atob(urlContent);
  37727. bytes = new Uint8Array(binaryString.length);
  37728. for (let i = 0; i < binaryString.length; i++) {
  37729. bytes[i] = binaryString.charCodeAt(i);
  37730. }
  37731. }
  37732. else {
  37733. throw new Error('Failed to decode base64-encoded data URL, Buffer and atob are not supported');
  37734. }
  37735. result = await WebAssembly.instantiate(bytes, opts);
  37736. }
  37737. else {
  37738. // https://github.com/mdn/webassembly-examples/issues/5
  37739. // WebAssembly.instantiateStreaming requires the server to provide the
  37740. // correct MIME type for .wasm files, which unfortunately doesn't work for
  37741. // a lot of static file servers, so we just work around it by getting the
  37742. // raw buffer.
  37743. const response = await fetch(url);
  37744. const contentType = response.headers.get('Content-Type') || '';
  37745. if ('instantiateStreaming' in WebAssembly &&
  37746. contentType.startsWith('application/wasm')) {
  37747. result = await WebAssembly.instantiateStreaming(response, opts);
  37748. }
  37749. else {
  37750. const buffer = await response.arrayBuffer();
  37751. result = await WebAssembly.instantiate(buffer, opts);
  37752. }
  37753. }
  37754. return result.instance;
  37755. };
  37756. const wasmHelperCode = wasmHelper.toString();
  37757. const wasmHelperPlugin = (config) => {
  37758. return {
  37759. name: 'vite:wasm-helper',
  37760. resolveId(id) {
  37761. if (id === wasmHelperId) {
  37762. return id;
  37763. }
  37764. },
  37765. async load(id) {
  37766. if (id === wasmHelperId) {
  37767. return `export default ${wasmHelperCode}`;
  37768. }
  37769. if (!id.endsWith('.wasm?init')) {
  37770. return;
  37771. }
  37772. const url = await fileToUrl(id, config, this);
  37773. return `
  37774. import initWasm from "${wasmHelperId}"
  37775. export default opts => initWasm(opts, ${JSON.stringify(url)})
  37776. `;
  37777. },
  37778. };
  37779. };
  37780. const wasmFallbackPlugin = () => {
  37781. return {
  37782. name: 'vite:wasm-fallback',
  37783. async load(id) {
  37784. if (!id.endsWith('.wasm')) {
  37785. return;
  37786. }
  37787. throw new Error('"ESM integration proposal for Wasm" is not supported currently. ' +
  37788. 'Use vite-plugin-wasm or other community plugins to handle this. ' +
  37789. 'Alternatively, you can use `.wasm?init` or `.wasm?url`. ' +
  37790. 'See https://vitejs.dev/guide/features.html#webassembly for more details.');
  37791. },
  37792. };
  37793. };
  37794. const WORKER_FILE_ID = 'worker_file';
  37795. const workerCache = new WeakMap();
  37796. function saveEmitWorkerAsset(config, asset) {
  37797. const fileName = asset.fileName;
  37798. const workerMap = workerCache.get(config.mainConfig || config);
  37799. workerMap.assets.set(fileName, asset);
  37800. }
  37801. // Ensure that only one rollup build is called at the same time to avoid
  37802. // leaking state in plugins between worker builds.
  37803. // TODO: Review if we can parallelize the bundling of workers.
  37804. const workerConfigSemaphore = new WeakMap();
  37805. async function bundleWorkerEntry(config, id, query) {
  37806. const processing = workerConfigSemaphore.get(config);
  37807. if (processing) {
  37808. await processing;
  37809. return bundleWorkerEntry(config, id, query);
  37810. }
  37811. const promise = serialBundleWorkerEntry(config, id, query);
  37812. workerConfigSemaphore.set(config, promise);
  37813. promise.then(() => workerConfigSemaphore.delete(config));
  37814. return promise;
  37815. }
  37816. async function serialBundleWorkerEntry(config, id, query) {
  37817. // bundle the file as entry to support imports
  37818. const { rollup } = await import('rollup');
  37819. const { plugins, rollupOptions, format } = config.worker;
  37820. const bundle = await rollup({
  37821. ...rollupOptions,
  37822. input: cleanUrl(id),
  37823. plugins,
  37824. onwarn(warning, warn) {
  37825. onRollupWarning(warning, warn, config);
  37826. },
  37827. preserveEntrySignatures: false,
  37828. });
  37829. let chunk;
  37830. try {
  37831. const workerOutputConfig = config.worker.rollupOptions.output;
  37832. const workerConfig = workerOutputConfig
  37833. ? Array.isArray(workerOutputConfig)
  37834. ? workerOutputConfig[0] || {}
  37835. : workerOutputConfig
  37836. : {};
  37837. const { output: [outputChunk, ...outputChunks], } = await bundle.generate({
  37838. entryFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'),
  37839. chunkFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'),
  37840. assetFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].[ext]'),
  37841. ...workerConfig,
  37842. format,
  37843. sourcemap: config.build.sourcemap,
  37844. });
  37845. chunk = outputChunk;
  37846. outputChunks.forEach((outputChunk) => {
  37847. if (outputChunk.type === 'asset') {
  37848. saveEmitWorkerAsset(config, outputChunk);
  37849. }
  37850. else if (outputChunk.type === 'chunk') {
  37851. saveEmitWorkerAsset(config, {
  37852. fileName: outputChunk.fileName,
  37853. source: outputChunk.code,
  37854. type: 'asset',
  37855. });
  37856. }
  37857. });
  37858. }
  37859. finally {
  37860. await bundle.close();
  37861. }
  37862. return emitSourcemapForWorkerEntry(config, query, chunk);
  37863. }
  37864. function emitSourcemapForWorkerEntry(config, query, chunk) {
  37865. const { map: sourcemap } = chunk;
  37866. if (sourcemap) {
  37867. if (config.build.sourcemap === 'hidden' ||
  37868. config.build.sourcemap === true) {
  37869. const data = sourcemap.toString();
  37870. const mapFileName = chunk.fileName + '.map';
  37871. saveEmitWorkerAsset(config, {
  37872. fileName: mapFileName,
  37873. type: 'asset',
  37874. source: data,
  37875. });
  37876. }
  37877. }
  37878. return chunk;
  37879. }
  37880. const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
  37881. function encodeWorkerAssetFileName(fileName, workerCache) {
  37882. const { fileNameHash } = workerCache;
  37883. const hash = getHash(fileName);
  37884. if (!fileNameHash.get(hash)) {
  37885. fileNameHash.set(hash, fileName);
  37886. }
  37887. return `__VITE_WORKER_ASSET__${hash}__`;
  37888. }
  37889. async function workerFileToUrl(config, id, query) {
  37890. const workerMap = workerCache.get(config.mainConfig || config);
  37891. let fileName = workerMap.bundle.get(id);
  37892. if (!fileName) {
  37893. const outputChunk = await bundleWorkerEntry(config, id, query);
  37894. fileName = outputChunk.fileName;
  37895. saveEmitWorkerAsset(config, {
  37896. fileName,
  37897. source: outputChunk.code,
  37898. type: 'asset',
  37899. });
  37900. workerMap.bundle.set(id, fileName);
  37901. }
  37902. return encodeWorkerAssetFileName(fileName, workerMap);
  37903. }
  37904. function webWorkerPostPlugin() {
  37905. return {
  37906. name: 'vite:worker-post',
  37907. resolveImportMeta(property, { chunkId, format }) {
  37908. // document is undefined in the worker, so we need to avoid it in iife
  37909. if (property === 'url' && format === 'iife') {
  37910. return 'self.location.href';
  37911. }
  37912. return null;
  37913. },
  37914. };
  37915. }
  37916. function webWorkerPlugin(config) {
  37917. const isBuild = config.command === 'build';
  37918. let server;
  37919. const isWorker = config.isWorker;
  37920. const isWorkerQueryId = (id) => {
  37921. const parsedQuery = parseRequest(id);
  37922. if (parsedQuery &&
  37923. (parsedQuery.worker ?? parsedQuery.sharedworker) != null) {
  37924. return true;
  37925. }
  37926. return false;
  37927. };
  37928. return {
  37929. name: 'vite:worker',
  37930. configureServer(_server) {
  37931. server = _server;
  37932. },
  37933. buildStart() {
  37934. if (isWorker) {
  37935. return;
  37936. }
  37937. workerCache.set(config, {
  37938. assets: new Map(),
  37939. bundle: new Map(),
  37940. fileNameHash: new Map(),
  37941. });
  37942. },
  37943. load(id) {
  37944. if (isBuild && isWorkerQueryId(id)) {
  37945. return '';
  37946. }
  37947. },
  37948. shouldTransformCachedModule({ id }) {
  37949. if (isBuild && isWorkerQueryId(id) && config.build.watch) {
  37950. return true;
  37951. }
  37952. },
  37953. async transform(raw, id, options) {
  37954. const ssr = options?.ssr === true;
  37955. const query = parseRequest(id);
  37956. if (query && query[WORKER_FILE_ID] != null) {
  37957. // if import worker by worker constructor will have query.type
  37958. // other type will be import worker by esm
  37959. const workerType = query['type'];
  37960. let injectEnv = '';
  37961. if (workerType === 'classic') {
  37962. injectEnv = `importScripts('${ENV_PUBLIC_PATH}')\n`;
  37963. }
  37964. else if (workerType === 'module') {
  37965. injectEnv = `import '${ENV_PUBLIC_PATH}'\n`;
  37966. }
  37967. else if (workerType === 'ignore') {
  37968. if (isBuild) {
  37969. injectEnv = '';
  37970. }
  37971. else if (server) {
  37972. // dynamic worker type we can't know how import the env
  37973. // so we copy /@vite/env code of server transform result into file header
  37974. const { moduleGraph } = server;
  37975. const module = moduleGraph.getModuleById(ENV_ENTRY);
  37976. injectEnv = module?.transformResult?.code || '';
  37977. }
  37978. }
  37979. return {
  37980. code: injectEnv + raw,
  37981. };
  37982. }
  37983. if (query == null ||
  37984. (query && (query.worker ?? query.sharedworker) == null)) {
  37985. return;
  37986. }
  37987. // stringified url or `new URL(...)`
  37988. let url;
  37989. const { format } = config.worker;
  37990. const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
  37991. const workerType = isBuild
  37992. ? format === 'es'
  37993. ? 'module'
  37994. : 'classic'
  37995. : 'module';
  37996. const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}';
  37997. if (isBuild) {
  37998. getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
  37999. if (query.inline != null) {
  38000. const chunk = await bundleWorkerEntry(config, id, query);
  38001. const encodedJs = `const encodedJs = "${Buffer.from(chunk.code).toString('base64')}";`;
  38002. const code =
  38003. // Using blob URL for SharedWorker results in multiple instances of a same worker
  38004. workerConstructor === 'Worker'
  38005. ? `${encodedJs}
  38006. const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
  38007. export default function WorkerWrapper() {
  38008. let objURL;
  38009. try {
  38010. objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
  38011. if (!objURL) throw ''
  38012. return new ${workerConstructor}(objURL)
  38013. } catch(e) {
  38014. return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
  38015. } finally {
  38016. objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
  38017. }
  38018. }`
  38019. : `${encodedJs}
  38020. export default function WorkerWrapper() {
  38021. return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
  38022. }
  38023. `;
  38024. return {
  38025. code,
  38026. // Empty sourcemap to suppress Rollup warning
  38027. map: { mappings: '' },
  38028. };
  38029. }
  38030. else {
  38031. url = await workerFileToUrl(config, id, query);
  38032. }
  38033. }
  38034. else {
  38035. url = await fileToUrl(cleanUrl(id), config, this);
  38036. url = injectQuery(url, WORKER_FILE_ID);
  38037. url = injectQuery(url, `type=${workerType}`);
  38038. }
  38039. if (query.url != null) {
  38040. return {
  38041. code: `export default ${JSON.stringify(url)}`,
  38042. map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
  38043. };
  38044. }
  38045. return {
  38046. code: `export default function WorkerWrapper() {
  38047. return new ${workerConstructor}(${JSON.stringify(url)}${workerOptions})
  38048. }`,
  38049. map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
  38050. };
  38051. },
  38052. renderChunk(code, chunk, outputOptions) {
  38053. let s;
  38054. const result = () => {
  38055. return (s && {
  38056. code: s.toString(),
  38057. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null,
  38058. });
  38059. };
  38060. if (code.match(workerAssetUrlRE)) {
  38061. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, config.isWorker);
  38062. let match;
  38063. s = new MagicString(code);
  38064. workerAssetUrlRE.lastIndex = 0;
  38065. // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
  38066. const workerMap = workerCache.get(config.mainConfig || config);
  38067. const { fileNameHash } = workerMap;
  38068. while ((match = workerAssetUrlRE.exec(code))) {
  38069. const [full, hash] = match;
  38070. const filename = fileNameHash.get(hash);
  38071. const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
  38072. const replacementString = typeof replacement === 'string'
  38073. ? JSON.stringify(replacement).slice(1, -1)
  38074. : `"+${replacement.runtime}+"`;
  38075. s.update(match.index, match.index + full.length, replacementString);
  38076. }
  38077. }
  38078. return result();
  38079. },
  38080. generateBundle(opts) {
  38081. // @ts-expect-error asset emits are skipped in legacy bundle
  38082. if (opts.__vite_skip_asset_emit__ || isWorker) {
  38083. return;
  38084. }
  38085. const workerMap = workerCache.get(config);
  38086. workerMap.assets.forEach((asset) => {
  38087. this.emitFile(asset);
  38088. workerMap.assets.delete(asset.fileName);
  38089. });
  38090. },
  38091. };
  38092. }
  38093. /**
  38094. * A plugin to avoid an aliased AND optimized dep from being aliased in src
  38095. */
  38096. function preAliasPlugin(config) {
  38097. const findPatterns = getAliasPatterns(config.resolve.alias);
  38098. const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config);
  38099. const isBuild = config.command === 'build';
  38100. return {
  38101. name: 'vite:pre-alias',
  38102. async resolveId(id, importer, options) {
  38103. const ssr = options?.ssr === true;
  38104. const depsOptimizer = getDepsOptimizer(config, ssr);
  38105. if (importer &&
  38106. depsOptimizer &&
  38107. bareImportRE.test(id) &&
  38108. !options?.scan &&
  38109. id !== '@vite/client' &&
  38110. id !== '@vite/env') {
  38111. if (findPatterns.find((pattern) => matches(pattern, id))) {
  38112. const optimizedId = await tryOptimizedResolve(depsOptimizer, id, importer, config.resolve.preserveSymlinks, config.packageCache);
  38113. if (optimizedId) {
  38114. return optimizedId; // aliased dep already optimized
  38115. }
  38116. if (depsOptimizer.options.noDiscovery) {
  38117. return;
  38118. }
  38119. const resolved = await this.resolve(id, importer, {
  38120. ...options,
  38121. custom: { ...options.custom, 'vite:pre-alias': true },
  38122. skipSelf: true,
  38123. });
  38124. if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
  38125. const optimizeDeps = depsOptimizer.options;
  38126. const resolvedId = cleanUrl(resolved.id);
  38127. const isVirtual = resolvedId === id || resolvedId.includes('\0');
  38128. if (!isVirtual &&
  38129. fs$l.existsSync(resolvedId) &&
  38130. !moduleListContains(optimizeDeps.exclude, id) &&
  38131. path$o.isAbsolute(resolvedId) &&
  38132. (isInNodeModules(resolvedId) ||
  38133. optimizeDeps.include?.includes(id)) &&
  38134. isOptimizable(resolvedId, optimizeDeps) &&
  38135. !(isBuild && ssr && isConfiguredAsExternal(id)) &&
  38136. (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps))) {
  38137. // aliased dep has not yet been optimized
  38138. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolvedId);
  38139. return { id: depsOptimizer.getOptimizedDepId(optimizedInfo) };
  38140. }
  38141. }
  38142. return resolved;
  38143. }
  38144. }
  38145. },
  38146. };
  38147. }
  38148. function optimizeAliasReplacementForSSR(id, optimizeDeps) {
  38149. if (optimizeDeps.include?.includes(id)) {
  38150. return true;
  38151. }
  38152. // In the regular resolution, the default for non-external modules is to
  38153. // be optimized if they are CJS. Here, we don't have the package id but
  38154. // only the replacement file path. We could find the package.json from
  38155. // the id and respect the same default in the future.
  38156. // Default to not optimize an aliased replacement for now, forcing the
  38157. // user to explicitly add it to the ssr.optimizeDeps.include list.
  38158. return false;
  38159. }
  38160. // In sync with rollup plugin alias logic
  38161. function matches(pattern, importee) {
  38162. if (pattern instanceof RegExp) {
  38163. return pattern.test(importee);
  38164. }
  38165. if (importee.length < pattern.length) {
  38166. return false;
  38167. }
  38168. if (importee === pattern) {
  38169. return true;
  38170. }
  38171. return importee.startsWith(pattern + '/');
  38172. }
  38173. function getAliasPatterns(entries) {
  38174. if (!entries) {
  38175. return [];
  38176. }
  38177. if (Array.isArray(entries)) {
  38178. return entries.map((entry) => entry.find);
  38179. }
  38180. return Object.entries(entries).map(([find]) => find);
  38181. }
  38182. const nonJsRe = /\.json(?:$|\?)/;
  38183. const metaEnvRe = /import\.meta\.env\.(.+)/;
  38184. const isNonJsRequest = (request) => nonJsRe.test(request);
  38185. function definePlugin(config) {
  38186. const isBuild = config.command === 'build';
  38187. const isBuildLib = isBuild && config.build.lib;
  38188. // ignore replace process.env in lib build
  38189. const processEnv = {};
  38190. const processNodeEnv = {};
  38191. if (!isBuildLib) {
  38192. const nodeEnv = process.env.NODE_ENV || config.mode;
  38193. Object.assign(processEnv, {
  38194. 'process.env.': `({}).`,
  38195. 'global.process.env.': `({}).`,
  38196. 'globalThis.process.env.': `({}).`,
  38197. });
  38198. Object.assign(processNodeEnv, {
  38199. 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
  38200. 'global.process.env.NODE_ENV': JSON.stringify(nodeEnv),
  38201. 'globalThis.process.env.NODE_ENV': JSON.stringify(nodeEnv),
  38202. __vite_process_env_NODE_ENV: JSON.stringify(nodeEnv),
  38203. });
  38204. }
  38205. const userDefine = {};
  38206. const userDefineEnv = {};
  38207. for (const key in config.define) {
  38208. const val = config.define[key];
  38209. userDefine[key] = typeof val === 'string' ? val : JSON.stringify(val);
  38210. // make sure `import.meta.env` object has user define properties
  38211. if (isBuild) {
  38212. const match = key.match(metaEnvRe);
  38213. if (match) {
  38214. userDefineEnv[match[1]] = `__vite__define__${userDefine[key]}`;
  38215. }
  38216. }
  38217. }
  38218. // during dev, import.meta properties are handled by importAnalysis plugin.
  38219. const importMetaKeys = {};
  38220. const importMetaFallbackKeys = {};
  38221. if (isBuild) {
  38222. // set here to allow override with config.define
  38223. importMetaKeys['import.meta.hot'] = `undefined`;
  38224. for (const key in config.env) {
  38225. importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(config.env[key]);
  38226. }
  38227. Object.assign(importMetaFallbackKeys, {
  38228. 'import.meta.env.': `({}).`,
  38229. 'import.meta.env': JSON.stringify({
  38230. ...config.env,
  38231. SSR: '__vite__ssr__',
  38232. ...userDefineEnv,
  38233. }).replace(/"__vite__define__(.+?)"([,}])/g, (_, val, suffix) => `${val.replace(/(^\\")|(\\"$)/g, '"')}${suffix}`),
  38234. });
  38235. }
  38236. function getImportMetaKeys(ssr) {
  38237. if (!isBuild)
  38238. return {};
  38239. return {
  38240. ...importMetaKeys,
  38241. 'import.meta.env.SSR': ssr + '',
  38242. };
  38243. }
  38244. function getImportMetaFallbackKeys(ssr) {
  38245. if (!isBuild)
  38246. return {};
  38247. return {
  38248. ...importMetaFallbackKeys,
  38249. 'import.meta.env': importMetaFallbackKeys['import.meta.env'].replace('"__vite__ssr__"', ssr + ''),
  38250. };
  38251. }
  38252. function generatePattern(ssr) {
  38253. const replaceProcessEnv = !ssr || config.ssr?.target === 'webworker';
  38254. const replacements = {
  38255. ...(replaceProcessEnv ? processNodeEnv : {}),
  38256. ...getImportMetaKeys(ssr),
  38257. ...userDefine,
  38258. ...getImportMetaFallbackKeys(ssr),
  38259. ...(replaceProcessEnv ? processEnv : {}),
  38260. };
  38261. if (isBuild && !replaceProcessEnv) {
  38262. replacements['__vite_process_env_NODE_ENV'] = 'process.env.NODE_ENV';
  38263. }
  38264. const replacementsKeys = Object.keys(replacements);
  38265. const pattern = replacementsKeys.length
  38266. ? new RegExp(
  38267. // Mustn't be preceded by a char that can be part of an identifier
  38268. // or a '.' that isn't part of a spread operator
  38269. '(?<![\\p{L}\\p{N}_$]|(?<!\\.\\.)\\.)(' +
  38270. replacementsKeys.map(escapeRegex).join('|') +
  38271. // Mustn't be followed by a char that can be part of an identifier
  38272. // or an assignment (but allow equality operators)
  38273. ')(?:(?<=\\.)|(?![\\p{L}\\p{N}_$]|\\s*?=[^=]))', 'gu')
  38274. : null;
  38275. return [replacements, pattern];
  38276. }
  38277. const defaultPattern = generatePattern(false);
  38278. const ssrPattern = generatePattern(true);
  38279. return {
  38280. name: 'vite:define',
  38281. transform(code, id, options) {
  38282. const ssr = options?.ssr === true;
  38283. if (!ssr && !isBuild) {
  38284. // for dev we inject actual global defines in the vite client to
  38285. // avoid the transform cost.
  38286. return;
  38287. }
  38288. if (
  38289. // exclude html, css and static assets for performance
  38290. isHTMLRequest(id) ||
  38291. isCSSRequest(id) ||
  38292. isNonJsRequest(id) ||
  38293. config.assetsInclude(id)) {
  38294. return;
  38295. }
  38296. const [replacements, pattern] = ssr ? ssrPattern : defaultPattern;
  38297. if (!pattern) {
  38298. return null;
  38299. }
  38300. if (ssr && !isBuild) {
  38301. // ssr + dev, simple replace
  38302. return code.replace(pattern, (_, match) => {
  38303. return '' + replacements[match];
  38304. });
  38305. }
  38306. const s = new MagicString(code);
  38307. let hasReplaced = false;
  38308. let match;
  38309. while ((match = pattern.exec(code))) {
  38310. hasReplaced = true;
  38311. const start = match.index;
  38312. const end = start + match[0].length;
  38313. const replacement = '' + replacements[match[1]];
  38314. s.update(start, end, replacement);
  38315. }
  38316. if (!hasReplaced) {
  38317. return null;
  38318. }
  38319. return transformStableResult(s, id, config);
  38320. },
  38321. };
  38322. }
  38323. const ignoreFlagRE = /\/\*\s*@vite-ignore\s*\*\//;
  38324. function err(e, pos) {
  38325. const error = new Error(e);
  38326. error.pos = pos;
  38327. return error;
  38328. }
  38329. function parseWorkerOptions(rawOpts, optsStartIndex) {
  38330. let opts = {};
  38331. try {
  38332. opts = evalValue(rawOpts);
  38333. }
  38334. catch {
  38335. throw err('Vite is unable to parse the worker options as the value is not static.' +
  38336. 'To ignore this error, please use /* @vite-ignore */ in the worker options.', optsStartIndex);
  38337. }
  38338. if (opts == null) {
  38339. return {};
  38340. }
  38341. if (typeof opts !== 'object') {
  38342. throw err(`Expected worker options to be an object, got ${typeof opts}`, optsStartIndex);
  38343. }
  38344. return opts;
  38345. }
  38346. function getWorkerType(raw, clean, i) {
  38347. const commaIndex = clean.indexOf(',', i);
  38348. if (commaIndex === -1) {
  38349. return 'classic';
  38350. }
  38351. const endIndex = clean.indexOf(')', i);
  38352. // case: ') ... ,' mean no worker options params
  38353. if (commaIndex > endIndex) {
  38354. return 'classic';
  38355. }
  38356. // need to find in comment code
  38357. const workerOptString = raw
  38358. .substring(commaIndex + 1, endIndex)
  38359. .replace(/\}[\s\S]*,/g, '}'); // strip trailing comma for parsing
  38360. const hasViteIgnore = ignoreFlagRE.test(workerOptString);
  38361. if (hasViteIgnore) {
  38362. return 'ignore';
  38363. }
  38364. // need to find in no comment code
  38365. const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex).trim();
  38366. if (!cleanWorkerOptString.length) {
  38367. return 'classic';
  38368. }
  38369. const workerOpts = parseWorkerOptions(workerOptString, commaIndex + 1);
  38370. if (workerOpts.type && ['classic', 'module'].includes(workerOpts.type)) {
  38371. return workerOpts.type;
  38372. }
  38373. return 'classic';
  38374. }
  38375. function workerImportMetaUrlPlugin(config) {
  38376. const isBuild = config.command === 'build';
  38377. let workerResolver;
  38378. return {
  38379. name: 'vite:worker-import-meta-url',
  38380. async transform(code, id, options) {
  38381. const ssr = options?.ssr === true;
  38382. if (!options?.ssr &&
  38383. (code.includes('new Worker') || code.includes('new SharedWorker')) &&
  38384. code.includes('new URL') &&
  38385. code.includes(`import.meta.url`)) {
  38386. const query = parseRequest(id);
  38387. let s;
  38388. const cleanString = stripLiteral(code);
  38389. const workerImportMetaUrlRE = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/g;
  38390. let match;
  38391. while ((match = workerImportMetaUrlRE.exec(cleanString))) {
  38392. const { 0: allExp, 1: exp, 2: emptyUrl, index } = match;
  38393. const urlIndex = allExp.indexOf(exp) + index;
  38394. const urlStart = cleanString.indexOf(emptyUrl, index);
  38395. const urlEnd = urlStart + emptyUrl.length;
  38396. const rawUrl = code.slice(urlStart, urlEnd);
  38397. // potential dynamic template string
  38398. if (rawUrl[0] === '`' && rawUrl.includes('${')) {
  38399. this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, urlIndex);
  38400. }
  38401. s || (s = new MagicString(code));
  38402. const workerType = getWorkerType(code, cleanString, index + allExp.length);
  38403. const url = rawUrl.slice(1, -1);
  38404. let file;
  38405. if (url[0] === '.') {
  38406. file = path$o.resolve(path$o.dirname(id), url);
  38407. }
  38408. else {
  38409. workerResolver ?? (workerResolver = config.createResolver({
  38410. extensions: [],
  38411. tryIndex: false,
  38412. preferRelative: true,
  38413. }));
  38414. file = await workerResolver(url, id);
  38415. file ?? (file = url[0] === '/'
  38416. ? slash$1(path$o.join(config.publicDir, url))
  38417. : slash$1(path$o.resolve(path$o.dirname(id), url)));
  38418. }
  38419. let builtUrl;
  38420. if (isBuild) {
  38421. getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
  38422. builtUrl = await workerFileToUrl(config, file, query);
  38423. }
  38424. else {
  38425. builtUrl = await fileToUrl(cleanUrl(file), config, this);
  38426. builtUrl = injectQuery(builtUrl, WORKER_FILE_ID);
  38427. builtUrl = injectQuery(builtUrl, `type=${workerType}`);
  38428. }
  38429. s.update(urlIndex, urlIndex + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`);
  38430. }
  38431. if (s) {
  38432. return transformStableResult(s, id, config);
  38433. }
  38434. return null;
  38435. }
  38436. },
  38437. };
  38438. }
  38439. /**
  38440. * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
  38441. *
  38442. * Supports template string with dynamic segments:
  38443. * ```
  38444. * new URL(`./dir/${name}.png`, import.meta.url)
  38445. * // transformed to
  38446. * import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`]
  38447. * ```
  38448. */
  38449. function assetImportMetaUrlPlugin(config) {
  38450. const normalizedPublicDir = normalizePath$3(config.publicDir);
  38451. let assetResolver;
  38452. return {
  38453. name: 'vite:asset-import-meta-url',
  38454. async transform(code, id, options) {
  38455. if (!options?.ssr &&
  38456. id !== preloadHelperId &&
  38457. id !== CLIENT_ENTRY &&
  38458. code.includes('new URL') &&
  38459. code.includes(`import.meta.url`)) {
  38460. let s;
  38461. const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g;
  38462. const cleanString = stripLiteral(code);
  38463. let match;
  38464. while ((match = assetImportMetaUrlRE.exec(cleanString))) {
  38465. const { 0: exp, 1: emptyUrl, index } = match;
  38466. const urlStart = cleanString.indexOf(emptyUrl, index);
  38467. const urlEnd = urlStart + emptyUrl.length;
  38468. const rawUrl = code.slice(urlStart, urlEnd);
  38469. if (!s)
  38470. s = new MagicString(code);
  38471. // potential dynamic template string
  38472. if (rawUrl[0] === '`' && rawUrl.includes('${')) {
  38473. let [pureUrl, queryString = ''] = rawUrl.split('?');
  38474. if (queryString) {
  38475. pureUrl += '`';
  38476. queryString = '?' + queryString.slice(0, -1);
  38477. }
  38478. const ast = this.parse(pureUrl);
  38479. const templateLiteral = ast.body[0].expression;
  38480. if (templateLiteral.expressions.length) {
  38481. const pattern = buildGlobPattern(templateLiteral);
  38482. if (pattern.startsWith('**')) {
  38483. // don't transform for patterns like this
  38484. // because users won't intend to do that in most cases
  38485. continue;
  38486. }
  38487. const globOptions = {
  38488. eager: true,
  38489. import: 'default',
  38490. // A hack to allow 'as' & 'query' exist at the same time
  38491. query: injectQuery(queryString, 'url'),
  38492. };
  38493. // Note: native import.meta.url is not supported in the baseline
  38494. // target so we use the global location here. It can be
  38495. // window.location or self.location in case it is used in a Web Worker.
  38496. // @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
  38497. s.update(index, index + exp.length, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], self.location)`);
  38498. continue;
  38499. }
  38500. }
  38501. const url = rawUrl.slice(1, -1);
  38502. let file;
  38503. if (url[0] === '.') {
  38504. file = slash$1(path$o.resolve(path$o.dirname(id), url));
  38505. }
  38506. else {
  38507. assetResolver ?? (assetResolver = config.createResolver({
  38508. extensions: [],
  38509. mainFields: [],
  38510. tryIndex: false,
  38511. preferRelative: true,
  38512. }));
  38513. file = await assetResolver(url, id);
  38514. file ?? (file = url.startsWith('/')
  38515. ? slash$1(path$o.join(config.publicDir, url))
  38516. : slash$1(path$o.resolve(path$o.dirname(id), url)));
  38517. }
  38518. // Get final asset URL. If the file does not exist,
  38519. // we fall back to the initial URL and let it resolve in runtime
  38520. let builtUrl;
  38521. if (file) {
  38522. try {
  38523. if (isParentDirectory(normalizedPublicDir, file)) {
  38524. const publicPath = '/' + path$o.posix.relative(normalizedPublicDir, file);
  38525. builtUrl = await fileToUrl(publicPath, config, this);
  38526. }
  38527. else {
  38528. builtUrl = await fileToUrl(file, config, this);
  38529. }
  38530. }
  38531. catch {
  38532. // do nothing, we'll log a warning after this
  38533. }
  38534. }
  38535. if (!builtUrl) {
  38536. const rawExp = code.slice(index, index + exp.length);
  38537. config.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
  38538. builtUrl = url;
  38539. }
  38540. s.update(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`);
  38541. }
  38542. if (s) {
  38543. return transformStableResult(s, id, config);
  38544. }
  38545. }
  38546. return null;
  38547. },
  38548. };
  38549. }
  38550. function buildGlobPattern(ast) {
  38551. let pattern = '';
  38552. let lastElementIndex = -1;
  38553. for (const exp of ast.expressions) {
  38554. for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
  38555. const el = ast.quasis[i];
  38556. if (el.end < exp.start) {
  38557. pattern += el.value.raw;
  38558. lastElementIndex = i;
  38559. }
  38560. }
  38561. pattern += '**';
  38562. }
  38563. for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
  38564. pattern += ast.quasis[i].value.raw;
  38565. }
  38566. return pattern;
  38567. }
  38568. /**
  38569. * plugin to ensure rollup can watch correctly.
  38570. */
  38571. function ensureWatchPlugin() {
  38572. return {
  38573. name: 'vite:ensure-watch',
  38574. load(id) {
  38575. if (queryRE.test(id)) {
  38576. this.addWatchFile(cleanUrl(id));
  38577. }
  38578. return null;
  38579. },
  38580. };
  38581. }
  38582. /**
  38583. * Prepares the rendered chunks to contain additional metadata during build.
  38584. */
  38585. function metadataPlugin() {
  38586. return {
  38587. name: 'vite:build-metadata',
  38588. async renderChunk(_code, chunk) {
  38589. chunk.viteMetadata = {
  38590. importedAssets: new Set(),
  38591. importedCss: new Set(),
  38592. };
  38593. return null;
  38594. },
  38595. };
  38596. }
  38597. class VariableDynamicImportError extends Error {}
  38598. /* eslint-disable-next-line no-template-curly-in-string */
  38599. const example = 'For example: import(`./foo/${bar}.js`).';
  38600. function sanitizeString(str) {
  38601. if (str.includes('*')) {
  38602. throw new VariableDynamicImportError('A dynamic import cannot contain * characters.');
  38603. }
  38604. return str;
  38605. }
  38606. function templateLiteralToGlob(node) {
  38607. let glob = '';
  38608. for (let i = 0; i < node.quasis.length; i += 1) {
  38609. glob += sanitizeString(node.quasis[i].value.raw);
  38610. if (node.expressions[i]) {
  38611. glob += expressionToGlob(node.expressions[i]);
  38612. }
  38613. }
  38614. return glob;
  38615. }
  38616. function callExpressionToGlob(node) {
  38617. const { callee } = node;
  38618. if (
  38619. callee.type === 'MemberExpression' &&
  38620. callee.property.type === 'Identifier' &&
  38621. callee.property.name === 'concat'
  38622. ) {
  38623. return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`;
  38624. }
  38625. return '*';
  38626. }
  38627. function binaryExpressionToGlob(node) {
  38628. if (node.operator !== '+') {
  38629. throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
  38630. }
  38631. return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
  38632. }
  38633. function expressionToGlob(node) {
  38634. switch (node.type) {
  38635. case 'TemplateLiteral':
  38636. return templateLiteralToGlob(node);
  38637. case 'CallExpression':
  38638. return callExpressionToGlob(node);
  38639. case 'BinaryExpression':
  38640. return binaryExpressionToGlob(node);
  38641. case 'Literal': {
  38642. return sanitizeString(node.value);
  38643. }
  38644. default:
  38645. return '*';
  38646. }
  38647. }
  38648. const defaultProtocol = 'file:';
  38649. const ignoredProtocols = ['data:', 'http:', 'https:'];
  38650. function shouldIgnore(glob) {
  38651. const containsAsterisk = glob.includes('*');
  38652. const globURL = new URL(glob, defaultProtocol);
  38653. const containsIgnoredProtocol = ignoredProtocols.some(
  38654. (ignoredProtocol) => ignoredProtocol === globURL.protocol
  38655. );
  38656. return !containsAsterisk || containsIgnoredProtocol;
  38657. }
  38658. function dynamicImportToGlob(node, sourceString) {
  38659. let glob = expressionToGlob(node);
  38660. if (shouldIgnore(glob)) {
  38661. return null;
  38662. }
  38663. glob = glob.replace(/\*\*/g, '*');
  38664. if (glob.startsWith('*')) {
  38665. throw new VariableDynamicImportError(
  38666. `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`
  38667. );
  38668. }
  38669. if (glob.startsWith('/')) {
  38670. throw new VariableDynamicImportError(
  38671. `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  38672. );
  38673. }
  38674. if (!glob.startsWith('./') && !glob.startsWith('../')) {
  38675. throw new VariableDynamicImportError(
  38676. `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  38677. );
  38678. }
  38679. // Disallow ./*.ext
  38680. const ownDirectoryStarExtension = /^\.\/\*\.[\w]+$/;
  38681. if (ownDirectoryStarExtension.test(glob)) {
  38682. throw new VariableDynamicImportError(
  38683. `${
  38684. `invalid import "${sourceString}". Variable imports cannot import their own directory, ` +
  38685. 'place imports in a separate directory or make the import filename more specific. '
  38686. }${example}`
  38687. );
  38688. }
  38689. if (require$$0$4.extname(glob) === '') {
  38690. throw new VariableDynamicImportError(
  38691. `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`
  38692. );
  38693. }
  38694. return glob;
  38695. }
  38696. const dynamicImportHelperId = '\0vite/dynamic-import-helper';
  38697. const relativePathRE = /^\.{1,2}\//;
  38698. // fast path to check if source contains a dynamic import. we check for a
  38699. // trailing slash too as a dynamic import statement can have comments between
  38700. // the `import` and the `(`.
  38701. const hasDynamicImportRE = /\bimport\s*[(/]/;
  38702. const dynamicImportHelper = (glob, path) => {
  38703. const v = glob[path];
  38704. if (v) {
  38705. return typeof v === 'function' ? v() : Promise.resolve(v);
  38706. }
  38707. return new Promise((_, reject) => {
  38708. (typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(reject.bind(null, new Error('Unknown variable dynamic import: ' + path)));
  38709. });
  38710. };
  38711. function parseDynamicImportPattern(strings) {
  38712. const filename = strings.slice(1, -1);
  38713. const rawQuery = parseRequest(filename);
  38714. let globParams = null;
  38715. const ast = parse$d(strings, {
  38716. ecmaVersion: 'latest',
  38717. sourceType: 'module',
  38718. }).body[0].expression;
  38719. const userPatternQuery = dynamicImportToGlob(ast, filename);
  38720. if (!userPatternQuery) {
  38721. return null;
  38722. }
  38723. const [userPattern] = userPatternQuery.split(requestQuerySplitRE, 2);
  38724. const [rawPattern] = filename.split(requestQuerySplitRE, 2);
  38725. if (rawQuery?.raw !== undefined) {
  38726. globParams = { as: 'raw' };
  38727. }
  38728. if (rawQuery?.url !== undefined) {
  38729. globParams = { as: 'url' };
  38730. }
  38731. if (rawQuery?.worker !== undefined) {
  38732. globParams = { as: 'worker' };
  38733. }
  38734. return {
  38735. globParams,
  38736. userPattern,
  38737. rawPattern,
  38738. };
  38739. }
  38740. async function transformDynamicImport(importSource, importer, resolve, root) {
  38741. if (importSource[1] !== '.' && importSource[1] !== '/') {
  38742. const resolvedFileName = await resolve(importSource.slice(1, -1), importer);
  38743. if (!resolvedFileName) {
  38744. return null;
  38745. }
  38746. const relativeFileName = posix$1.relative(posix$1.dirname(normalizePath$3(importer)), normalizePath$3(resolvedFileName));
  38747. importSource = normalizePath$3('`' + (relativeFileName[0] === '.' ? '' : './') + relativeFileName + '`');
  38748. }
  38749. const dynamicImportPattern = parseDynamicImportPattern(importSource);
  38750. if (!dynamicImportPattern) {
  38751. return null;
  38752. }
  38753. const { globParams, rawPattern, userPattern } = dynamicImportPattern;
  38754. const params = globParams
  38755. ? `, ${JSON.stringify({ ...globParams, import: '*' })}`
  38756. : '';
  38757. let newRawPattern = posix$1.relative(posix$1.dirname(importer), await toAbsoluteGlob(rawPattern, root, importer, resolve));
  38758. if (!relativePathRE.test(newRawPattern)) {
  38759. newRawPattern = `./${newRawPattern}`;
  38760. }
  38761. const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
  38762. return {
  38763. rawPattern: newRawPattern,
  38764. pattern: userPattern,
  38765. glob: exp,
  38766. };
  38767. }
  38768. function dynamicImportVarsPlugin(config) {
  38769. const resolve = config.createResolver({
  38770. preferRelative: true,
  38771. tryIndex: false,
  38772. extensions: [],
  38773. });
  38774. const { include, exclude, warnOnError } = config.build.dynamicImportVarsOptions;
  38775. const filter = createFilter(include, exclude);
  38776. return {
  38777. name: 'vite:dynamic-import-vars',
  38778. resolveId(id) {
  38779. if (id === dynamicImportHelperId) {
  38780. return id;
  38781. }
  38782. },
  38783. load(id) {
  38784. if (id === dynamicImportHelperId) {
  38785. return 'export default ' + dynamicImportHelper.toString();
  38786. }
  38787. },
  38788. async transform(source, importer) {
  38789. if (!filter(importer) ||
  38790. importer === CLIENT_ENTRY ||
  38791. !hasDynamicImportRE.test(source)) {
  38792. return;
  38793. }
  38794. await init;
  38795. let imports = [];
  38796. try {
  38797. imports = parse$e(source)[0];
  38798. }
  38799. catch (e) {
  38800. // ignore as it might not be a JS file, the subsequent plugins will catch the error
  38801. return null;
  38802. }
  38803. if (!imports.length) {
  38804. return null;
  38805. }
  38806. let s;
  38807. let needDynamicImportHelper = false;
  38808. for (let index = 0; index < imports.length; index++) {
  38809. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = imports[index];
  38810. if (dynamicIndex === -1 || source[start] !== '`') {
  38811. continue;
  38812. }
  38813. s || (s = new MagicString(source));
  38814. let result;
  38815. try {
  38816. // When import string is using backticks, es-module-lexer `end` captures
  38817. // until the closing parenthesis, instead of the closing backtick.
  38818. // There may be inline comments between the backtick and the closing
  38819. // parenthesis, so we manually remove them for now.
  38820. // See https://github.com/guybedford/es-module-lexer/issues/118
  38821. const importSource = removeComments(source.slice(start, end)).trim();
  38822. result = await transformDynamicImport(importSource, importer, resolve, config.root);
  38823. }
  38824. catch (error) {
  38825. if (warnOnError) {
  38826. this.warn(error);
  38827. }
  38828. else {
  38829. this.error(error);
  38830. }
  38831. }
  38832. if (!result) {
  38833. continue;
  38834. }
  38835. const { rawPattern, glob } = result;
  38836. needDynamicImportHelper = true;
  38837. s.overwrite(expStart, expEnd, `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)`);
  38838. }
  38839. if (s) {
  38840. if (needDynamicImportHelper) {
  38841. s.prepend(`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`);
  38842. }
  38843. return transformStableResult(s, importer, config);
  38844. }
  38845. },
  38846. };
  38847. }
  38848. async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
  38849. const isBuild = config.command === 'build';
  38850. const isWatch = isBuild && !!config.build.watch;
  38851. const buildPlugins = isBuild
  38852. ? await (await Promise.resolve().then(function () { return build$1; })).resolveBuildPlugins(config)
  38853. : { pre: [], post: [] };
  38854. const { modulePreload } = config.build;
  38855. return [
  38856. ...(isDepsOptimizerEnabled(config, false) ||
  38857. isDepsOptimizerEnabled(config, true)
  38858. ? [
  38859. isBuild
  38860. ? optimizedDepsBuildPlugin(config)
  38861. : optimizedDepsPlugin(config),
  38862. ]
  38863. : []),
  38864. isWatch ? ensureWatchPlugin() : null,
  38865. isBuild ? metadataPlugin() : null,
  38866. watchPackageDataPlugin(config.packageCache),
  38867. preAliasPlugin(config),
  38868. alias$1({ entries: config.resolve.alias }),
  38869. ...prePlugins,
  38870. modulePreload === true ||
  38871. (typeof modulePreload === 'object' && modulePreload.polyfill)
  38872. ? modulePreloadPolyfillPlugin(config)
  38873. : null,
  38874. resolvePlugin({
  38875. ...config.resolve,
  38876. root: config.root,
  38877. isProduction: config.isProduction,
  38878. isBuild,
  38879. packageCache: config.packageCache,
  38880. ssrConfig: config.ssr,
  38881. asSrc: true,
  38882. getDepsOptimizer: (ssr) => getDepsOptimizer(config, ssr),
  38883. shouldExternalize: isBuild && config.build.ssr && config.ssr?.format !== 'cjs'
  38884. ? (id) => shouldExternalizeForSSR(id, config)
  38885. : undefined,
  38886. }),
  38887. htmlInlineProxyPlugin(config),
  38888. cssPlugin(config),
  38889. config.esbuild !== false ? esbuildPlugin(config) : null,
  38890. jsonPlugin({
  38891. namedExports: true,
  38892. ...config.json,
  38893. }, isBuild),
  38894. wasmHelperPlugin(config),
  38895. webWorkerPlugin(config),
  38896. assetPlugin(config),
  38897. ...normalPlugins,
  38898. wasmFallbackPlugin(),
  38899. definePlugin(config),
  38900. cssPostPlugin(config),
  38901. isBuild && buildHtmlPlugin(config),
  38902. workerImportMetaUrlPlugin(config),
  38903. assetImportMetaUrlPlugin(config),
  38904. ...buildPlugins.pre,
  38905. dynamicImportVarsPlugin(config),
  38906. importGlobPlugin(config),
  38907. ...postPlugins,
  38908. ...buildPlugins.post,
  38909. // internal server-only plugins are always applied after everything else
  38910. ...(isBuild
  38911. ? []
  38912. : [clientInjectionsPlugin(config), importAnalysisPlugin(config)]),
  38913. ].filter(Boolean);
  38914. }
  38915. function createPluginHookUtils(plugins) {
  38916. // sort plugins per hook
  38917. const sortedPluginsCache = new Map();
  38918. function getSortedPlugins(hookName) {
  38919. if (sortedPluginsCache.has(hookName))
  38920. return sortedPluginsCache.get(hookName);
  38921. const sorted = getSortedPluginsByHook(hookName, plugins);
  38922. sortedPluginsCache.set(hookName, sorted);
  38923. return sorted;
  38924. }
  38925. function getSortedPluginHooks(hookName) {
  38926. const plugins = getSortedPlugins(hookName);
  38927. return plugins
  38928. .map((p) => {
  38929. const hook = p[hookName];
  38930. return typeof hook === 'object' && 'handler' in hook
  38931. ? hook.handler
  38932. : hook;
  38933. })
  38934. .filter(Boolean);
  38935. }
  38936. return {
  38937. getSortedPlugins,
  38938. getSortedPluginHooks,
  38939. };
  38940. }
  38941. function getSortedPluginsByHook(hookName, plugins) {
  38942. const pre = [];
  38943. const normal = [];
  38944. const post = [];
  38945. for (const plugin of plugins) {
  38946. const hook = plugin[hookName];
  38947. if (hook) {
  38948. if (typeof hook === 'object') {
  38949. if (hook.order === 'pre') {
  38950. pre.push(plugin);
  38951. continue;
  38952. }
  38953. if (hook.order === 'post') {
  38954. post.push(plugin);
  38955. continue;
  38956. }
  38957. }
  38958. normal.push(plugin);
  38959. }
  38960. }
  38961. return [...pre, ...normal, ...post];
  38962. }
  38963. function ansiRegex({onlyFirst = false} = {}) {
  38964. const pattern = [
  38965. '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
  38966. '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
  38967. ].join('|');
  38968. return new RegExp(pattern, onlyFirst ? undefined : 'g');
  38969. }
  38970. function stripAnsi(string) {
  38971. if (typeof string !== 'string') {
  38972. throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
  38973. }
  38974. return string.replace(ansiRegex(), '');
  38975. }
  38976. function prepareError(err) {
  38977. // only copy the information we need and avoid serializing unnecessary
  38978. // properties, since some errors may attach full objects (e.g. PostCSS)
  38979. return {
  38980. message: stripAnsi(err.message),
  38981. stack: stripAnsi(cleanStack(err.stack || '')),
  38982. id: err.id,
  38983. frame: stripAnsi(err.frame || ''),
  38984. plugin: err.plugin,
  38985. pluginCode: err.pluginCode,
  38986. loc: err.loc,
  38987. };
  38988. }
  38989. function buildErrorMessage(err, args = [], includeStack = true) {
  38990. if (err.plugin)
  38991. args.push(` Plugin: ${colors$1.magenta(err.plugin)}`);
  38992. const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : '';
  38993. if (err.id)
  38994. args.push(` File: ${colors$1.cyan(err.id)}${loc}`);
  38995. if (err.frame)
  38996. args.push(colors$1.yellow(pad$1(err.frame)));
  38997. if (includeStack && err.stack)
  38998. args.push(pad$1(cleanStack(err.stack)));
  38999. return args.join('\n');
  39000. }
  39001. function cleanStack(stack) {
  39002. return stack
  39003. .split(/\n/g)
  39004. .filter((l) => /^\s*at/.test(l))
  39005. .join('\n');
  39006. }
  39007. function logError(server, err) {
  39008. const msg = buildErrorMessage(err, [
  39009. colors$1.red(`Internal server error: ${err.message}`),
  39010. ]);
  39011. server.config.logger.error(msg, {
  39012. clear: true,
  39013. timestamp: true,
  39014. error: err,
  39015. });
  39016. server.ws.send({
  39017. type: 'error',
  39018. err: prepareError(err),
  39019. });
  39020. }
  39021. function errorMiddleware(server, allowNext = false) {
  39022. // note the 4 args must be kept for connect to treat this as error middleware
  39023. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  39024. return function viteErrorMiddleware(err, _req, res, next) {
  39025. logError(server, err);
  39026. if (allowNext) {
  39027. next();
  39028. }
  39029. else {
  39030. res.statusCode = 500;
  39031. res.end(`
  39032. <!DOCTYPE html>
  39033. <html lang="en">
  39034. <head>
  39035. <meta charset="UTF-8" />
  39036. <title>Error</title>
  39037. <script type="module">
  39038. import { ErrorOverlay } from '/@vite/client'
  39039. document.body.appendChild(new ErrorOverlay(${JSON.stringify(prepareError(err)).replace(/</g, '\\u003c')}))
  39040. </script>
  39041. </head>
  39042. <body>
  39043. </body>
  39044. </html>
  39045. `);
  39046. }
  39047. };
  39048. }
  39049. /**
  39050. * This file is refactored into TypeScript based on
  39051. * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
  39052. */
  39053. let parser = Parser$1;
  39054. async function createPluginContainer(config, moduleGraph, watcher) {
  39055. const { plugins, logger, root, build: { rollupOptions }, } = config;
  39056. const { getSortedPluginHooks, getSortedPlugins } = createPluginHookUtils(plugins);
  39057. const seenResolves = {};
  39058. const debugResolve = createDebugger('vite:resolve');
  39059. const debugPluginResolve = createDebugger('vite:plugin-resolve', {
  39060. onlyWhenFocused: 'vite:plugin',
  39061. });
  39062. const debugPluginTransform = createDebugger('vite:plugin-transform', {
  39063. onlyWhenFocused: 'vite:plugin',
  39064. });
  39065. const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
  39066. const debugSourcemapCombine = createDebugger('vite:sourcemap-combine', {
  39067. onlyWhenFocused: true,
  39068. });
  39069. // ---------------------------------------------------------------------------
  39070. const watchFiles = new Set();
  39071. const minimalContext = {
  39072. meta: {
  39073. rollupVersion: VERSION,
  39074. watchMode: true,
  39075. },
  39076. };
  39077. function warnIncompatibleMethod(method, plugin) {
  39078. logger.warn(colors$1.cyan(`[plugin:${plugin}] `) +
  39079. colors$1.yellow(`context method ${colors$1.bold(`${method}()`)} is not supported in serve mode. This plugin is likely not vite-compatible.`));
  39080. }
  39081. // parallel, ignores returns
  39082. async function hookParallel(hookName, context, args) {
  39083. const parallelPromises = [];
  39084. for (const plugin of getSortedPlugins(hookName)) {
  39085. const hook = plugin[hookName];
  39086. if (!hook)
  39087. continue;
  39088. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  39089. // @ts-ignore hook is not a primitive
  39090. const handler = 'handler' in hook ? hook.handler : hook;
  39091. if (hook.sequential) {
  39092. await Promise.all(parallelPromises);
  39093. parallelPromises.length = 0;
  39094. await handler.apply(context(plugin), args(plugin));
  39095. }
  39096. else {
  39097. parallelPromises.push(handler.apply(context(plugin), args(plugin)));
  39098. }
  39099. }
  39100. await Promise.all(parallelPromises);
  39101. }
  39102. // throw when an unsupported ModuleInfo property is accessed,
  39103. // so that incompatible plugins fail in a non-cryptic way.
  39104. const ModuleInfoProxy = {
  39105. get(info, key) {
  39106. if (key in info) {
  39107. return info[key];
  39108. }
  39109. // Don't throw an error when returning from an async function
  39110. if (key === 'then') {
  39111. return undefined;
  39112. }
  39113. throw Error(`[vite] The "${key}" property of ModuleInfo is not supported.`);
  39114. },
  39115. };
  39116. // same default value of "moduleInfo.meta" as in Rollup
  39117. const EMPTY_OBJECT = Object.freeze({});
  39118. function getModuleInfo(id) {
  39119. const module = moduleGraph?.getModuleById(id);
  39120. if (!module) {
  39121. return null;
  39122. }
  39123. if (!module.info) {
  39124. module.info = new Proxy({ id, meta: module.meta || EMPTY_OBJECT }, ModuleInfoProxy);
  39125. }
  39126. return module.info;
  39127. }
  39128. function updateModuleInfo(id, { meta }) {
  39129. if (meta) {
  39130. const moduleInfo = getModuleInfo(id);
  39131. if (moduleInfo) {
  39132. moduleInfo.meta = { ...moduleInfo.meta, ...meta };
  39133. }
  39134. }
  39135. }
  39136. // we should create a new context for each async hook pipeline so that the
  39137. // active plugin in that pipeline can be tracked in a concurrency-safe manner.
  39138. // using a class to make creating new contexts more efficient
  39139. class Context {
  39140. constructor(initialPlugin) {
  39141. this.meta = minimalContext.meta;
  39142. this.ssr = false;
  39143. this._scan = false;
  39144. this._activeId = null;
  39145. this._activeCode = null;
  39146. this._addedImports = null;
  39147. this._activePlugin = initialPlugin || null;
  39148. }
  39149. parse(code, opts = {}) {
  39150. return parser.parse(code, {
  39151. sourceType: 'module',
  39152. ecmaVersion: 'latest',
  39153. locations: true,
  39154. ...opts,
  39155. });
  39156. }
  39157. async resolve(id, importer, options) {
  39158. let skip;
  39159. if (options?.skipSelf && this._activePlugin) {
  39160. skip = new Set(this._resolveSkips);
  39161. skip.add(this._activePlugin);
  39162. }
  39163. let out = await container.resolveId(id, importer, {
  39164. assertions: options?.assertions,
  39165. custom: options?.custom,
  39166. isEntry: !!options?.isEntry,
  39167. skip,
  39168. ssr: this.ssr,
  39169. scan: this._scan,
  39170. });
  39171. if (typeof out === 'string')
  39172. out = { id: out };
  39173. return out;
  39174. }
  39175. async load(options) {
  39176. // We may not have added this to our module graph yet, so ensure it exists
  39177. await moduleGraph?.ensureEntryFromUrl(unwrapId(options.id), this.ssr);
  39178. // Not all options passed to this function make sense in the context of loading individual files,
  39179. // but we can at least update the module info properties we support
  39180. updateModuleInfo(options.id, options);
  39181. await container.load(options.id, { ssr: this.ssr });
  39182. const moduleInfo = this.getModuleInfo(options.id);
  39183. // This shouldn't happen due to calling ensureEntryFromUrl, but 1) our types can't ensure that
  39184. // and 2) moduleGraph may not have been provided (though in the situations where that happens,
  39185. // we should never have plugins calling this.load)
  39186. if (!moduleInfo)
  39187. throw Error(`Failed to load module with id ${options.id}`);
  39188. return moduleInfo;
  39189. }
  39190. getModuleInfo(id) {
  39191. return getModuleInfo(id);
  39192. }
  39193. getModuleIds() {
  39194. return moduleGraph
  39195. ? moduleGraph.idToModuleMap.keys()
  39196. : Array.prototype[Symbol.iterator]();
  39197. }
  39198. addWatchFile(id) {
  39199. watchFiles.add(id);
  39200. (this._addedImports || (this._addedImports = new Set())).add(id);
  39201. if (watcher)
  39202. ensureWatchedFile(watcher, id, root);
  39203. }
  39204. getWatchFiles() {
  39205. return [...watchFiles];
  39206. }
  39207. emitFile(assetOrFile) {
  39208. warnIncompatibleMethod(`emitFile`, this._activePlugin.name);
  39209. return '';
  39210. }
  39211. setAssetSource() {
  39212. warnIncompatibleMethod(`setAssetSource`, this._activePlugin.name);
  39213. }
  39214. getFileName() {
  39215. warnIncompatibleMethod(`getFileName`, this._activePlugin.name);
  39216. return '';
  39217. }
  39218. warn(e, position) {
  39219. const err = formatError(e, position, this);
  39220. const msg = buildErrorMessage(err, [colors$1.yellow(`warning: ${err.message}`)], false);
  39221. logger.warn(msg, {
  39222. clear: true,
  39223. timestamp: true,
  39224. });
  39225. }
  39226. error(e, position) {
  39227. // error thrown here is caught by the transform middleware and passed on
  39228. // the the error middleware.
  39229. throw formatError(e, position, this);
  39230. }
  39231. }
  39232. function formatError(e, position, ctx) {
  39233. const err = (typeof e === 'string' ? new Error(e) : e);
  39234. if (err.pluginCode) {
  39235. return err; // The plugin likely called `this.error`
  39236. }
  39237. if (err.file && err.name === 'CssSyntaxError') {
  39238. err.id = normalizePath$3(err.file);
  39239. }
  39240. if (ctx._activePlugin)
  39241. err.plugin = ctx._activePlugin.name;
  39242. if (ctx._activeId && !err.id)
  39243. err.id = ctx._activeId;
  39244. if (ctx._activeCode) {
  39245. err.pluginCode = ctx._activeCode;
  39246. // some rollup plugins, e.g. json, sets err.position instead of err.pos
  39247. const pos = position ?? err.pos ?? err.position;
  39248. if (pos != null) {
  39249. let errLocation;
  39250. try {
  39251. errLocation = numberToPos(ctx._activeCode, pos);
  39252. }
  39253. catch (err2) {
  39254. logger.error(colors$1.red(`Error in error handler:\n${err2.stack || err2.message}\n`),
  39255. // print extra newline to separate the two errors
  39256. { error: err2 });
  39257. throw err;
  39258. }
  39259. err.loc = err.loc || {
  39260. file: err.id,
  39261. ...errLocation,
  39262. };
  39263. err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos);
  39264. }
  39265. else if (err.loc) {
  39266. // css preprocessors may report errors in an included file
  39267. if (!err.frame) {
  39268. let code = ctx._activeCode;
  39269. if (err.loc.file) {
  39270. err.id = normalizePath$3(err.loc.file);
  39271. try {
  39272. code = fs$l.readFileSync(err.loc.file, 'utf-8');
  39273. }
  39274. catch { }
  39275. }
  39276. err.frame = generateCodeFrame(code, err.loc);
  39277. }
  39278. }
  39279. else if (err.line && err.column) {
  39280. err.loc = {
  39281. file: err.id,
  39282. line: err.line,
  39283. column: err.column,
  39284. };
  39285. err.frame = err.frame || generateCodeFrame(err.id, err.loc);
  39286. }
  39287. if (ctx instanceof TransformContext &&
  39288. typeof err.loc?.line === 'number' &&
  39289. typeof err.loc?.column === 'number') {
  39290. const rawSourceMap = ctx._getCombinedSourcemap();
  39291. if (rawSourceMap) {
  39292. const traced = new TraceMap(rawSourceMap);
  39293. const { source, line, column } = originalPositionFor$1(traced, {
  39294. line: Number(err.loc.line),
  39295. column: Number(err.loc.column),
  39296. });
  39297. if (source && line != null && column != null) {
  39298. err.loc = { file: source, line, column };
  39299. }
  39300. }
  39301. }
  39302. }
  39303. else if (err.loc) {
  39304. if (!err.frame) {
  39305. let code = err.pluginCode;
  39306. if (err.loc.file) {
  39307. err.id = normalizePath$3(err.loc.file);
  39308. if (!code) {
  39309. try {
  39310. code = fs$l.readFileSync(err.loc.file, 'utf-8');
  39311. }
  39312. catch { }
  39313. }
  39314. }
  39315. if (code) {
  39316. err.frame = generateCodeFrame(code, err.loc);
  39317. }
  39318. }
  39319. }
  39320. if (typeof err.loc?.column !== 'number' &&
  39321. typeof err.loc?.line !== 'number' &&
  39322. !err.loc?.file) {
  39323. delete err.loc;
  39324. }
  39325. return err;
  39326. }
  39327. class TransformContext extends Context {
  39328. constructor(filename, code, inMap) {
  39329. super();
  39330. this.originalSourcemap = null;
  39331. this.sourcemapChain = [];
  39332. this.combinedMap = null;
  39333. this.filename = filename;
  39334. this.originalCode = code;
  39335. if (inMap) {
  39336. if (debugSourcemapCombine) {
  39337. // @ts-expect-error inject name for debug purpose
  39338. inMap.name = '$inMap';
  39339. }
  39340. this.sourcemapChain.push(inMap);
  39341. }
  39342. }
  39343. _getCombinedSourcemap(createIfNull = false) {
  39344. if (debugSourcemapCombine &&
  39345. debugSourcemapCombineFilter &&
  39346. this.filename.includes(debugSourcemapCombineFilter)) {
  39347. debugSourcemapCombine('----------', this.filename);
  39348. debugSourcemapCombine(this.combinedMap);
  39349. debugSourcemapCombine(this.sourcemapChain);
  39350. debugSourcemapCombine('----------');
  39351. }
  39352. let combinedMap = this.combinedMap;
  39353. for (let m of this.sourcemapChain) {
  39354. if (typeof m === 'string')
  39355. m = JSON.parse(m);
  39356. if (!('version' in m)) {
  39357. // empty, nullified source map
  39358. combinedMap = this.combinedMap = null;
  39359. this.sourcemapChain.length = 0;
  39360. break;
  39361. }
  39362. if (!combinedMap) {
  39363. combinedMap = m;
  39364. }
  39365. else {
  39366. combinedMap = combineSourcemaps(cleanUrl(this.filename), [
  39367. {
  39368. ...m,
  39369. sourcesContent: combinedMap.sourcesContent,
  39370. },
  39371. combinedMap,
  39372. ]);
  39373. }
  39374. }
  39375. if (!combinedMap) {
  39376. return createIfNull
  39377. ? new MagicString(this.originalCode).generateMap({
  39378. includeContent: true,
  39379. hires: true,
  39380. source: cleanUrl(this.filename),
  39381. })
  39382. : null;
  39383. }
  39384. if (combinedMap !== this.combinedMap) {
  39385. this.combinedMap = combinedMap;
  39386. this.sourcemapChain.length = 0;
  39387. }
  39388. return this.combinedMap;
  39389. }
  39390. getCombinedSourcemap() {
  39391. return this._getCombinedSourcemap(true);
  39392. }
  39393. }
  39394. let closed = false;
  39395. const container = {
  39396. options: await (async () => {
  39397. let options = rollupOptions;
  39398. for (const optionsHook of getSortedPluginHooks('options')) {
  39399. options = (await optionsHook.call(minimalContext, options)) || options;
  39400. }
  39401. if (options.acornInjectPlugins) {
  39402. parser = Parser$1.extend(...arraify(options.acornInjectPlugins));
  39403. }
  39404. return {
  39405. acorn,
  39406. acornInjectPlugins: [],
  39407. ...options,
  39408. };
  39409. })(),
  39410. getModuleInfo,
  39411. async buildStart() {
  39412. await hookParallel('buildStart', (plugin) => new Context(plugin), () => [container.options]);
  39413. },
  39414. async resolveId(rawId, importer = join$2(root, 'index.html'), options) {
  39415. const skip = options?.skip;
  39416. const ssr = options?.ssr;
  39417. const scan = !!options?.scan;
  39418. const ctx = new Context();
  39419. ctx.ssr = !!ssr;
  39420. ctx._scan = scan;
  39421. ctx._resolveSkips = skip;
  39422. const resolveStart = debugResolve ? performance$1.now() : 0;
  39423. let id = null;
  39424. const partial = {};
  39425. for (const plugin of getSortedPlugins('resolveId')) {
  39426. if (!plugin.resolveId)
  39427. continue;
  39428. if (skip?.has(plugin))
  39429. continue;
  39430. ctx._activePlugin = plugin;
  39431. const pluginResolveStart = debugPluginResolve ? performance$1.now() : 0;
  39432. const handler = 'handler' in plugin.resolveId
  39433. ? plugin.resolveId.handler
  39434. : plugin.resolveId;
  39435. const result = await handler.call(ctx, rawId, importer, {
  39436. assertions: options?.assertions ?? {},
  39437. custom: options?.custom,
  39438. isEntry: !!options?.isEntry,
  39439. ssr,
  39440. scan,
  39441. });
  39442. if (!result)
  39443. continue;
  39444. if (typeof result === 'string') {
  39445. id = result;
  39446. }
  39447. else {
  39448. id = result.id;
  39449. Object.assign(partial, result);
  39450. }
  39451. debugPluginResolve?.(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, root));
  39452. // resolveId() is hookFirst - first non-null result is returned.
  39453. break;
  39454. }
  39455. if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
  39456. const key = rawId + id;
  39457. // avoid spamming
  39458. if (!seenResolves[key]) {
  39459. seenResolves[key] = true;
  39460. debugResolve(`${timeFrom(resolveStart)} ${colors$1.cyan(rawId)} -> ${colors$1.dim(id)}`);
  39461. }
  39462. }
  39463. if (id) {
  39464. partial.id = isExternalUrl(id) ? id : normalizePath$3(id);
  39465. return partial;
  39466. }
  39467. else {
  39468. return null;
  39469. }
  39470. },
  39471. async load(id, options) {
  39472. const ssr = options?.ssr;
  39473. const ctx = new Context();
  39474. ctx.ssr = !!ssr;
  39475. for (const plugin of getSortedPlugins('load')) {
  39476. if (!plugin.load)
  39477. continue;
  39478. ctx._activePlugin = plugin;
  39479. const handler = 'handler' in plugin.load ? plugin.load.handler : plugin.load;
  39480. const result = await handler.call(ctx, id, { ssr });
  39481. if (result != null) {
  39482. if (isObject$2(result)) {
  39483. updateModuleInfo(id, result);
  39484. }
  39485. return result;
  39486. }
  39487. }
  39488. return null;
  39489. },
  39490. async transform(code, id, options) {
  39491. const inMap = options?.inMap;
  39492. const ssr = options?.ssr;
  39493. const ctx = new TransformContext(id, code, inMap);
  39494. ctx.ssr = !!ssr;
  39495. for (const plugin of getSortedPlugins('transform')) {
  39496. if (!plugin.transform)
  39497. continue;
  39498. ctx._activePlugin = plugin;
  39499. ctx._activeId = id;
  39500. ctx._activeCode = code;
  39501. const start = debugPluginTransform ? performance$1.now() : 0;
  39502. let result;
  39503. const handler = 'handler' in plugin.transform
  39504. ? plugin.transform.handler
  39505. : plugin.transform;
  39506. try {
  39507. result = await handler.call(ctx, code, id, { ssr });
  39508. }
  39509. catch (e) {
  39510. ctx.error(e);
  39511. }
  39512. if (!result)
  39513. continue;
  39514. debugPluginTransform?.(timeFrom(start), plugin.name, prettifyUrl(id, root));
  39515. if (isObject$2(result)) {
  39516. if (result.code !== undefined) {
  39517. code = result.code;
  39518. if (result.map) {
  39519. if (debugSourcemapCombine) {
  39520. // @ts-expect-error inject plugin name for debug purpose
  39521. result.map.name = plugin.name;
  39522. }
  39523. ctx.sourcemapChain.push(result.map);
  39524. }
  39525. }
  39526. updateModuleInfo(id, result);
  39527. }
  39528. else {
  39529. code = result;
  39530. }
  39531. }
  39532. return {
  39533. code,
  39534. map: ctx._getCombinedSourcemap(),
  39535. };
  39536. },
  39537. async close() {
  39538. if (closed)
  39539. return;
  39540. const ctx = new Context();
  39541. await hookParallel('buildEnd', () => ctx, () => []);
  39542. await hookParallel('closeBundle', () => ctx, () => []);
  39543. closed = true;
  39544. },
  39545. };
  39546. return container;
  39547. }
  39548. const debug$9 = createDebugger('vite:deps');
  39549. const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/;
  39550. // A simple regex to detect import sources. This is only used on
  39551. // <script lang="ts"> blocks in vue (setup only) or svelte files, since
  39552. // seemingly unused imports are dropped by esbuild when transpiling TS which
  39553. // prevents it from crawling further.
  39554. // We can't use es-module-lexer because it can't handle TS, and don't want to
  39555. // use Acorn because it's slow. Luckily this doesn't have to be bullet proof
  39556. // since even missed imports can be caught at runtime, and false positives will
  39557. // simply be ignored.
  39558. const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
  39559. function scanImports(config) {
  39560. // Only used to scan non-ssr code
  39561. const start = performance$1.now();
  39562. const deps = {};
  39563. const missing = {};
  39564. let entries;
  39565. const scanContext = { cancelled: false };
  39566. const esbuildContext = computeEntries(config).then((computedEntries) => {
  39567. entries = computedEntries;
  39568. if (!entries.length) {
  39569. if (!config.optimizeDeps.entries && !config.optimizeDeps.include) {
  39570. config.logger.warn(colors$1.yellow('(!) Could not auto-determine entry point from rollupOptions or html files ' +
  39571. 'and there are no explicit optimizeDeps.include patterns. ' +
  39572. 'Skipping dependency pre-bundling.'));
  39573. }
  39574. return;
  39575. }
  39576. if (scanContext.cancelled)
  39577. return;
  39578. debug$9?.(`Crawling dependencies using entries: ${entries
  39579. .map((entry) => `\n ${colors$1.dim(entry)}`)
  39580. .join('')}`);
  39581. return prepareEsbuildScanner(config, entries, deps, missing, scanContext);
  39582. });
  39583. const result = esbuildContext
  39584. .then((context) => {
  39585. function disposeContext() {
  39586. return context?.dispose().catch((e) => {
  39587. config.logger.error('Failed to dispose esbuild context', { error: e });
  39588. });
  39589. }
  39590. if (!context || scanContext?.cancelled) {
  39591. disposeContext();
  39592. return { deps: {}, missing: {} };
  39593. }
  39594. return context
  39595. .rebuild()
  39596. .then(() => {
  39597. return {
  39598. // Ensure a fixed order so hashes are stable and improve logs
  39599. deps: orderedDependencies(deps),
  39600. missing,
  39601. };
  39602. })
  39603. .finally(() => {
  39604. return disposeContext();
  39605. });
  39606. })
  39607. .catch(async (e) => {
  39608. if (e.errors && e.message.includes('The build was canceled')) {
  39609. // esbuild logs an error when cancelling, but this is expected so
  39610. // return an empty result instead
  39611. return { deps: {}, missing: {} };
  39612. }
  39613. const prependMessage = colors$1.red(`\
  39614. Failed to scan for dependencies from entries:
  39615. ${entries.join('\n')}
  39616. `);
  39617. if (e.errors) {
  39618. const msgs = await formatMessages(e.errors, {
  39619. kind: 'error',
  39620. color: true,
  39621. });
  39622. e.message = prependMessage + msgs.join('\n');
  39623. }
  39624. else {
  39625. e.message = prependMessage + e.message;
  39626. }
  39627. throw e;
  39628. })
  39629. .finally(() => {
  39630. if (debug$9) {
  39631. const duration = (performance$1.now() - start).toFixed(2);
  39632. const depsStr = Object.keys(orderedDependencies(deps))
  39633. .sort()
  39634. .map((id) => `\n ${colors$1.cyan(id)} -> ${colors$1.dim(deps[id])}`)
  39635. .join('') || colors$1.dim('no dependencies found');
  39636. debug$9(`Scan completed in ${duration}ms: ${depsStr}`);
  39637. }
  39638. });
  39639. return {
  39640. cancel: async () => {
  39641. scanContext.cancelled = true;
  39642. return esbuildContext.then((context) => context?.cancel());
  39643. },
  39644. result,
  39645. };
  39646. }
  39647. async function computeEntries(config) {
  39648. let entries = [];
  39649. const explicitEntryPatterns = config.optimizeDeps.entries;
  39650. const buildInput = config.build.rollupOptions?.input;
  39651. if (explicitEntryPatterns) {
  39652. entries = await globEntries(explicitEntryPatterns, config);
  39653. }
  39654. else if (buildInput) {
  39655. const resolvePath = (p) => path$o.resolve(config.root, p);
  39656. if (typeof buildInput === 'string') {
  39657. entries = [resolvePath(buildInput)];
  39658. }
  39659. else if (Array.isArray(buildInput)) {
  39660. entries = buildInput.map(resolvePath);
  39661. }
  39662. else if (isObject$2(buildInput)) {
  39663. entries = Object.values(buildInput).map(resolvePath);
  39664. }
  39665. else {
  39666. throw new Error('invalid rollupOptions.input value.');
  39667. }
  39668. }
  39669. else {
  39670. entries = await globEntries('**/*.html', config);
  39671. }
  39672. // Non-supported entry file types and virtual files should not be scanned for
  39673. // dependencies.
  39674. entries = entries.filter((entry) => isScannable(entry) && fs$l.existsSync(entry));
  39675. return entries;
  39676. }
  39677. async function prepareEsbuildScanner(config, entries, deps, missing, scanContext) {
  39678. const container = await createPluginContainer(config);
  39679. if (scanContext?.cancelled)
  39680. return;
  39681. const plugin = esbuildScanPlugin(config, container, deps, missing, entries);
  39682. const { plugins = [], ...esbuildOptions } = config.optimizeDeps?.esbuildOptions ?? {};
  39683. return await esbuild.context({
  39684. absWorkingDir: process.cwd(),
  39685. write: false,
  39686. stdin: {
  39687. contents: entries.map((e) => `import ${JSON.stringify(e)}`).join('\n'),
  39688. loader: 'js',
  39689. },
  39690. bundle: true,
  39691. format: 'esm',
  39692. logLevel: 'silent',
  39693. plugins: [...plugins, plugin],
  39694. ...esbuildOptions,
  39695. });
  39696. }
  39697. function orderedDependencies(deps) {
  39698. const depsList = Object.entries(deps);
  39699. // Ensure the same browserHash for the same set of dependencies
  39700. depsList.sort((a, b) => a[0].localeCompare(b[0]));
  39701. return Object.fromEntries(depsList);
  39702. }
  39703. function globEntries(pattern, config) {
  39704. return glob(pattern, {
  39705. cwd: config.root,
  39706. ignore: [
  39707. '**/node_modules/**',
  39708. `**/${config.build.outDir}/**`,
  39709. // if there aren't explicit entries, also ignore other common folders
  39710. ...(config.optimizeDeps.entries
  39711. ? []
  39712. : [`**/__tests__/**`, `**/coverage/**`]),
  39713. ],
  39714. absolute: true,
  39715. suppressErrors: true, // suppress EACCES errors
  39716. });
  39717. }
  39718. const scriptRE = /(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis;
  39719. const commentRE = /<!--.*?-->/gs;
  39720. const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  39721. const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  39722. const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  39723. const contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  39724. function esbuildScanPlugin(config, container, depImports, missing, entries) {
  39725. const seen = new Map();
  39726. const resolve = async (id, importer, options) => {
  39727. const key = id + (importer && path$o.dirname(importer));
  39728. if (seen.has(key)) {
  39729. return seen.get(key);
  39730. }
  39731. const resolved = await container.resolveId(id, importer && normalizePath$3(importer), {
  39732. ...options,
  39733. scan: true,
  39734. });
  39735. const res = resolved?.id;
  39736. seen.set(key, res);
  39737. return res;
  39738. };
  39739. const include = config.optimizeDeps?.include;
  39740. const exclude = [
  39741. ...(config.optimizeDeps?.exclude || []),
  39742. '@vite/client',
  39743. '@vite/env',
  39744. ];
  39745. const externalUnlessEntry = ({ path }) => ({
  39746. path,
  39747. external: !entries.includes(path),
  39748. });
  39749. const doTransformGlobImport = async (contents, id, loader) => {
  39750. let transpiledContents;
  39751. // transpile because `transformGlobImport` only expects js
  39752. if (loader !== 'js') {
  39753. transpiledContents = (await transform$2(contents, { loader })).code;
  39754. }
  39755. else {
  39756. transpiledContents = contents;
  39757. }
  39758. const result = await transformGlobImport(transpiledContents, id, config.root, resolve, config.isProduction);
  39759. return result?.s.toString() || transpiledContents;
  39760. };
  39761. return {
  39762. name: 'vite:dep-scan',
  39763. setup(build) {
  39764. const scripts = {};
  39765. // external urls
  39766. build.onResolve({ filter: externalRE }, ({ path }) => ({
  39767. path,
  39768. external: true,
  39769. }));
  39770. // data urls
  39771. build.onResolve({ filter: dataUrlRE }, ({ path }) => ({
  39772. path,
  39773. external: true,
  39774. }));
  39775. // local scripts (`<script>` in Svelte and `<script setup>` in Vue)
  39776. build.onResolve({ filter: virtualModuleRE }, ({ path }) => {
  39777. return {
  39778. // strip prefix to get valid filesystem path so esbuild can resolve imports in the file
  39779. path: path.replace(virtualModulePrefix, ''),
  39780. namespace: 'script',
  39781. };
  39782. });
  39783. build.onLoad({ filter: /.*/, namespace: 'script' }, ({ path }) => {
  39784. return scripts[path];
  39785. });
  39786. // html types: extract script contents -----------------------------------
  39787. build.onResolve({ filter: htmlTypesRE }, async ({ path, importer }) => {
  39788. const resolved = await resolve(path, importer);
  39789. if (!resolved)
  39790. return;
  39791. // It is possible for the scanner to scan html types in node_modules.
  39792. // If we can optimize this html type, skip it so it's handled by the
  39793. // bare import resolve, and recorded as optimization dep.
  39794. if (isInNodeModules(resolved) &&
  39795. isOptimizable(resolved, config.optimizeDeps))
  39796. return;
  39797. return {
  39798. path: resolved,
  39799. namespace: 'html',
  39800. };
  39801. });
  39802. // extract scripts inside HTML-like files and treat it as a js module
  39803. build.onLoad({ filter: htmlTypesRE, namespace: 'html' }, async ({ path }) => {
  39804. let raw = await fsp.readFile(path, 'utf-8');
  39805. // Avoid matching the content of the comment
  39806. raw = raw.replace(commentRE, '<!---->');
  39807. const isHtml = path.endsWith('.html');
  39808. scriptRE.lastIndex = 0;
  39809. let js = '';
  39810. let scriptId = 0;
  39811. let match;
  39812. while ((match = scriptRE.exec(raw))) {
  39813. const [, openTag, content] = match;
  39814. const typeMatch = openTag.match(typeRE);
  39815. const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
  39816. const langMatch = openTag.match(langRE);
  39817. const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
  39818. // skip non type module script
  39819. if (isHtml && type !== 'module') {
  39820. continue;
  39821. }
  39822. // skip type="application/ld+json" and other non-JS types
  39823. if (type &&
  39824. !(type.includes('javascript') ||
  39825. type.includes('ecmascript') ||
  39826. type === 'module')) {
  39827. continue;
  39828. }
  39829. let loader = 'js';
  39830. if (lang === 'ts' || lang === 'tsx' || lang === 'jsx') {
  39831. loader = lang;
  39832. }
  39833. else if (path.endsWith('.astro')) {
  39834. loader = 'ts';
  39835. }
  39836. const srcMatch = openTag.match(srcRE);
  39837. if (srcMatch) {
  39838. const src = srcMatch[1] || srcMatch[2] || srcMatch[3];
  39839. js += `import ${JSON.stringify(src)}\n`;
  39840. }
  39841. else if (content.trim()) {
  39842. // The reason why virtual modules are needed:
  39843. // 1. There can be module scripts (`<script context="module">` in Svelte and `<script>` in Vue)
  39844. // or local scripts (`<script>` in Svelte and `<script setup>` in Vue)
  39845. // 2. There can be multiple module scripts in html
  39846. // We need to handle these separately in case variable names are reused between them
  39847. // append imports in TS to prevent esbuild from removing them
  39848. // since they may be used in the template
  39849. const contents = content +
  39850. (loader.startsWith('ts') ? extractImportPaths(content) : '');
  39851. const key = `${path}?id=${scriptId++}`;
  39852. if (contents.includes('import.meta.glob')) {
  39853. scripts[key] = {
  39854. loader: 'js',
  39855. contents: await doTransformGlobImport(contents, path, loader),
  39856. pluginData: {
  39857. htmlType: { loader },
  39858. },
  39859. };
  39860. }
  39861. else {
  39862. scripts[key] = {
  39863. loader,
  39864. contents,
  39865. pluginData: {
  39866. htmlType: { loader },
  39867. },
  39868. };
  39869. }
  39870. const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
  39871. const contextMatch = openTag.match(contextRE);
  39872. const context = contextMatch &&
  39873. (contextMatch[1] || contextMatch[2] || contextMatch[3]);
  39874. // Especially for Svelte files, exports in <script context="module"> means module exports,
  39875. // exports in <script> means component props. To avoid having two same export name from the
  39876. // star exports, we need to ignore exports in <script>
  39877. if (path.endsWith('.svelte') && context !== 'module') {
  39878. js += `import ${virtualModulePath}\n`;
  39879. }
  39880. else {
  39881. js += `export * from ${virtualModulePath}\n`;
  39882. }
  39883. }
  39884. }
  39885. // This will trigger incorrectly if `export default` is contained
  39886. // anywhere in a string. Svelte and Astro files can't have
  39887. // `export default` as code so we know if it's encountered it's a
  39888. // false positive (e.g. contained in a string)
  39889. if (!path.endsWith('.vue') || !js.includes('export default')) {
  39890. js += '\nexport default {}';
  39891. }
  39892. return {
  39893. loader: 'js',
  39894. contents: js,
  39895. };
  39896. });
  39897. // bare imports: record and externalize ----------------------------------
  39898. build.onResolve({
  39899. // avoid matching windows volume
  39900. filter: /^[\w@][^:]/,
  39901. }, async ({ path: id, importer, pluginData }) => {
  39902. if (moduleListContains(exclude, id)) {
  39903. return externalUnlessEntry({ path: id });
  39904. }
  39905. if (depImports[id]) {
  39906. return externalUnlessEntry({ path: id });
  39907. }
  39908. const resolved = await resolve(id, importer, {
  39909. custom: {
  39910. depScan: { loader: pluginData?.htmlType?.loader },
  39911. },
  39912. });
  39913. if (resolved) {
  39914. if (shouldExternalizeDep(resolved, id)) {
  39915. return externalUnlessEntry({ path: id });
  39916. }
  39917. if (isInNodeModules(resolved) || include?.includes(id)) {
  39918. // dependency or forced included, externalize and stop crawling
  39919. if (isOptimizable(resolved, config.optimizeDeps)) {
  39920. depImports[id] = resolved;
  39921. }
  39922. return externalUnlessEntry({ path: id });
  39923. }
  39924. else if (isScannable(resolved)) {
  39925. const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
  39926. // linked package, keep crawling
  39927. return {
  39928. path: path$o.resolve(resolved),
  39929. namespace,
  39930. };
  39931. }
  39932. else {
  39933. return externalUnlessEntry({ path: id });
  39934. }
  39935. }
  39936. else {
  39937. missing[id] = normalizePath$3(importer);
  39938. }
  39939. });
  39940. // Externalized file types -----------------------------------------------
  39941. // these are done on raw ids using esbuild's native regex filter so it
  39942. // should be faster than doing it in the catch-all via js
  39943. // they are done after the bare import resolve because a package name
  39944. // may end with these extensions
  39945. // css
  39946. build.onResolve({ filter: CSS_LANGS_RE }, externalUnlessEntry);
  39947. // json & wasm
  39948. build.onResolve({ filter: /\.(json|json5|wasm)$/ }, externalUnlessEntry);
  39949. // known asset types
  39950. build.onResolve({
  39951. filter: new RegExp(`\\.(${KNOWN_ASSET_TYPES.join('|')})$`),
  39952. }, externalUnlessEntry);
  39953. // known vite query types: ?worker, ?raw
  39954. build.onResolve({ filter: SPECIAL_QUERY_RE }, ({ path }) => ({
  39955. path,
  39956. external: true,
  39957. }));
  39958. // catch all -------------------------------------------------------------
  39959. build.onResolve({
  39960. filter: /.*/,
  39961. }, async ({ path: id, importer, pluginData }) => {
  39962. // use vite resolver to support urls and omitted extensions
  39963. const resolved = await resolve(id, importer, {
  39964. custom: {
  39965. depScan: { loader: pluginData?.htmlType?.loader },
  39966. },
  39967. });
  39968. if (resolved) {
  39969. if (shouldExternalizeDep(resolved, id) || !isScannable(resolved)) {
  39970. return externalUnlessEntry({ path: id });
  39971. }
  39972. const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
  39973. return {
  39974. path: path$o.resolve(cleanUrl(resolved)),
  39975. namespace,
  39976. };
  39977. }
  39978. else {
  39979. // resolve failed... probably unsupported type
  39980. return externalUnlessEntry({ path: id });
  39981. }
  39982. });
  39983. // for jsx/tsx, we need to access the content and check for
  39984. // presence of import.meta.glob, since it results in import relationships
  39985. // but isn't crawled by esbuild.
  39986. build.onLoad({ filter: JS_TYPES_RE }, async ({ path: id }) => {
  39987. let ext = path$o.extname(id).slice(1);
  39988. if (ext === 'mjs')
  39989. ext = 'js';
  39990. let contents = await fsp.readFile(id, 'utf-8');
  39991. if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) {
  39992. contents = config.esbuild.jsxInject + `\n` + contents;
  39993. }
  39994. const loader = config.optimizeDeps?.esbuildOptions?.loader?.[`.${ext}`] ||
  39995. ext;
  39996. if (contents.includes('import.meta.glob')) {
  39997. return {
  39998. loader: 'js',
  39999. contents: await doTransformGlobImport(contents, id, loader),
  40000. };
  40001. }
  40002. return {
  40003. loader,
  40004. contents,
  40005. };
  40006. });
  40007. },
  40008. };
  40009. }
  40010. /**
  40011. * when using TS + (Vue + `<script setup>`) or Svelte, imports may seem
  40012. * unused to esbuild and dropped in the build output, which prevents
  40013. * esbuild from crawling further.
  40014. * the solution is to add `import 'x'` for every source to force
  40015. * esbuild to keep crawling due to potential side effects.
  40016. */
  40017. function extractImportPaths(code) {
  40018. // empty singleline & multiline comments to avoid matching comments
  40019. code = code
  40020. .replace(multilineCommentsRE$1, '/* */')
  40021. .replace(singlelineCommentsRE$1, '');
  40022. let js = '';
  40023. let m;
  40024. importsRE.lastIndex = 0;
  40025. while ((m = importsRE.exec(code)) != null) {
  40026. js += `\nimport ${m[1]}`;
  40027. }
  40028. return js;
  40029. }
  40030. function shouldExternalizeDep(resolvedId, rawId) {
  40031. // not a valid file path
  40032. if (!path$o.isAbsolute(resolvedId)) {
  40033. return true;
  40034. }
  40035. // virtual id
  40036. if (resolvedId === rawId || resolvedId.includes('\0')) {
  40037. return true;
  40038. }
  40039. return false;
  40040. }
  40041. function isScannable(id) {
  40042. return JS_TYPES_RE.test(id) || htmlTypesRE.test(id);
  40043. }
  40044. const debug$8 = createDebugger('vite:deps');
  40045. /**
  40046. * The amount to wait for requests to register newly found dependencies before triggering
  40047. * a re-bundle + page reload
  40048. */
  40049. const debounceMs = 100;
  40050. const depsOptimizerMap = new WeakMap();
  40051. const devSsrDepsOptimizerMap = new WeakMap();
  40052. function getDepsOptimizer(config, ssr) {
  40053. // Workers compilation shares the DepsOptimizer from the main build
  40054. const isDevSsr = ssr && config.command !== 'build';
  40055. return (isDevSsr ? devSsrDepsOptimizerMap : depsOptimizerMap).get(config.mainConfig || config);
  40056. }
  40057. async function initDepsOptimizer(config, server) {
  40058. // Non Dev SSR Optimizer
  40059. const ssr = config.command === 'build' && !!config.build.ssr;
  40060. if (!getDepsOptimizer(config, ssr)) {
  40061. await createDepsOptimizer(config, server);
  40062. }
  40063. }
  40064. let creatingDevSsrOptimizer;
  40065. async function initDevSsrDepsOptimizer(config, server) {
  40066. if (getDepsOptimizer(config, true)) {
  40067. // ssr
  40068. return;
  40069. }
  40070. if (creatingDevSsrOptimizer) {
  40071. return creatingDevSsrOptimizer;
  40072. }
  40073. creatingDevSsrOptimizer = (async function () {
  40074. // Important: scanning needs to be done before starting the SSR dev optimizer
  40075. // If ssrLoadModule is called before server.listen(), the main deps optimizer
  40076. // will not be yet created
  40077. const ssr = false;
  40078. if (!getDepsOptimizer(config, ssr)) {
  40079. await initDepsOptimizer(config, server);
  40080. }
  40081. await getDepsOptimizer(config, ssr).scanProcessing;
  40082. await createDevSsrDepsOptimizer(config);
  40083. creatingDevSsrOptimizer = undefined;
  40084. })();
  40085. return await creatingDevSsrOptimizer;
  40086. }
  40087. async function createDepsOptimizer(config, server) {
  40088. const { logger } = config;
  40089. const isBuild = config.command === 'build';
  40090. const ssr = isBuild && !!config.build.ssr; // safe as Dev SSR don't use this optimizer
  40091. const sessionTimestamp = Date.now().toString();
  40092. const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr);
  40093. let debounceProcessingHandle;
  40094. let closed = false;
  40095. let metadata = cachedMetadata || initDepsOptimizerMetadata(config, ssr, sessionTimestamp);
  40096. const depsOptimizer = {
  40097. metadata,
  40098. registerMissingImport,
  40099. run: () => debouncedProcessing(0),
  40100. isOptimizedDepFile: createIsOptimizedDepFile(config),
  40101. isOptimizedDepUrl: createIsOptimizedDepUrl(config),
  40102. getOptimizedDepId: (depInfo) => isBuild ? depInfo.file : `${depInfo.file}?v=${depInfo.browserHash}`,
  40103. registerWorkersSource,
  40104. delayDepsOptimizerUntil,
  40105. resetRegisteredIds,
  40106. ensureFirstRun,
  40107. close,
  40108. options: getDepOptimizationConfig(config, ssr),
  40109. };
  40110. depsOptimizerMap.set(config, depsOptimizer);
  40111. let newDepsDiscovered = false;
  40112. let newDepsToLog = [];
  40113. let newDepsToLogHandle;
  40114. const logNewlyDiscoveredDeps = () => {
  40115. if (newDepsToLog.length) {
  40116. config.logger.info(colors$1.green(`✨ new dependencies optimized: ${depsLogString(newDepsToLog)}`), {
  40117. timestamp: true,
  40118. });
  40119. newDepsToLog = [];
  40120. }
  40121. };
  40122. let depOptimizationProcessing = newDepOptimizationProcessing();
  40123. let depOptimizationProcessingQueue = [];
  40124. const resolveEnqueuedProcessingPromises = () => {
  40125. // Resolve all the processings (including the ones which were delayed)
  40126. for (const processing of depOptimizationProcessingQueue) {
  40127. processing.resolve();
  40128. }
  40129. depOptimizationProcessingQueue = [];
  40130. };
  40131. let enqueuedRerun;
  40132. let currentlyProcessing = false;
  40133. let firstRunCalled = !!cachedMetadata;
  40134. // During build, we wait for every module to be scanned before resolving
  40135. // optimized deps loading for rollup on each rebuild. It will be recreated
  40136. // after each buildStart.
  40137. // During dev, if this is a cold run, we wait for static imports discovered
  40138. // from the first request before resolving to minimize full page reloads.
  40139. // On warm start or after the first optimization is run, we use a simpler
  40140. // debounce strategy each time a new dep is discovered.
  40141. let crawlEndFinder;
  40142. if (isBuild || !cachedMetadata) {
  40143. crawlEndFinder = setupOnCrawlEnd(onCrawlEnd);
  40144. }
  40145. let optimizationResult;
  40146. let discover;
  40147. async function close() {
  40148. closed = true;
  40149. crawlEndFinder?.cancel();
  40150. await Promise.allSettled([
  40151. discover?.cancel(),
  40152. depsOptimizer.scanProcessing,
  40153. optimizationResult?.cancel(),
  40154. ]);
  40155. }
  40156. if (!cachedMetadata) {
  40157. // Enter processing state until crawl of static imports ends
  40158. currentlyProcessing = true;
  40159. // Initialize discovered deps with manually added optimizeDeps.include info
  40160. const deps = {};
  40161. await addManuallyIncludedOptimizeDeps(deps, config, ssr);
  40162. const discovered = toDiscoveredDependencies(config, deps, ssr, sessionTimestamp);
  40163. for (const depInfo of Object.values(discovered)) {
  40164. addOptimizedDepInfo(metadata, 'discovered', {
  40165. ...depInfo,
  40166. processing: depOptimizationProcessing.promise,
  40167. });
  40168. newDepsDiscovered = true;
  40169. }
  40170. if (config.optimizeDeps.noDiscovery) {
  40171. // We don't need to scan for dependencies or wait for the static crawl to end
  40172. // Run the first optimization run immediately
  40173. runOptimizer();
  40174. }
  40175. else if (!isBuild) {
  40176. // Important, the scanner is dev only
  40177. depsOptimizer.scanProcessing = new Promise((resolve) => {
  40178. (async () => {
  40179. try {
  40180. debug$8?.(colors$1.green(`scanning for dependencies...`));
  40181. discover = discoverProjectDependencies(config);
  40182. const deps = await discover.result;
  40183. discover = undefined;
  40184. // Add these dependencies to the discovered list, as these are currently
  40185. // used by the preAliasPlugin to support aliased and optimized deps.
  40186. // This is also used by the CJS externalization heuristics in legacy mode
  40187. for (const id of Object.keys(deps)) {
  40188. if (!metadata.discovered[id]) {
  40189. addMissingDep(id, deps[id]);
  40190. }
  40191. }
  40192. const knownDeps = prepareKnownDeps();
  40193. // For dev, we run the scanner and the first optimization
  40194. // run on the background, but we wait until crawling has ended
  40195. // to decide if we send this result to the browser or we need to
  40196. // do another optimize step
  40197. optimizationResult = runOptimizeDeps(config, knownDeps);
  40198. }
  40199. catch (e) {
  40200. logger.error(e.stack || e.message);
  40201. }
  40202. finally {
  40203. resolve();
  40204. depsOptimizer.scanProcessing = undefined;
  40205. }
  40206. })();
  40207. });
  40208. }
  40209. }
  40210. function startNextDiscoveredBatch() {
  40211. newDepsDiscovered = false;
  40212. // Add the current depOptimizationProcessing to the queue, these
  40213. // promises are going to be resolved once a rerun is committed
  40214. depOptimizationProcessingQueue.push(depOptimizationProcessing);
  40215. // Create a new promise for the next rerun, discovered missing
  40216. // dependencies will be assigned this promise from this point
  40217. depOptimizationProcessing = newDepOptimizationProcessing();
  40218. }
  40219. function prepareKnownDeps() {
  40220. const knownDeps = {};
  40221. // Clone optimized info objects, fileHash, browserHash may be changed for them
  40222. for (const dep of Object.keys(metadata.optimized)) {
  40223. knownDeps[dep] = { ...metadata.optimized[dep] };
  40224. }
  40225. for (const dep of Object.keys(metadata.discovered)) {
  40226. // Clone the discovered info discarding its processing promise
  40227. const { processing, ...info } = metadata.discovered[dep];
  40228. knownDeps[dep] = info;
  40229. }
  40230. return knownDeps;
  40231. }
  40232. async function runOptimizer(preRunResult) {
  40233. // a successful completion of the optimizeDeps rerun will end up
  40234. // creating new bundled version of all current and discovered deps
  40235. // in the cache dir and a new metadata info object assigned
  40236. // to _metadata. A fullReload is only issued if the previous bundled
  40237. // dependencies have changed.
  40238. // if the rerun fails, _metadata remains untouched, current discovered
  40239. // deps are cleaned, and a fullReload is issued
  40240. // All deps, previous known and newly discovered are rebundled,
  40241. // respect insertion order to keep the metadata file stable
  40242. const isRerun = firstRunCalled;
  40243. firstRunCalled = true;
  40244. // Ensure that rerun is called sequentially
  40245. enqueuedRerun = undefined;
  40246. // Ensure that a rerun will not be issued for current discovered deps
  40247. if (debounceProcessingHandle)
  40248. clearTimeout(debounceProcessingHandle);
  40249. if (closed || Object.keys(metadata.discovered).length === 0) {
  40250. currentlyProcessing = false;
  40251. return;
  40252. }
  40253. currentlyProcessing = true;
  40254. try {
  40255. let processingResult;
  40256. if (preRunResult) {
  40257. processingResult = preRunResult;
  40258. }
  40259. else {
  40260. const knownDeps = prepareKnownDeps();
  40261. startNextDiscoveredBatch();
  40262. optimizationResult = runOptimizeDeps(config, knownDeps);
  40263. processingResult = await optimizationResult.result;
  40264. optimizationResult = undefined;
  40265. }
  40266. if (closed) {
  40267. currentlyProcessing = false;
  40268. processingResult.cancel();
  40269. resolveEnqueuedProcessingPromises();
  40270. return;
  40271. }
  40272. const newData = processingResult.metadata;
  40273. const needsInteropMismatch = findInteropMismatches(metadata.discovered, newData.optimized);
  40274. // After a re-optimization, if the internal bundled chunks change a full page reload
  40275. // is required. If the files are stable, we can avoid the reload that is expensive
  40276. // for large applications. Comparing their fileHash we can find out if it is safe to
  40277. // keep the current browser state.
  40278. const needsReload = needsInteropMismatch.length > 0 ||
  40279. metadata.hash !== newData.hash ||
  40280. Object.keys(metadata.optimized).some((dep) => {
  40281. return (metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash);
  40282. });
  40283. const commitProcessing = async () => {
  40284. await processingResult.commit();
  40285. // While optimizeDeps is running, new missing deps may be discovered,
  40286. // in which case they will keep being added to metadata.discovered
  40287. for (const id in metadata.discovered) {
  40288. if (!newData.optimized[id]) {
  40289. addOptimizedDepInfo(newData, 'discovered', metadata.discovered[id]);
  40290. }
  40291. }
  40292. // If we don't reload the page, we need to keep browserHash stable
  40293. if (!needsReload) {
  40294. newData.browserHash = metadata.browserHash;
  40295. for (const dep in newData.chunks) {
  40296. newData.chunks[dep].browserHash = metadata.browserHash;
  40297. }
  40298. for (const dep in newData.optimized) {
  40299. newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
  40300. }
  40301. }
  40302. // Commit hash and needsInterop changes to the discovered deps info
  40303. // object. Allow for code to await for the discovered processing promise
  40304. // and use the information in the same object
  40305. for (const o in newData.optimized) {
  40306. const discovered = metadata.discovered[o];
  40307. if (discovered) {
  40308. const optimized = newData.optimized[o];
  40309. discovered.browserHash = optimized.browserHash;
  40310. discovered.fileHash = optimized.fileHash;
  40311. discovered.needsInterop = optimized.needsInterop;
  40312. discovered.processing = undefined;
  40313. }
  40314. }
  40315. if (isRerun) {
  40316. newDepsToLog.push(...Object.keys(newData.optimized).filter((dep) => !metadata.optimized[dep]));
  40317. }
  40318. metadata = depsOptimizer.metadata = newData;
  40319. resolveEnqueuedProcessingPromises();
  40320. };
  40321. if (!needsReload) {
  40322. await commitProcessing();
  40323. if (!debug$8) {
  40324. if (newDepsToLogHandle)
  40325. clearTimeout(newDepsToLogHandle);
  40326. newDepsToLogHandle = setTimeout(() => {
  40327. newDepsToLogHandle = undefined;
  40328. logNewlyDiscoveredDeps();
  40329. }, 2 * debounceMs);
  40330. }
  40331. else {
  40332. debug$8(colors$1.green(`✨ ${!isRerun
  40333. ? `dependencies optimized`
  40334. : `optimized dependencies unchanged`}`));
  40335. }
  40336. }
  40337. else {
  40338. if (newDepsDiscovered) {
  40339. // There are newly discovered deps, and another rerun is about to be
  40340. // executed. Avoid the current full reload discarding this rerun result
  40341. // We don't resolve the processing promise, as they will be resolved
  40342. // once a rerun is committed
  40343. processingResult.cancel();
  40344. debug$8?.(colors$1.green(`✨ delaying reload as new dependencies have been found...`));
  40345. }
  40346. else {
  40347. await commitProcessing();
  40348. if (!debug$8) {
  40349. if (newDepsToLogHandle)
  40350. clearTimeout(newDepsToLogHandle);
  40351. newDepsToLogHandle = undefined;
  40352. logNewlyDiscoveredDeps();
  40353. }
  40354. logger.info(colors$1.green(`✨ optimized dependencies changed. reloading`), {
  40355. timestamp: true,
  40356. });
  40357. if (needsInteropMismatch.length > 0) {
  40358. config.logger.warn(`Mixed ESM and CJS detected in ${colors$1.yellow(needsInteropMismatch.join(', '))}, add ${needsInteropMismatch.length === 1 ? 'it' : 'them'} to optimizeDeps.needsInterop to speed up cold start`, {
  40359. timestamp: true,
  40360. });
  40361. }
  40362. fullReload();
  40363. }
  40364. }
  40365. }
  40366. catch (e) {
  40367. logger.error(colors$1.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true, error: e });
  40368. resolveEnqueuedProcessingPromises();
  40369. // Reset missing deps, let the server rediscover the dependencies
  40370. metadata.discovered = {};
  40371. }
  40372. currentlyProcessing = false;
  40373. // @ts-expect-error `enqueuedRerun` could exist because `debouncedProcessing` may run while awaited
  40374. enqueuedRerun?.();
  40375. }
  40376. function fullReload() {
  40377. if (server) {
  40378. // Cached transform results have stale imports (resolved to
  40379. // old locations) so they need to be invalidated before the page is
  40380. // reloaded.
  40381. server.moduleGraph.invalidateAll();
  40382. server.ws.send({
  40383. type: 'full-reload',
  40384. path: '*',
  40385. });
  40386. }
  40387. }
  40388. async function rerun() {
  40389. // debounce time to wait for new missing deps finished, issue a new
  40390. // optimization of deps (both old and newly found) once the previous
  40391. // optimizeDeps processing is finished
  40392. const deps = Object.keys(metadata.discovered);
  40393. const depsString = depsLogString(deps);
  40394. debug$8?.(colors$1.green(`new dependencies found: ${depsString}`));
  40395. runOptimizer();
  40396. }
  40397. function getDiscoveredBrowserHash(hash, deps, missing) {
  40398. return getHash(hash + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp);
  40399. }
  40400. function registerMissingImport(id, resolved) {
  40401. const optimized = metadata.optimized[id];
  40402. if (optimized) {
  40403. return optimized;
  40404. }
  40405. const chunk = metadata.chunks[id];
  40406. if (chunk) {
  40407. return chunk;
  40408. }
  40409. let missing = metadata.discovered[id];
  40410. if (missing) {
  40411. // We are already discover this dependency
  40412. // It will be processed in the next rerun call
  40413. return missing;
  40414. }
  40415. missing = addMissingDep(id, resolved);
  40416. // Until the first optimize run is called, avoid triggering processing
  40417. // We'll wait until the user codebase is eagerly processed by Vite so
  40418. // we can get a list of every missing dependency before giving to the
  40419. // browser a dependency that may be outdated, thus avoiding full page reloads
  40420. if (!crawlEndFinder) {
  40421. if (isBuild) {
  40422. logger.error('Vite Internal Error: Missing dependency found after crawling ended');
  40423. }
  40424. // Debounced rerun, let other missing dependencies be discovered before
  40425. // the running next optimizeDeps
  40426. debouncedProcessing();
  40427. }
  40428. // Return the path for the optimized bundle, this path is known before
  40429. // esbuild is run to generate the pre-bundle
  40430. return missing;
  40431. }
  40432. function addMissingDep(id, resolved) {
  40433. newDepsDiscovered = true;
  40434. return addOptimizedDepInfo(metadata, 'discovered', {
  40435. id,
  40436. file: getOptimizedDepPath(id, config, ssr),
  40437. src: resolved,
  40438. // Adding a browserHash to this missing dependency that is unique to
  40439. // the current state of known + missing deps. If its optimizeDeps run
  40440. // doesn't alter the bundled files of previous known dependencies,
  40441. // we don't need a full reload and this browserHash will be kept
  40442. browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
  40443. // loading of this pre-bundled dep needs to await for its processing
  40444. // promise to be resolved
  40445. processing: depOptimizationProcessing.promise,
  40446. exportsData: extractExportsData(resolved, config, ssr),
  40447. });
  40448. }
  40449. function debouncedProcessing(timeout = debounceMs) {
  40450. if (!newDepsDiscovered) {
  40451. return;
  40452. }
  40453. // Debounced rerun, let other missing dependencies be discovered before
  40454. // the running next optimizeDeps
  40455. enqueuedRerun = undefined;
  40456. if (debounceProcessingHandle)
  40457. clearTimeout(debounceProcessingHandle);
  40458. if (newDepsToLogHandle)
  40459. clearTimeout(newDepsToLogHandle);
  40460. newDepsToLogHandle = undefined;
  40461. debounceProcessingHandle = setTimeout(() => {
  40462. debounceProcessingHandle = undefined;
  40463. enqueuedRerun = rerun;
  40464. if (!currentlyProcessing) {
  40465. enqueuedRerun();
  40466. }
  40467. }, timeout);
  40468. }
  40469. // During dev, onCrawlEnd is called once when the server starts and all static
  40470. // imports after the first request have been crawled (dynamic imports may also
  40471. // be crawled if the browser requests them right away).
  40472. // During build, onCrawlEnd will be called once after each buildStart (so in
  40473. // watch mode it will be called after each rebuild has processed every module).
  40474. // All modules are transformed first in this case (both static and dynamic).
  40475. async function onCrawlEnd() {
  40476. // On build time, a missing dep appearing after onCrawlEnd is an internal error
  40477. // On dev, switch after this point to a simple debounce strategy
  40478. crawlEndFinder = undefined;
  40479. debug$8?.(colors$1.green(`✨ static imports crawl ended`));
  40480. if (closed) {
  40481. return;
  40482. }
  40483. const crawlDeps = Object.keys(metadata.discovered);
  40484. // Await for the scan+optimize step running in the background
  40485. // It normally should be over by the time crawling of user code ended
  40486. await depsOptimizer.scanProcessing;
  40487. if (!isBuild && optimizationResult) {
  40488. const result = await optimizationResult.result;
  40489. optimizationResult = undefined;
  40490. currentlyProcessing = false;
  40491. const scanDeps = Object.keys(result.metadata.optimized);
  40492. if (scanDeps.length === 0 && crawlDeps.length === 0) {
  40493. debug$8?.(colors$1.green(`✨ no dependencies found by the scanner or crawling static imports`));
  40494. result.cancel();
  40495. firstRunCalled = true;
  40496. return;
  40497. }
  40498. const needsInteropMismatch = findInteropMismatches(metadata.discovered, result.metadata.optimized);
  40499. const scannerMissedDeps = crawlDeps.some((dep) => !scanDeps.includes(dep));
  40500. const outdatedResult = needsInteropMismatch.length > 0 || scannerMissedDeps;
  40501. if (outdatedResult) {
  40502. // Drop this scan result, and perform a new optimization to avoid a full reload
  40503. result.cancel();
  40504. // Add deps found by the scanner to the discovered deps while crawling
  40505. for (const dep of scanDeps) {
  40506. if (!crawlDeps.includes(dep)) {
  40507. addMissingDep(dep, result.metadata.optimized[dep].src);
  40508. }
  40509. }
  40510. if (scannerMissedDeps) {
  40511. debug$8?.(colors$1.yellow(`✨ new dependencies were found while crawling that weren't detected by the scanner`));
  40512. }
  40513. debug$8?.(colors$1.green(`✨ re-running optimizer`));
  40514. debouncedProcessing(0);
  40515. }
  40516. else {
  40517. debug$8?.(colors$1.green(`✨ using post-scan optimizer result, the scanner found every used dependency`));
  40518. startNextDiscoveredBatch();
  40519. runOptimizer(result);
  40520. }
  40521. }
  40522. else {
  40523. currentlyProcessing = false;
  40524. if (crawlDeps.length === 0) {
  40525. debug$8?.(colors$1.green(`✨ no dependencies found while crawling the static imports`));
  40526. firstRunCalled = true;
  40527. }
  40528. else {
  40529. // queue the first optimizer run
  40530. debouncedProcessing(0);
  40531. }
  40532. }
  40533. }
  40534. // Called during buildStart at build time, when build --watch is used.
  40535. function resetRegisteredIds() {
  40536. crawlEndFinder?.cancel();
  40537. crawlEndFinder = setupOnCrawlEnd(onCrawlEnd);
  40538. }
  40539. function registerWorkersSource(id) {
  40540. crawlEndFinder?.registerWorkersSource(id);
  40541. }
  40542. function delayDepsOptimizerUntil(id, done) {
  40543. if (crawlEndFinder && !depsOptimizer.isOptimizedDepFile(id)) {
  40544. crawlEndFinder.delayDepsOptimizerUntil(id, done);
  40545. }
  40546. }
  40547. function ensureFirstRun() {
  40548. crawlEndFinder?.ensureFirstRun();
  40549. }
  40550. }
  40551. const callCrawlEndIfIdleAfterMs = 50;
  40552. function setupOnCrawlEnd(onCrawlEnd) {
  40553. const registeredIds = new Set();
  40554. const seenIds = new Set();
  40555. const workersSources = new Set();
  40556. let timeoutHandle;
  40557. let cancelled = false;
  40558. function cancel() {
  40559. cancelled = true;
  40560. }
  40561. let crawlEndCalled = false;
  40562. function callOnCrawlEnd() {
  40563. if (!cancelled && !crawlEndCalled) {
  40564. crawlEndCalled = true;
  40565. onCrawlEnd();
  40566. }
  40567. }
  40568. // If all the inputs are dependencies, we aren't going to get any
  40569. // delayDepsOptimizerUntil(id) calls. We need to guard against this
  40570. // by forcing a rerun if no deps have been registered
  40571. let firstRunEnsured = false;
  40572. function ensureFirstRun() {
  40573. if (!firstRunEnsured && seenIds.size === 0) {
  40574. setTimeout(() => {
  40575. if (seenIds.size === 0) {
  40576. callOnCrawlEnd();
  40577. }
  40578. }, 200);
  40579. }
  40580. firstRunEnsured = true;
  40581. }
  40582. function registerWorkersSource(id) {
  40583. workersSources.add(id);
  40584. // Avoid waiting for this id, as it may be blocked by the rollup
  40585. // bundling process of the worker that also depends on the optimizer
  40586. registeredIds.delete(id);
  40587. checkIfCrawlEndAfterTimeout();
  40588. }
  40589. function delayDepsOptimizerUntil(id, done) {
  40590. if (!seenIds.has(id)) {
  40591. seenIds.add(id);
  40592. if (!workersSources.has(id)) {
  40593. registeredIds.add(id);
  40594. done()
  40595. .catch(() => { })
  40596. .finally(() => markIdAsDone(id));
  40597. }
  40598. }
  40599. }
  40600. function markIdAsDone(id) {
  40601. registeredIds.delete(id);
  40602. checkIfCrawlEndAfterTimeout();
  40603. }
  40604. function checkIfCrawlEndAfterTimeout() {
  40605. if (cancelled || registeredIds.size > 0)
  40606. return;
  40607. if (timeoutHandle)
  40608. clearTimeout(timeoutHandle);
  40609. timeoutHandle = setTimeout(callOnCrawlEndWhenIdle, callCrawlEndIfIdleAfterMs);
  40610. }
  40611. async function callOnCrawlEndWhenIdle() {
  40612. if (cancelled || registeredIds.size > 0)
  40613. return;
  40614. callOnCrawlEnd();
  40615. }
  40616. return {
  40617. ensureFirstRun,
  40618. registerWorkersSource,
  40619. delayDepsOptimizerUntil,
  40620. cancel,
  40621. };
  40622. }
  40623. async function createDevSsrDepsOptimizer(config) {
  40624. const metadata = await optimizeServerSsrDeps(config);
  40625. const depsOptimizer = {
  40626. metadata,
  40627. isOptimizedDepFile: createIsOptimizedDepFile(config),
  40628. isOptimizedDepUrl: createIsOptimizedDepUrl(config),
  40629. getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
  40630. registerMissingImport: () => {
  40631. throw new Error('Vite Internal Error: registerMissingImport is not supported in dev SSR');
  40632. },
  40633. // noop, there is no scanning during dev SSR
  40634. // the optimizer blocks the server start
  40635. run: () => { },
  40636. registerWorkersSource: (id) => { },
  40637. delayDepsOptimizerUntil: (id, done) => { },
  40638. resetRegisteredIds: () => { },
  40639. ensureFirstRun: () => { },
  40640. close: async () => { },
  40641. options: config.ssr.optimizeDeps,
  40642. };
  40643. devSsrDepsOptimizerMap.set(config, depsOptimizer);
  40644. }
  40645. function findInteropMismatches(discovered, optimized) {
  40646. const needsInteropMismatch = [];
  40647. for (const dep in discovered) {
  40648. const discoveredDepInfo = discovered[dep];
  40649. const depInfo = optimized[dep];
  40650. if (depInfo) {
  40651. if (discoveredDepInfo.needsInterop !== undefined &&
  40652. depInfo.needsInterop !== discoveredDepInfo.needsInterop) {
  40653. // This only happens when a discovered dependency has mixed ESM and CJS syntax
  40654. // and it hasn't been manually added to optimizeDeps.needsInterop
  40655. needsInteropMismatch.push(dep);
  40656. debug$8?.(colors$1.cyan(`✨ needsInterop mismatch detected for ${dep}`));
  40657. }
  40658. }
  40659. }
  40660. return needsInteropMismatch;
  40661. }
  40662. const debug$7 = createDebugger('vite:deps');
  40663. const jsExtensionRE = /\.js$/i;
  40664. const jsMapExtensionRE = /\.js\.map$/i;
  40665. /**
  40666. * Scan and optimize dependencies within a project.
  40667. * Used by Vite CLI when running `vite optimize`.
  40668. */
  40669. async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
  40670. const log = asCommand ? config.logger.info : debug$7;
  40671. const ssr = config.command === 'build' && !!config.build.ssr;
  40672. const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr, force, asCommand);
  40673. if (cachedMetadata) {
  40674. return cachedMetadata;
  40675. }
  40676. const deps = await discoverProjectDependencies(config).result;
  40677. const depsString = depsLogString(Object.keys(deps));
  40678. log?.(colors$1.green(`Optimizing dependencies:\n ${depsString}`));
  40679. await addManuallyIncludedOptimizeDeps(deps, config, ssr);
  40680. const depsInfo = toDiscoveredDependencies(config, deps, ssr);
  40681. const result = await runOptimizeDeps(config, depsInfo).result;
  40682. await result.commit();
  40683. return result.metadata;
  40684. }
  40685. async function optimizeServerSsrDeps(config) {
  40686. const ssr = true;
  40687. const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr, config.optimizeDeps.force, false);
  40688. if (cachedMetadata) {
  40689. return cachedMetadata;
  40690. }
  40691. let alsoInclude;
  40692. let noExternalFilter;
  40693. const { exclude } = getDepOptimizationConfig(config, ssr);
  40694. const noExternal = config.ssr?.noExternal;
  40695. if (noExternal) {
  40696. alsoInclude = arraify(noExternal).filter((ne) => typeof ne === 'string');
  40697. noExternalFilter =
  40698. noExternal === true
  40699. ? (dep) => true
  40700. : createFilter$1(undefined, exclude, {
  40701. resolve: false,
  40702. });
  40703. }
  40704. const deps = {};
  40705. await addManuallyIncludedOptimizeDeps(deps, config, ssr, alsoInclude, noExternalFilter);
  40706. const depsInfo = toDiscoveredDependencies(config, deps, true);
  40707. const result = await runOptimizeDeps(config, depsInfo, true).result;
  40708. await result.commit();
  40709. return result.metadata;
  40710. }
  40711. function initDepsOptimizerMetadata(config, ssr, timestamp) {
  40712. const hash = getDepHash(config, ssr);
  40713. return {
  40714. hash,
  40715. browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
  40716. optimized: {},
  40717. chunks: {},
  40718. discovered: {},
  40719. depInfoList: [],
  40720. };
  40721. }
  40722. function addOptimizedDepInfo(metadata, type, depInfo) {
  40723. metadata[type][depInfo.id] = depInfo;
  40724. metadata.depInfoList.push(depInfo);
  40725. return depInfo;
  40726. }
  40727. let firstLoadCachedDepOptimizationMetadata = true;
  40728. /**
  40729. * Creates the initial dep optimization metadata, loading it from the deps cache
  40730. * if it exists and pre-bundling isn't forced
  40731. */
  40732. async function loadCachedDepOptimizationMetadata(config, ssr, force = config.optimizeDeps.force, asCommand = false) {
  40733. const log = asCommand ? config.logger.info : debug$7;
  40734. if (firstLoadCachedDepOptimizationMetadata) {
  40735. firstLoadCachedDepOptimizationMetadata = false;
  40736. // Fire up a clean up of stale processing deps dirs if older process exited early
  40737. setTimeout(() => cleanupDepsCacheStaleDirs(config), 0);
  40738. }
  40739. const depsCacheDir = getDepsCacheDir(config, ssr);
  40740. if (!force) {
  40741. let cachedMetadata;
  40742. try {
  40743. const cachedMetadataPath = path$o.join(depsCacheDir, '_metadata.json');
  40744. cachedMetadata = parseDepsOptimizerMetadata(await fsp.readFile(cachedMetadataPath, 'utf-8'), depsCacheDir);
  40745. }
  40746. catch (e) { }
  40747. // hash is consistent, no need to re-bundle
  40748. if (cachedMetadata && cachedMetadata.hash === getDepHash(config, ssr)) {
  40749. log?.('Hash is consistent. Skipping. Use --force to override.');
  40750. // Nothing to commit or cancel as we are using the cache, we only
  40751. // need to resolve the processing promise so requests can move on
  40752. return cachedMetadata;
  40753. }
  40754. }
  40755. else {
  40756. config.logger.info('Forced re-optimization of dependencies');
  40757. }
  40758. // Start with a fresh cache
  40759. await fsp.rm(depsCacheDir, { recursive: true, force: true });
  40760. }
  40761. /**
  40762. * Initial optimizeDeps at server start. Perform a fast scan using esbuild to
  40763. * find deps to pre-bundle and include user hard-coded dependencies
  40764. */
  40765. function discoverProjectDependencies(config) {
  40766. const { cancel, result } = scanImports(config);
  40767. return {
  40768. cancel,
  40769. result: result.then(({ deps, missing }) => {
  40770. const missingIds = Object.keys(missing);
  40771. if (missingIds.length) {
  40772. throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds
  40773. .map((id) => `${colors$1.cyan(id)} ${colors$1.white(colors$1.dim(`(imported by ${missing[id]})`))}`)
  40774. .join(`\n `)}\n\nAre they installed?`);
  40775. }
  40776. return deps;
  40777. }),
  40778. };
  40779. }
  40780. function toDiscoveredDependencies(config, deps, ssr, timestamp) {
  40781. const browserHash = getOptimizedBrowserHash(getDepHash(config, ssr), deps, timestamp);
  40782. const discovered = {};
  40783. for (const id in deps) {
  40784. const src = deps[id];
  40785. discovered[id] = {
  40786. id,
  40787. file: getOptimizedDepPath(id, config, ssr),
  40788. src,
  40789. browserHash: browserHash,
  40790. exportsData: extractExportsData(src, config, ssr),
  40791. };
  40792. }
  40793. return discovered;
  40794. }
  40795. function depsLogString(qualifiedIds) {
  40796. return colors$1.yellow(qualifiedIds.join(`, `));
  40797. }
  40798. /**
  40799. * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
  40800. * the metadata and start the server without waiting for the optimizeDeps processing to be completed
  40801. */
  40802. function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command === 'build' &&
  40803. !!resolvedConfig.build.ssr) {
  40804. const optimizerContext = { cancelled: false };
  40805. const config = {
  40806. ...resolvedConfig,
  40807. command: 'build',
  40808. };
  40809. const depsCacheDir = getDepsCacheDir(resolvedConfig, ssr);
  40810. const processingCacheDir = getProcessingDepsCacheDir(resolvedConfig, ssr);
  40811. // Create a temporal directory so we don't need to delete optimized deps
  40812. // until they have been processed. This also avoids leaving the deps cache
  40813. // directory in a corrupted state if there is an error
  40814. fs$l.mkdirSync(processingCacheDir, { recursive: true });
  40815. // a hint for Node.js
  40816. // all files in the cache directory should be recognized as ES modules
  40817. fs$l.writeFileSync(path$o.resolve(processingCacheDir, 'package.json'), `{\n "type": "module"\n}\n`);
  40818. const metadata = initDepsOptimizerMetadata(config, ssr);
  40819. metadata.browserHash = getOptimizedBrowserHash(metadata.hash, depsFromOptimizedDepInfo(depsInfo));
  40820. // We prebundle dependencies with esbuild and cache them, but there is no need
  40821. // to wait here. Code that needs to access the cached deps needs to await
  40822. // the optimizedDepInfo.processing promise for each dep
  40823. const qualifiedIds = Object.keys(depsInfo);
  40824. let cleaned = false;
  40825. let committed = false;
  40826. const cleanUp = () => {
  40827. // If commit was already called, ignore the clean up even if a cancel was requested
  40828. // This minimizes the chances of leaving the deps cache in a corrupted state
  40829. if (!cleaned && !committed) {
  40830. cleaned = true;
  40831. // No need to wait, we can clean up in the background because temp folders
  40832. // are unique per run
  40833. fsp.rm(processingCacheDir, { recursive: true, force: true }).catch(() => {
  40834. // Ignore errors
  40835. });
  40836. }
  40837. };
  40838. const succesfulResult = {
  40839. metadata,
  40840. cancel: cleanUp,
  40841. commit: async () => {
  40842. if (cleaned) {
  40843. throw new Error('Can not commit a Deps Optimization run as it was cancelled');
  40844. }
  40845. // Ignore clean up requests after this point so the temp folder isn't deleted before
  40846. // we finish commiting the new deps cache files to the deps folder
  40847. committed = true;
  40848. // Write metadata file, then commit the processing folder to the global deps cache
  40849. // Rewire the file paths from the temporal processing dir to the final deps cache dir
  40850. const dataPath = path$o.join(processingCacheDir, '_metadata.json');
  40851. fs$l.writeFileSync(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
  40852. // In order to minimize the time where the deps folder isn't in a consistent state,
  40853. // we first rename the old depsCacheDir to a temporal path, then we rename the
  40854. // new processing cache dir to the depsCacheDir. In systems where doing so in sync
  40855. // is safe, we do an atomic operation (at least for this thread). For Windows, we
  40856. // found there are cases where the rename operation may finish before it's done
  40857. // so we do a graceful rename checking that the folder has been properly renamed.
  40858. // We found that the rename-rename (then delete the old folder in the background)
  40859. // is safer than a delete-rename operation.
  40860. const temporalPath = depsCacheDir + getTempSuffix();
  40861. const depsCacheDirPresent = fs$l.existsSync(depsCacheDir);
  40862. if (isWindows$4) {
  40863. if (depsCacheDirPresent)
  40864. await safeRename(depsCacheDir, temporalPath);
  40865. await safeRename(processingCacheDir, depsCacheDir);
  40866. }
  40867. else {
  40868. if (depsCacheDirPresent)
  40869. fs$l.renameSync(depsCacheDir, temporalPath);
  40870. fs$l.renameSync(processingCacheDir, depsCacheDir);
  40871. }
  40872. // Delete temporal path in the background
  40873. if (depsCacheDirPresent)
  40874. fsp.rm(temporalPath, { recursive: true, force: true });
  40875. },
  40876. };
  40877. if (!qualifiedIds.length) {
  40878. // No deps to optimize, we still commit the processing cache dir to remove
  40879. // the previous optimized deps if they exist, and let the next server start
  40880. // skip the scanner step if the lockfile hasn't changed
  40881. return {
  40882. cancel: async () => cleanUp(),
  40883. result: Promise.resolve(succesfulResult),
  40884. };
  40885. }
  40886. const cancelledResult = {
  40887. metadata,
  40888. commit: async () => cleanUp(),
  40889. cancel: cleanUp,
  40890. };
  40891. const start = performance$1.now();
  40892. const preparedRun = prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, processingCacheDir, optimizerContext);
  40893. const runResult = preparedRun.then(({ context, idToExports }) => {
  40894. function disposeContext() {
  40895. return context?.dispose().catch((e) => {
  40896. config.logger.error('Failed to dispose esbuild context', { error: e });
  40897. });
  40898. }
  40899. if (!context || optimizerContext.cancelled) {
  40900. disposeContext();
  40901. return cancelledResult;
  40902. }
  40903. return context
  40904. .rebuild()
  40905. .then((result) => {
  40906. const meta = result.metafile;
  40907. // the paths in `meta.outputs` are relative to `process.cwd()`
  40908. const processingCacheDirOutputPath = path$o.relative(process.cwd(), processingCacheDir);
  40909. for (const id in depsInfo) {
  40910. const output = esbuildOutputFromId(meta.outputs, id, processingCacheDir);
  40911. const { exportsData, ...info } = depsInfo[id];
  40912. addOptimizedDepInfo(metadata, 'optimized', {
  40913. ...info,
  40914. // We only need to hash the output.imports in to check for stability, but adding the hash
  40915. // and file path gives us a unique hash that may be useful for other things in the future
  40916. fileHash: getHash(metadata.hash +
  40917. depsInfo[id].file +
  40918. JSON.stringify(output.imports)),
  40919. browserHash: metadata.browserHash,
  40920. // After bundling we have more information and can warn the user about legacy packages
  40921. // that require manual configuration
  40922. needsInterop: needsInterop(config, ssr, id, idToExports[id], output),
  40923. });
  40924. }
  40925. for (const o of Object.keys(meta.outputs)) {
  40926. if (!o.match(jsMapExtensionRE)) {
  40927. const id = path$o
  40928. .relative(processingCacheDirOutputPath, o)
  40929. .replace(jsExtensionRE, '');
  40930. const file = getOptimizedDepPath(id, resolvedConfig, ssr);
  40931. if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) {
  40932. addOptimizedDepInfo(metadata, 'chunks', {
  40933. id,
  40934. file,
  40935. needsInterop: false,
  40936. browserHash: metadata.browserHash,
  40937. });
  40938. }
  40939. }
  40940. }
  40941. debug$7?.(`Dependencies bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
  40942. return succesfulResult;
  40943. })
  40944. .catch((e) => {
  40945. if (e.errors && e.message.includes('The build was canceled')) {
  40946. // esbuild logs an error when cancelling, but this is expected so
  40947. // return an empty result instead
  40948. return cancelledResult;
  40949. }
  40950. throw e;
  40951. })
  40952. .finally(() => {
  40953. return disposeContext();
  40954. });
  40955. });
  40956. runResult.catch(() => {
  40957. cleanUp();
  40958. });
  40959. return {
  40960. async cancel() {
  40961. optimizerContext.cancelled = true;
  40962. const { context } = await preparedRun;
  40963. await context?.cancel();
  40964. cleanUp();
  40965. },
  40966. result: runResult,
  40967. };
  40968. }
  40969. async function prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, processingCacheDir, optimizerContext) {
  40970. const isBuild = resolvedConfig.command === 'build';
  40971. const config = {
  40972. ...resolvedConfig,
  40973. command: 'build',
  40974. };
  40975. // esbuild generates nested directory output with lowest common ancestor base
  40976. // this is unpredictable and makes it difficult to analyze entry / output
  40977. // mapping. So what we do here is:
  40978. // 1. flatten all ids to eliminate slash
  40979. // 2. in the plugin, read the entry ourselves as virtual files to retain the
  40980. // path.
  40981. const flatIdDeps = {};
  40982. const idToExports = {};
  40983. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  40984. const { plugins: pluginsFromConfig = [], ...esbuildOptions } = optimizeDeps?.esbuildOptions ?? {};
  40985. await Promise.all(Object.keys(depsInfo).map(async (id) => {
  40986. const src = depsInfo[id].src;
  40987. const exportsData = await (depsInfo[id].exportsData ??
  40988. extractExportsData(src, config, ssr));
  40989. if (exportsData.jsxLoader && !esbuildOptions.loader?.['.js']) {
  40990. // Ensure that optimization won't fail by defaulting '.js' to the JSX parser.
  40991. // This is useful for packages such as Gatsby.
  40992. esbuildOptions.loader = {
  40993. '.js': 'jsx',
  40994. ...esbuildOptions.loader,
  40995. };
  40996. }
  40997. const flatId = flattenId(id);
  40998. flatIdDeps[flatId] = src;
  40999. idToExports[id] = exportsData;
  41000. }));
  41001. if (optimizerContext.cancelled)
  41002. return { context: undefined, idToExports };
  41003. // esbuild automatically replaces process.env.NODE_ENV for platform 'browser'
  41004. // In lib mode, we need to keep process.env.NODE_ENV untouched, so to at build
  41005. // time we replace it by __vite_process_env_NODE_ENV. This placeholder will be
  41006. // later replaced by the define plugin
  41007. const define = {
  41008. 'process.env.NODE_ENV': isBuild
  41009. ? '__vite_process_env_NODE_ENV'
  41010. : JSON.stringify(process.env.NODE_ENV || config.mode),
  41011. };
  41012. const platform = ssr && config.ssr?.target !== 'webworker' ? 'node' : 'browser';
  41013. const external = [...(optimizeDeps?.exclude ?? [])];
  41014. if (isBuild) {
  41015. let rollupOptionsExternal = config?.build?.rollupOptions?.external;
  41016. if (rollupOptionsExternal) {
  41017. if (typeof rollupOptionsExternal === 'string') {
  41018. rollupOptionsExternal = [rollupOptionsExternal];
  41019. }
  41020. // TODO: decide whether to support RegExp and function options
  41021. // They're not supported yet because `optimizeDeps.exclude` currently only accepts strings
  41022. if (!Array.isArray(rollupOptionsExternal) ||
  41023. rollupOptionsExternal.some((ext) => typeof ext !== 'string')) {
  41024. throw new Error(`[vite] 'build.rollupOptions.external' can only be an array of strings or a string when using esbuild optimization at build time.`);
  41025. }
  41026. external.push(...rollupOptionsExternal);
  41027. }
  41028. }
  41029. const plugins = [...pluginsFromConfig];
  41030. if (external.length) {
  41031. plugins.push(esbuildCjsExternalPlugin(external, platform));
  41032. }
  41033. plugins.push(esbuildDepPlugin(flatIdDeps, external, config, ssr));
  41034. const context = await esbuild.context({
  41035. absWorkingDir: process.cwd(),
  41036. entryPoints: Object.keys(flatIdDeps),
  41037. bundle: true,
  41038. // We can't use platform 'neutral', as esbuild has custom handling
  41039. // when the platform is 'node' or 'browser' that can't be emulated
  41040. // by using mainFields and conditions
  41041. platform,
  41042. define,
  41043. format: 'esm',
  41044. // See https://github.com/evanw/esbuild/issues/1921#issuecomment-1152991694
  41045. banner: platform === 'node'
  41046. ? {
  41047. js: `import { createRequire } from 'module';const require = createRequire(import.meta.url);`,
  41048. }
  41049. : undefined,
  41050. target: isBuild ? config.build.target || undefined : ESBUILD_MODULES_TARGET,
  41051. external,
  41052. logLevel: 'error',
  41053. splitting: true,
  41054. sourcemap: true,
  41055. outdir: processingCacheDir,
  41056. ignoreAnnotations: !isBuild,
  41057. metafile: true,
  41058. plugins,
  41059. charset: 'utf8',
  41060. ...esbuildOptions,
  41061. supported: {
  41062. 'dynamic-import': true,
  41063. 'import-meta': true,
  41064. ...esbuildOptions.supported,
  41065. },
  41066. });
  41067. return { context, idToExports };
  41068. }
  41069. async function findKnownImports(config, ssr) {
  41070. const { deps } = await scanImports(config).result;
  41071. await addManuallyIncludedOptimizeDeps(deps, config, ssr);
  41072. return Object.keys(deps);
  41073. }
  41074. async function addManuallyIncludedOptimizeDeps(deps, config, ssr, extra = [], filter) {
  41075. const { logger } = config;
  41076. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  41077. const optimizeDepsInclude = optimizeDeps?.include ?? [];
  41078. if (optimizeDepsInclude.length || extra.length) {
  41079. const unableToOptimize = (id, msg) => {
  41080. if (optimizeDepsInclude.includes(id)) {
  41081. logger.warn(`${msg}: ${colors$1.cyan(id)}, present in '${ssr ? 'ssr.' : ''}optimizeDeps.include'`);
  41082. }
  41083. };
  41084. const resolve = createOptimizeDepsIncludeResolver(config, ssr);
  41085. for (const id of [...optimizeDepsInclude, ...extra]) {
  41086. // normalize 'foo >bar` as 'foo > bar' to prevent same id being added
  41087. // and for pretty printing
  41088. const normalizedId = normalizeId(id);
  41089. if (!deps[normalizedId] && filter?.(normalizedId) !== false) {
  41090. const entry = await resolve(id);
  41091. if (entry) {
  41092. if (isOptimizable(entry, optimizeDeps)) {
  41093. if (!entry.endsWith('?__vite_skip_optimization')) {
  41094. deps[normalizedId] = entry;
  41095. }
  41096. }
  41097. else {
  41098. unableToOptimize(id, 'Cannot optimize dependency');
  41099. }
  41100. }
  41101. else {
  41102. unableToOptimize(id, 'Failed to resolve dependency');
  41103. }
  41104. }
  41105. }
  41106. }
  41107. }
  41108. function createOptimizeDepsIncludeResolver(config, ssr) {
  41109. const resolve = config.createResolver({
  41110. asSrc: false,
  41111. scan: true,
  41112. ssrOptimizeCheck: ssr,
  41113. ssrConfig: config.ssr,
  41114. packageCache: new Map(),
  41115. });
  41116. return async (id) => {
  41117. const lastArrowIndex = id.lastIndexOf('>');
  41118. if (lastArrowIndex === -1) {
  41119. return await resolve(id, undefined, undefined, ssr);
  41120. }
  41121. // split nested selected id by last '>', for example:
  41122. // 'foo > bar > baz' => 'foo > bar' & 'baz'
  41123. const nestedRoot = id.substring(0, lastArrowIndex).trim();
  41124. const nestedPath = id.substring(lastArrowIndex + 1).trim();
  41125. const basedir = nestedResolveBasedir(nestedRoot, config.root, config.resolve.preserveSymlinks);
  41126. return await resolve(nestedPath, basedir, undefined, ssr);
  41127. };
  41128. }
  41129. /**
  41130. * Continously resolve the basedir of packages separated by '>'
  41131. */
  41132. function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
  41133. const pkgs = id.split('>').map((pkg) => pkg.trim());
  41134. for (const pkg of pkgs) {
  41135. basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir;
  41136. }
  41137. return basedir;
  41138. }
  41139. function newDepOptimizationProcessing() {
  41140. let resolve;
  41141. const promise = new Promise((_resolve) => {
  41142. resolve = _resolve;
  41143. });
  41144. return { promise, resolve: resolve };
  41145. }
  41146. // Convert to { id: src }
  41147. function depsFromOptimizedDepInfo(depsInfo) {
  41148. return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
  41149. }
  41150. function getOptimizedDepPath(id, config, ssr) {
  41151. return normalizePath$3(path$o.resolve(getDepsCacheDir(config, ssr), flattenId(id) + '.js'));
  41152. }
  41153. function getDepsCacheSuffix(config, ssr) {
  41154. let suffix = '';
  41155. if (config.command === 'build') {
  41156. // Differentiate build caches depending on outDir to allow parallel builds
  41157. const { outDir } = config.build;
  41158. const buildId = outDir.length > 8 || outDir.includes('/') ? getHash(outDir) : outDir;
  41159. suffix += `_build-${buildId}`;
  41160. }
  41161. if (ssr) {
  41162. suffix += '_ssr';
  41163. }
  41164. return suffix;
  41165. }
  41166. function getDepsCacheDir(config, ssr) {
  41167. return getDepsCacheDirPrefix(config) + getDepsCacheSuffix(config, ssr);
  41168. }
  41169. function getProcessingDepsCacheDir(config, ssr) {
  41170. return (getDepsCacheDirPrefix(config) +
  41171. getDepsCacheSuffix(config, ssr) +
  41172. getTempSuffix());
  41173. }
  41174. function getTempSuffix() {
  41175. return ('_temp_' +
  41176. getHash(`${process.pid}:${Date.now().toString()}:${Math.random()
  41177. .toString(16)
  41178. .slice(2)}`));
  41179. }
  41180. function getDepsCacheDirPrefix(config) {
  41181. return normalizePath$3(path$o.resolve(config.cacheDir, 'deps'));
  41182. }
  41183. function createIsOptimizedDepFile(config) {
  41184. const depsCacheDirPrefix = getDepsCacheDirPrefix(config);
  41185. return (id) => id.startsWith(depsCacheDirPrefix);
  41186. }
  41187. function createIsOptimizedDepUrl(config) {
  41188. const { root } = config;
  41189. const depsCacheDir = getDepsCacheDirPrefix(config);
  41190. // determine the url prefix of files inside cache directory
  41191. const depsCacheDirRelative = normalizePath$3(path$o.relative(root, depsCacheDir));
  41192. const depsCacheDirPrefix = depsCacheDirRelative.startsWith('../')
  41193. ? // if the cache directory is outside root, the url prefix would be something
  41194. // like '/@fs/absolute/path/to/node_modules/.vite'
  41195. `/@fs/${removeLeadingSlash(normalizePath$3(depsCacheDir))}`
  41196. : // if the cache directory is inside root, the url prefix would be something
  41197. // like '/node_modules/.vite'
  41198. `/${depsCacheDirRelative}`;
  41199. return function isOptimizedDepUrl(url) {
  41200. return url.startsWith(depsCacheDirPrefix);
  41201. };
  41202. }
  41203. function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
  41204. const { hash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
  41205. // Paths can be absolute or relative to the deps cache dir where
  41206. // the _metadata.json is located
  41207. if (key === 'file' || key === 'src') {
  41208. return normalizePath$3(path$o.resolve(depsCacheDir, value));
  41209. }
  41210. return value;
  41211. });
  41212. if (!chunks ||
  41213. Object.values(optimized).some((depInfo) => !depInfo.fileHash)) {
  41214. // outdated _metadata.json version, ignore
  41215. return;
  41216. }
  41217. const metadata = {
  41218. hash,
  41219. browserHash,
  41220. optimized: {},
  41221. discovered: {},
  41222. chunks: {},
  41223. depInfoList: [],
  41224. };
  41225. for (const id of Object.keys(optimized)) {
  41226. addOptimizedDepInfo(metadata, 'optimized', {
  41227. ...optimized[id],
  41228. id,
  41229. browserHash,
  41230. });
  41231. }
  41232. for (const id of Object.keys(chunks)) {
  41233. addOptimizedDepInfo(metadata, 'chunks', {
  41234. ...chunks[id],
  41235. id,
  41236. browserHash,
  41237. needsInterop: false,
  41238. });
  41239. }
  41240. return metadata;
  41241. }
  41242. /**
  41243. * Stringify metadata for deps cache. Remove processing promises
  41244. * and individual dep info browserHash. Once the cache is reload
  41245. * the next time the server start we need to use the global
  41246. * browserHash to allow long term caching
  41247. */
  41248. function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
  41249. const { hash, browserHash, optimized, chunks } = metadata;
  41250. return JSON.stringify({
  41251. hash,
  41252. browserHash,
  41253. optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop }) => [
  41254. id,
  41255. {
  41256. src,
  41257. file,
  41258. fileHash,
  41259. needsInterop,
  41260. },
  41261. ])),
  41262. chunks: Object.fromEntries(Object.values(chunks).map(({ id, file }) => [id, { file }])),
  41263. }, (key, value) => {
  41264. // Paths can be absolute or relative to the deps cache dir where
  41265. // the _metadata.json is located
  41266. if (key === 'file' || key === 'src') {
  41267. return normalizePath$3(path$o.relative(depsCacheDir, value));
  41268. }
  41269. return value;
  41270. }, 2);
  41271. }
  41272. function esbuildOutputFromId(outputs, id, cacheDirOutputPath) {
  41273. const cwd = process.cwd();
  41274. const flatId = flattenId(id) + '.js';
  41275. const normalizedOutputPath = normalizePath$3(path$o.relative(cwd, path$o.join(cacheDirOutputPath, flatId)));
  41276. const output = outputs[normalizedOutputPath];
  41277. if (output) {
  41278. return output;
  41279. }
  41280. // If the root dir was symlinked, esbuild could return output keys as `../cwd/`
  41281. // Normalize keys to support this case too
  41282. for (const [key, value] of Object.entries(outputs)) {
  41283. if (normalizePath$3(path$o.relative(cwd, key)) === normalizedOutputPath) {
  41284. return value;
  41285. }
  41286. }
  41287. }
  41288. async function extractExportsData(filePath, config, ssr) {
  41289. await init;
  41290. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  41291. const esbuildOptions = optimizeDeps?.esbuildOptions ?? {};
  41292. if (optimizeDeps.extensions?.some((ext) => filePath.endsWith(ext))) {
  41293. // For custom supported extensions, build the entry file to transform it into JS,
  41294. // and then parse with es-module-lexer. Note that the `bundle` option is not `true`,
  41295. // so only the entry file is being transformed.
  41296. const result = await build$3({
  41297. ...esbuildOptions,
  41298. entryPoints: [filePath],
  41299. write: false,
  41300. format: 'esm',
  41301. });
  41302. const [imports, exports] = parse$e(result.outputFiles[0].text);
  41303. return {
  41304. hasImports: imports.length > 0,
  41305. exports: exports.map((e) => e.n),
  41306. };
  41307. }
  41308. let parseResult;
  41309. let usedJsxLoader = false;
  41310. const entryContent = await fsp.readFile(filePath, 'utf-8');
  41311. try {
  41312. parseResult = parse$e(entryContent);
  41313. }
  41314. catch {
  41315. const loader = esbuildOptions.loader?.[path$o.extname(filePath)] || 'jsx';
  41316. debug$7?.(`Unable to parse: ${filePath}.\n Trying again with a ${loader} transform.`);
  41317. const transformed = await transformWithEsbuild(entryContent, filePath, {
  41318. loader,
  41319. });
  41320. parseResult = parse$e(transformed.code);
  41321. usedJsxLoader = true;
  41322. }
  41323. const [imports, exports] = parseResult;
  41324. const exportsData = {
  41325. hasImports: imports.length > 0,
  41326. exports: exports.map((e) => e.n),
  41327. jsxLoader: usedJsxLoader,
  41328. };
  41329. return exportsData;
  41330. }
  41331. function needsInterop(config, ssr, id, exportsData, output) {
  41332. if (getDepOptimizationConfig(config, ssr)?.needsInterop?.includes(id)) {
  41333. return true;
  41334. }
  41335. const { hasImports, exports } = exportsData;
  41336. // entry has no ESM syntax - likely CJS or UMD
  41337. if (!exports.length && !hasImports) {
  41338. return true;
  41339. }
  41340. if (output) {
  41341. // if a peer dependency used require() on an ESM dependency, esbuild turns the
  41342. // ESM dependency's entry chunk into a single default export... detect
  41343. // such cases by checking exports mismatch, and force interop.
  41344. const generatedExports = output.exports;
  41345. if (!generatedExports ||
  41346. (isSingleDefaultExport(generatedExports) &&
  41347. !isSingleDefaultExport(exports))) {
  41348. return true;
  41349. }
  41350. }
  41351. return false;
  41352. }
  41353. function isSingleDefaultExport(exports) {
  41354. return exports.length === 1 && exports[0] === 'default';
  41355. }
  41356. const lockfileFormats = [
  41357. { name: 'package-lock.json', checkPatches: true, manager: 'npm' },
  41358. { name: 'yarn.lock', checkPatches: true, manager: 'yarn' },
  41359. { name: 'pnpm-lock.yaml', checkPatches: false, manager: 'pnpm' },
  41360. { name: 'bun.lockb', checkPatches: true, manager: 'bun' },
  41361. ].sort((_, { manager }) => {
  41362. return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1;
  41363. });
  41364. const lockfileNames = lockfileFormats.map((l) => l.name);
  41365. function getDepHash(config, ssr) {
  41366. const lockfilePath = lookupFile(config.root, lockfileNames);
  41367. let content = lockfilePath ? fs$l.readFileSync(lockfilePath, 'utf-8') : '';
  41368. if (lockfilePath) {
  41369. const lockfileName = path$o.basename(lockfilePath);
  41370. const { checkPatches } = lockfileFormats.find((f) => f.name === lockfileName);
  41371. if (checkPatches) {
  41372. // Default of https://github.com/ds300/patch-package
  41373. const fullPath = path$o.join(path$o.dirname(lockfilePath), 'patches');
  41374. const stat = tryStatSync(fullPath);
  41375. if (stat?.isDirectory()) {
  41376. content += stat.mtimeMs.toString();
  41377. }
  41378. }
  41379. }
  41380. // also take config into account
  41381. // only a subset of config options that can affect dep optimization
  41382. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  41383. content += JSON.stringify({
  41384. mode: process.env.NODE_ENV || config.mode,
  41385. root: config.root,
  41386. resolve: config.resolve,
  41387. buildTarget: config.build.target,
  41388. assetsInclude: config.assetsInclude,
  41389. plugins: config.plugins.map((p) => p.name),
  41390. optimizeDeps: {
  41391. include: optimizeDeps?.include,
  41392. exclude: optimizeDeps?.exclude,
  41393. esbuildOptions: {
  41394. ...optimizeDeps?.esbuildOptions,
  41395. plugins: optimizeDeps?.esbuildOptions?.plugins?.map((p) => p.name),
  41396. },
  41397. },
  41398. }, (_, value) => {
  41399. if (typeof value === 'function' || value instanceof RegExp) {
  41400. return value.toString();
  41401. }
  41402. return value;
  41403. });
  41404. return getHash(content);
  41405. }
  41406. function getOptimizedBrowserHash(hash, deps, timestamp = '') {
  41407. return getHash(hash + JSON.stringify(deps) + timestamp);
  41408. }
  41409. function optimizedDepInfoFromId(metadata, id) {
  41410. return (metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id]);
  41411. }
  41412. function optimizedDepInfoFromFile(metadata, file) {
  41413. return metadata.depInfoList.find((depInfo) => depInfo.file === file);
  41414. }
  41415. function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
  41416. for (const o of Object.keys(dependenciesInfo)) {
  41417. const info = dependenciesInfo[o];
  41418. if (callbackFn(info, o)) {
  41419. return info;
  41420. }
  41421. }
  41422. }
  41423. async function optimizedDepNeedsInterop(metadata, file, config, ssr) {
  41424. const depInfo = optimizedDepInfoFromFile(metadata, file);
  41425. if (depInfo?.src && depInfo.needsInterop === undefined) {
  41426. depInfo.exportsData ?? (depInfo.exportsData = extractExportsData(depInfo.src, config, ssr));
  41427. depInfo.needsInterop = needsInterop(config, ssr, depInfo.id, await depInfo.exportsData);
  41428. }
  41429. return depInfo?.needsInterop;
  41430. }
  41431. const MAX_TEMP_DIR_AGE_MS = 24 * 60 * 60 * 1000;
  41432. async function cleanupDepsCacheStaleDirs(config) {
  41433. try {
  41434. const cacheDir = path$o.resolve(config.cacheDir);
  41435. if (fs$l.existsSync(cacheDir)) {
  41436. const dirents = await fsp.readdir(cacheDir, { withFileTypes: true });
  41437. for (const dirent of dirents) {
  41438. if (dirent.isDirectory() && dirent.name.includes('_temp_')) {
  41439. const tempDirPath = path$o.resolve(config.cacheDir, dirent.name);
  41440. const stats = await fsp.stat(tempDirPath).catch((_) => null);
  41441. if (stats?.mtime &&
  41442. Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
  41443. await fsp.rm(tempDirPath, { recursive: true, force: true });
  41444. }
  41445. }
  41446. }
  41447. }
  41448. }
  41449. catch (err) {
  41450. config.logger.error(err);
  41451. }
  41452. }
  41453. // We found issues with renaming folders in some systems. This is a custom
  41454. // implementation for the optimizer. It isn't intended to be a general utility
  41455. // Based on node-graceful-fs
  41456. // The ISC License
  41457. // Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors
  41458. // https://github.com/isaacs/node-graceful-fs/blob/main/LICENSE
  41459. // On Windows, A/V software can lock the directory, causing this
  41460. // to fail with an EACCES or EPERM if the directory contains newly
  41461. // created files. The original tried for up to 60 seconds, we only
  41462. // wait for 5 seconds, as a longer time would be seen as an error
  41463. const GRACEFUL_RENAME_TIMEOUT = 5000;
  41464. const safeRename = promisify$4(function gracefulRename(from, to, cb) {
  41465. const start = Date.now();
  41466. let backoff = 0;
  41467. fs$l.rename(from, to, function CB(er) {
  41468. if (er &&
  41469. (er.code === 'EACCES' || er.code === 'EPERM') &&
  41470. Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
  41471. setTimeout(function () {
  41472. fs$l.stat(to, function (stater, st) {
  41473. if (stater && stater.code === 'ENOENT')
  41474. fs$l.rename(from, to, CB);
  41475. else
  41476. CB(er);
  41477. });
  41478. }, backoff);
  41479. if (backoff < 100)
  41480. backoff += 10;
  41481. return;
  41482. }
  41483. if (cb)
  41484. cb(er);
  41485. });
  41486. });
  41487. var index$1 = {
  41488. __proto__: null,
  41489. addManuallyIncludedOptimizeDeps: addManuallyIncludedOptimizeDeps,
  41490. addOptimizedDepInfo: addOptimizedDepInfo,
  41491. cleanupDepsCacheStaleDirs: cleanupDepsCacheStaleDirs,
  41492. createIsOptimizedDepFile: createIsOptimizedDepFile,
  41493. createIsOptimizedDepUrl: createIsOptimizedDepUrl,
  41494. depsFromOptimizedDepInfo: depsFromOptimizedDepInfo,
  41495. depsLogString: depsLogString,
  41496. discoverProjectDependencies: discoverProjectDependencies,
  41497. extractExportsData: extractExportsData,
  41498. findKnownImports: findKnownImports,
  41499. getDepHash: getDepHash,
  41500. getDepsCacheDir: getDepsCacheDir,
  41501. getDepsOptimizer: getDepsOptimizer,
  41502. getOptimizedDepPath: getOptimizedDepPath,
  41503. initDepsOptimizer: initDepsOptimizer,
  41504. initDepsOptimizerMetadata: initDepsOptimizerMetadata,
  41505. initDevSsrDepsOptimizer: initDevSsrDepsOptimizer,
  41506. loadCachedDepOptimizationMetadata: loadCachedDepOptimizationMetadata,
  41507. newDepOptimizationProcessing: newDepOptimizationProcessing,
  41508. optimizeDeps: optimizeDeps,
  41509. optimizeServerSsrDeps: optimizeServerSsrDeps,
  41510. optimizedDepInfoFromFile: optimizedDepInfoFromFile,
  41511. optimizedDepInfoFromId: optimizedDepInfoFromId,
  41512. optimizedDepNeedsInterop: optimizedDepNeedsInterop,
  41513. runOptimizeDeps: runOptimizeDeps,
  41514. toDiscoveredDependencies: toDiscoveredDependencies
  41515. };
  41516. /**
  41517. * A flag for injected helpers. This flag will be set to `false` if the output
  41518. * target is not native es - so that injected helper logic can be conditionally
  41519. * dropped.
  41520. */
  41521. const isModernFlag = `__VITE_IS_MODERN__`;
  41522. const preloadMethod = `__vitePreload`;
  41523. const preloadMarker = `__VITE_PRELOAD__`;
  41524. const preloadHelperId = '\0vite/preload-helper';
  41525. const preloadMarkerWithQuote = new RegExp(`['"]${preloadMarker}['"]`);
  41526. const dynamicImportPrefixRE = /import\s*\(/;
  41527. // TODO: abstract
  41528. const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
  41529. const optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/;
  41530. function toRelativePath(filename, importer) {
  41531. const relPath = path$o.relative(path$o.dirname(importer), filename);
  41532. return relPath[0] === '.' ? relPath : `./${relPath}`;
  41533. }
  41534. function indexOfMatchInSlice(str, reg, pos = 0) {
  41535. if (pos !== 0) {
  41536. str = str.slice(pos);
  41537. }
  41538. const matcher = str.match(reg);
  41539. return matcher?.index !== undefined ? matcher.index + pos : -1;
  41540. }
  41541. /**
  41542. * Helper for preloading CSS and direct imports of async chunks in parallel to
  41543. * the async chunk itself.
  41544. */
  41545. function detectScriptRel() {
  41546. const relList = document.createElement('link').relList;
  41547. return relList && relList.supports && relList.supports('modulepreload')
  41548. ? 'modulepreload'
  41549. : 'preload';
  41550. }
  41551. function preload(baseModule, deps, importerUrl) {
  41552. // @ts-expect-error __VITE_IS_MODERN__ will be replaced with boolean later
  41553. if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
  41554. return baseModule();
  41555. }
  41556. const links = document.getElementsByTagName('link');
  41557. return Promise.all(deps.map((dep) => {
  41558. // @ts-expect-error assetsURL is declared before preload.toString()
  41559. dep = assetsURL(dep, importerUrl);
  41560. if (dep in seen)
  41561. return;
  41562. seen[dep] = true;
  41563. const isCss = dep.endsWith('.css');
  41564. const cssSelector = isCss ? '[rel="stylesheet"]' : '';
  41565. const isBaseRelative = !!importerUrl;
  41566. // check if the file is already preloaded by SSR markup
  41567. if (isBaseRelative) {
  41568. // When isBaseRelative is true then we have `importerUrl` and `dep` is
  41569. // already converted to an absolute URL by the `assetsURL` function
  41570. for (let i = links.length - 1; i >= 0; i--) {
  41571. const link = links[i];
  41572. // The `links[i].href` is an absolute URL thanks to browser doing the work
  41573. // for us. See https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes:idl-domstring-5
  41574. if (link.href === dep && (!isCss || link.rel === 'stylesheet')) {
  41575. return;
  41576. }
  41577. }
  41578. }
  41579. else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
  41580. return;
  41581. }
  41582. const link = document.createElement('link');
  41583. link.rel = isCss ? 'stylesheet' : scriptRel;
  41584. if (!isCss) {
  41585. link.as = 'script';
  41586. link.crossOrigin = '';
  41587. }
  41588. link.href = dep;
  41589. document.head.appendChild(link);
  41590. if (isCss) {
  41591. return new Promise((res, rej) => {
  41592. link.addEventListener('load', res);
  41593. link.addEventListener('error', () => rej(new Error(`Unable to preload CSS for ${dep}`)));
  41594. });
  41595. }
  41596. })).then(() => baseModule());
  41597. }
  41598. /**
  41599. * Build only. During serve this is performed as part of ./importAnalysis.
  41600. */
  41601. function buildImportAnalysisPlugin(config) {
  41602. const ssr = !!config.build.ssr;
  41603. const isWorker = config.isWorker;
  41604. const insertPreload = !(ssr ||
  41605. !!config.build.lib ||
  41606. isWorker ||
  41607. config.build.modulePreload === false);
  41608. const resolveModulePreloadDependencies = config.build.modulePreload && config.build.modulePreload.resolveDependencies;
  41609. const renderBuiltUrl = config.experimental.renderBuiltUrl;
  41610. const customModulePreloadPaths = !!(resolveModulePreloadDependencies || renderBuiltUrl);
  41611. const isRelativeBase = config.base === './' || config.base === '';
  41612. const optimizeModulePreloadRelativePaths = isRelativeBase && !customModulePreloadPaths;
  41613. const { modulePreload } = config.build;
  41614. const scriptRel = modulePreload && modulePreload.polyfill
  41615. ? `'modulepreload'`
  41616. : `(${detectScriptRel.toString()})()`;
  41617. // There are three different cases for the preload list format in __vitePreload
  41618. //
  41619. // __vitePreload(() => import(asyncChunk), [ ...deps... ])
  41620. //
  41621. // This is maintained to keep backwards compatibility as some users developed plugins
  41622. // using regex over this list to workaround the fact that module preload wasn't
  41623. // configurable.
  41624. const assetsURL = customModulePreloadPaths
  41625. ? // If `experimental.renderBuiltUrl` or `build.modulePreload.resolveDependencies` are used
  41626. // the dependencies are already resolved. To avoid the need for `new URL(dep, import.meta.url)`
  41627. // a helper `__vitePreloadRelativeDep` is used to resolve from relative paths which can be minimized.
  41628. `function(dep, importerUrl) { return dep.startsWith('.') ? new URL(dep, importerUrl).href : dep }`
  41629. : optimizeModulePreloadRelativePaths
  41630. ? // If there isn't custom resolvers affecting the deps list, deps in the list are relative
  41631. // to the current chunk and are resolved to absolute URL by the __vitePreload helper itself.
  41632. // The importerUrl is passed as third parameter to __vitePreload in this case
  41633. `function(dep, importerUrl) { return new URL(dep, importerUrl).href }`
  41634. : // If the base isn't relative, then the deps are relative to the projects `outDir` and the base
  41635. // is appended inside __vitePreload too.
  41636. `function(dep) { return ${JSON.stringify(config.base)}+dep }`;
  41637. const preloadCode = `const scriptRel = ${scriptRel};const assetsURL = ${assetsURL};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
  41638. return {
  41639. name: 'vite:build-import-analysis',
  41640. resolveId(id) {
  41641. if (id === preloadHelperId) {
  41642. return id;
  41643. }
  41644. },
  41645. load(id) {
  41646. if (id === preloadHelperId) {
  41647. return preloadCode;
  41648. }
  41649. },
  41650. async transform(source, importer) {
  41651. if (isInNodeModules(importer) && !dynamicImportPrefixRE.test(source)) {
  41652. return;
  41653. }
  41654. await init;
  41655. let imports = [];
  41656. try {
  41657. imports = parse$e(source)[0];
  41658. }
  41659. catch (e) {
  41660. this.error(e, e.idx);
  41661. }
  41662. if (!imports.length) {
  41663. return null;
  41664. }
  41665. const { root } = config;
  41666. const depsOptimizer = getDepsOptimizer(config, ssr);
  41667. const normalizeUrl = async (url, pos) => {
  41668. let importerFile = importer;
  41669. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  41670. if (moduleListContains(optimizeDeps?.exclude, url)) {
  41671. if (depsOptimizer) {
  41672. await depsOptimizer.scanProcessing;
  41673. // if the dependency encountered in the optimized file was excluded from the optimization
  41674. // the dependency needs to be resolved starting from the original source location of the optimized file
  41675. // because starting from node_modules/.vite will not find the dependency if it was not hoisted
  41676. // (that is, if it is under node_modules directory in the package source of the optimized file)
  41677. for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
  41678. if (!optimizedModule.src)
  41679. continue; // Ignore chunks
  41680. if (optimizedModule.file === importer) {
  41681. importerFile = optimizedModule.src;
  41682. }
  41683. }
  41684. }
  41685. }
  41686. const resolved = await this.resolve(url, importerFile);
  41687. if (!resolved) {
  41688. // in ssr, we should let node handle the missing modules
  41689. if (ssr) {
  41690. return [url, url];
  41691. }
  41692. return this.error(`Failed to resolve import "${url}" from "${path$o.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
  41693. }
  41694. // normalize all imports into resolved URLs
  41695. // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
  41696. if (resolved.id.startsWith(root + '/')) {
  41697. // in root: infer short absolute path from root
  41698. url = resolved.id.slice(root.length);
  41699. }
  41700. else {
  41701. url = resolved.id;
  41702. }
  41703. if (isExternalUrl(url)) {
  41704. return [url, url];
  41705. }
  41706. return [url, resolved.id];
  41707. };
  41708. let s;
  41709. const str = () => s || (s = new MagicString(source));
  41710. let needPreloadHelper = false;
  41711. for (let index = 0; index < imports.length; index++) {
  41712. const { s: start, e: end, ss: expStart, se: expEnd, n: specifier, d: dynamicIndex, a: assertIndex, } = imports[index];
  41713. const isDynamicImport = dynamicIndex > -1;
  41714. // strip import assertions as we can process them ourselves
  41715. if (!isDynamicImport && assertIndex > -1) {
  41716. str().remove(end + 1, expEnd);
  41717. }
  41718. if (isDynamicImport && insertPreload) {
  41719. needPreloadHelper = true;
  41720. str().prependLeft(expStart, `${preloadMethod}(() => `);
  41721. str().appendRight(expEnd, `,${isModernFlag}?"${preloadMarker}":void 0${optimizeModulePreloadRelativePaths || customModulePreloadPaths
  41722. ? ',import.meta.url'
  41723. : ''})`);
  41724. }
  41725. // static import or valid string in dynamic import
  41726. // If resolvable, let's resolve it
  41727. if (depsOptimizer && specifier) {
  41728. // skip external / data uri
  41729. if (isExternalUrl(specifier) || isDataUrl(specifier)) {
  41730. continue;
  41731. }
  41732. // normalize
  41733. const [url, resolvedId] = await normalizeUrl(specifier, start);
  41734. if (url !== specifier) {
  41735. if (depsOptimizer.isOptimizedDepFile(resolvedId) &&
  41736. !resolvedId.match(optimizedDepChunkRE)) {
  41737. const file = cleanUrl(resolvedId); // Remove ?v={hash}
  41738. const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata, file, config, ssr);
  41739. let rewriteDone = false;
  41740. if (needsInterop === undefined) {
  41741. // Non-entry dynamic imports from dependencies will reach here as there isn't
  41742. // optimize info for them, but they don't need es interop. If the request isn't
  41743. // a dynamic import, then it is an internal Vite error
  41744. if (!file.match(optimizedDepDynamicRE)) {
  41745. config.logger.error(colors$1.red(`Vite Error, ${url} optimized info should be defined`));
  41746. }
  41747. }
  41748. else if (needsInterop) {
  41749. // config.logger.info(`${url} needs interop`)
  41750. interopNamedImports(str(), imports[index], url, index, importer, config);
  41751. rewriteDone = true;
  41752. }
  41753. if (!rewriteDone) {
  41754. const rewrittenUrl = JSON.stringify(file);
  41755. const s = isDynamicImport ? start : start - 1;
  41756. const e = isDynamicImport ? end : end + 1;
  41757. str().update(s, e, rewrittenUrl);
  41758. }
  41759. }
  41760. }
  41761. }
  41762. // Differentiate CSS imports that use the default export from those that
  41763. // do not by injecting a ?used query - this allows us to avoid including
  41764. // the CSS string when unnecessary (esbuild has trouble tree-shaking
  41765. // them)
  41766. if (specifier &&
  41767. isCSSRequest(specifier) &&
  41768. // always inject ?used query when it is a dynamic import
  41769. // because there is no way to check whether the default export is used
  41770. (source.slice(expStart, start).includes('from') || isDynamicImport) &&
  41771. // already has ?used query (by import.meta.glob)
  41772. !specifier.match(/\?used(&|$)/) &&
  41773. // don't append ?used when SPECIAL_QUERY_RE exists
  41774. !specifier.match(SPECIAL_QUERY_RE) &&
  41775. // edge case for package names ending with .css (e.g normalize.css)
  41776. !(bareImportRE.test(specifier) && !specifier.includes('/'))) {
  41777. const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`);
  41778. str().update(start, end, isDynamicImport ? `'${url}'` : url);
  41779. }
  41780. }
  41781. if (needPreloadHelper &&
  41782. insertPreload &&
  41783. !source.includes(`const ${preloadMethod} =`)) {
  41784. str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`);
  41785. }
  41786. if (s) {
  41787. return {
  41788. code: s.toString(),
  41789. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null,
  41790. };
  41791. }
  41792. },
  41793. renderChunk(code, _, { format }) {
  41794. // make sure we only perform the preload logic in modern builds.
  41795. if (code.indexOf(isModernFlag) > -1) {
  41796. const re = new RegExp(isModernFlag, 'g');
  41797. const isModern = String(format === 'es');
  41798. if (config.build.sourcemap) {
  41799. const s = new MagicString(code);
  41800. let match;
  41801. while ((match = re.exec(code))) {
  41802. s.update(match.index, match.index + isModernFlag.length, isModern);
  41803. }
  41804. return {
  41805. code: s.toString(),
  41806. map: s.generateMap({ hires: true }),
  41807. };
  41808. }
  41809. else {
  41810. return code.replace(re, isModern);
  41811. }
  41812. }
  41813. return null;
  41814. },
  41815. generateBundle({ format }, bundle) {
  41816. if (format !== 'es' ||
  41817. ssr ||
  41818. isWorker ||
  41819. config.build.modulePreload === false) {
  41820. return;
  41821. }
  41822. for (const file in bundle) {
  41823. const chunk = bundle[file];
  41824. // can't use chunk.dynamicImports.length here since some modules e.g.
  41825. // dynamic import to constant json may get inlined.
  41826. if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) {
  41827. const code = chunk.code;
  41828. let imports;
  41829. try {
  41830. imports = parse$e(code)[0].filter((i) => i.d > -1);
  41831. }
  41832. catch (e) {
  41833. this.error(e, e.idx);
  41834. }
  41835. const s = new MagicString(code);
  41836. const rewroteMarkerStartPos = new Set(); // position of the leading double quote
  41837. if (imports.length) {
  41838. for (let index = 0; index < imports.length; index++) {
  41839. // To handle escape sequences in specifier strings, the .n field will be provided where possible.
  41840. const { n: name, s: start, e: end, ss: expStart, se: expEnd, } = imports[index];
  41841. // check the chunk being imported
  41842. let url = name;
  41843. if (!url) {
  41844. const rawUrl = code.slice(start, end);
  41845. if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"`)
  41846. url = rawUrl.slice(1, -1);
  41847. }
  41848. const deps = new Set();
  41849. let hasRemovedPureCssChunk = false;
  41850. let normalizedFile = undefined;
  41851. if (url) {
  41852. normalizedFile = path$o.posix.join(path$o.posix.dirname(chunk.fileName), url);
  41853. const ownerFilename = chunk.fileName;
  41854. // literal import - trace direct imports and add to deps
  41855. const analyzed = new Set();
  41856. const addDeps = (filename) => {
  41857. if (filename === ownerFilename)
  41858. return;
  41859. if (analyzed.has(filename))
  41860. return;
  41861. analyzed.add(filename);
  41862. const chunk = bundle[filename];
  41863. if (chunk) {
  41864. deps.add(chunk.fileName);
  41865. chunk.imports.forEach(addDeps);
  41866. // Ensure that the css imported by current chunk is loaded after the dependencies.
  41867. // So the style of current chunk won't be overwritten unexpectedly.
  41868. chunk.viteMetadata.importedCss.forEach((file) => {
  41869. deps.add(file);
  41870. });
  41871. }
  41872. else {
  41873. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  41874. const chunk = removedPureCssFiles.get(filename);
  41875. if (chunk) {
  41876. if (chunk.viteMetadata.importedCss.size) {
  41877. chunk.viteMetadata.importedCss.forEach((file) => {
  41878. deps.add(file);
  41879. });
  41880. hasRemovedPureCssChunk = true;
  41881. }
  41882. s.update(expStart, expEnd, 'Promise.resolve({})');
  41883. }
  41884. }
  41885. };
  41886. addDeps(normalizedFile);
  41887. }
  41888. let markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote, end);
  41889. // fix issue #3051
  41890. if (markerStartPos === -1 && imports.length === 1) {
  41891. markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote);
  41892. }
  41893. if (markerStartPos > 0) {
  41894. // the dep list includes the main chunk, so only need to reload when there are actual other deps.
  41895. const depsArray = deps.size > 1 ||
  41896. // main chunk is removed
  41897. (hasRemovedPureCssChunk && deps.size > 0)
  41898. ? [...deps]
  41899. : [];
  41900. let renderedDeps;
  41901. if (normalizedFile && customModulePreloadPaths) {
  41902. const { modulePreload } = config.build;
  41903. const resolveDependencies = modulePreload && modulePreload.resolveDependencies;
  41904. let resolvedDeps;
  41905. if (resolveDependencies) {
  41906. // We can't let the user remove css deps as these aren't really preloads, they are just using
  41907. // the same mechanism as module preloads for this chunk
  41908. const cssDeps = [];
  41909. const otherDeps = [];
  41910. for (const dep of depsArray) {
  41911. (dep.endsWith('.css') ? cssDeps : otherDeps).push(dep);
  41912. }
  41913. resolvedDeps = [
  41914. ...resolveDependencies(normalizedFile, otherDeps, {
  41915. hostId: file,
  41916. hostType: 'js',
  41917. }),
  41918. ...cssDeps,
  41919. ];
  41920. }
  41921. else {
  41922. resolvedDeps = depsArray;
  41923. }
  41924. renderedDeps = resolvedDeps.map((dep) => {
  41925. const replacement = toOutputFilePathInJS(dep, 'asset', chunk.fileName, 'js', config, toRelativePath);
  41926. const replacementString = typeof replacement === 'string'
  41927. ? JSON.stringify(replacement)
  41928. : replacement.runtime;
  41929. return replacementString;
  41930. });
  41931. }
  41932. else {
  41933. renderedDeps = depsArray.map((d) =>
  41934. // Don't include the assets dir if the default asset file names
  41935. // are used, the path will be reconstructed by the import preload helper
  41936. JSON.stringify(optimizeModulePreloadRelativePaths
  41937. ? toRelativePath(d, file)
  41938. : d));
  41939. }
  41940. s.update(markerStartPos, markerStartPos + preloadMarker.length + 2, `[${renderedDeps.join(',')}]`);
  41941. rewroteMarkerStartPos.add(markerStartPos);
  41942. }
  41943. }
  41944. }
  41945. // there may still be markers due to inlined dynamic imports, remove
  41946. // all the markers regardless
  41947. let markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote);
  41948. while (markerStartPos >= 0) {
  41949. if (!rewroteMarkerStartPos.has(markerStartPos)) {
  41950. s.update(markerStartPos, markerStartPos + preloadMarker.length + 2, 'void 0');
  41951. }
  41952. markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote, markerStartPos + preloadMarker.length + 2);
  41953. }
  41954. if (s.hasChanged()) {
  41955. chunk.code = s.toString();
  41956. if (config.build.sourcemap && chunk.map) {
  41957. const nextMap = s.generateMap({
  41958. source: chunk.fileName,
  41959. hires: true,
  41960. });
  41961. const map = combineSourcemaps(chunk.fileName, [nextMap, chunk.map], false);
  41962. map.toUrl = () => genSourceMapUrl(map);
  41963. chunk.map = map;
  41964. if (config.build.sourcemap === 'inline') {
  41965. chunk.code = chunk.code.replace(convertSourceMap.mapFileCommentRegex, '');
  41966. chunk.code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  41967. }
  41968. else if (config.build.sourcemap) {
  41969. const mapAsset = bundle[chunk.fileName + '.map'];
  41970. if (mapAsset && mapAsset.type === 'asset') {
  41971. mapAsset.source = map.toString();
  41972. }
  41973. }
  41974. }
  41975. }
  41976. }
  41977. }
  41978. },
  41979. };
  41980. }
  41981. function ssrManifestPlugin(config) {
  41982. // module id => preload assets mapping
  41983. const ssrManifest = {};
  41984. const base = config.base; // TODO:base
  41985. return {
  41986. name: 'vite:ssr-manifest',
  41987. generateBundle(_options, bundle) {
  41988. for (const file in bundle) {
  41989. const chunk = bundle[file];
  41990. if (chunk.type === 'chunk') {
  41991. for (const id in chunk.modules) {
  41992. const normalizedId = normalizePath$3(relative$2(config.root, id));
  41993. const mappedChunks = ssrManifest[normalizedId] ?? (ssrManifest[normalizedId] = []);
  41994. if (!chunk.isEntry) {
  41995. mappedChunks.push(joinUrlSegments(base, chunk.fileName));
  41996. // <link> tags for entry chunks are already generated in static HTML,
  41997. // so we only need to record info for non-entry chunks.
  41998. chunk.viteMetadata.importedCss.forEach((file) => {
  41999. mappedChunks.push(joinUrlSegments(base, file));
  42000. });
  42001. }
  42002. chunk.viteMetadata.importedAssets.forEach((file) => {
  42003. mappedChunks.push(joinUrlSegments(base, file));
  42004. });
  42005. }
  42006. if (chunk.code.includes(preloadMethod)) {
  42007. // generate css deps map
  42008. const code = chunk.code;
  42009. let imports;
  42010. try {
  42011. imports = parse$e(code)[0].filter((i) => i.n && i.d > -1);
  42012. }
  42013. catch (e) {
  42014. this.error(e, e.idx);
  42015. }
  42016. if (imports.length) {
  42017. for (let index = 0; index < imports.length; index++) {
  42018. const { s: start, e: end, n: name } = imports[index];
  42019. // check the chunk being imported
  42020. const url = code.slice(start, end);
  42021. const deps = [];
  42022. const ownerFilename = chunk.fileName;
  42023. // literal import - trace direct imports and add to deps
  42024. const analyzed = new Set();
  42025. const addDeps = (filename) => {
  42026. if (filename === ownerFilename)
  42027. return;
  42028. if (analyzed.has(filename))
  42029. return;
  42030. analyzed.add(filename);
  42031. const chunk = bundle[filename];
  42032. if (chunk) {
  42033. chunk.viteMetadata.importedCss.forEach((file) => {
  42034. deps.push(joinUrlSegments(base, file)); // TODO:base
  42035. });
  42036. chunk.imports.forEach(addDeps);
  42037. }
  42038. };
  42039. const normalizedFile = normalizePath$3(join$2(dirname$2(chunk.fileName), url.slice(1, -1)));
  42040. addDeps(normalizedFile);
  42041. ssrManifest[basename$2(name)] = deps;
  42042. }
  42043. }
  42044. }
  42045. }
  42046. }
  42047. this.emitFile({
  42048. fileName: typeof config.build.ssrManifest === 'string'
  42049. ? config.build.ssrManifest
  42050. : 'ssr-manifest.json',
  42051. type: 'asset',
  42052. source: jsonStableStringify$1(ssrManifest, { space: 2 }),
  42053. });
  42054. },
  42055. };
  42056. }
  42057. /**
  42058. * A plugin to provide build load fallback for arbitrary request with queries.
  42059. */
  42060. function loadFallbackPlugin() {
  42061. return {
  42062. name: 'vite:load-fallback',
  42063. async load(id) {
  42064. try {
  42065. // if we don't add `await` here, we couldn't catch the error in readFile
  42066. return await promises$2.readFile(cleanUrl(id), 'utf-8');
  42067. }
  42068. catch (e) {
  42069. return promises$2.readFile(id, 'utf-8');
  42070. }
  42071. },
  42072. };
  42073. }
  42074. function resolveChokidarOptions(config, options) {
  42075. const { ignored = [], ...otherOptions } = options ?? {};
  42076. const resolvedWatchOptions = {
  42077. ignored: [
  42078. '**/.git/**',
  42079. '**/node_modules/**',
  42080. '**/test-results/**',
  42081. glob.escapePath(config.cacheDir) + '/**',
  42082. ...(Array.isArray(ignored) ? ignored : [ignored]),
  42083. ],
  42084. ignoreInitial: true,
  42085. ignorePermissionErrors: true,
  42086. ...otherOptions,
  42087. };
  42088. return resolvedWatchOptions;
  42089. }
  42090. /**
  42091. * make sure systemjs register wrap to had complete parameters in system format
  42092. */
  42093. function completeSystemWrapPlugin() {
  42094. const SystemJSWrapRE = /System.register\(.*(\(exports\)|\(\))/g;
  42095. return {
  42096. name: 'vite:force-systemjs-wrap-complete',
  42097. renderChunk(code, chunk, opts) {
  42098. if (opts.format === 'system') {
  42099. return {
  42100. code: code.replace(SystemJSWrapRE, (s, s1) => s.replace(s1, '(exports, module)')),
  42101. map: null,
  42102. };
  42103. }
  42104. },
  42105. };
  42106. }
  42107. /*!
  42108. * etag
  42109. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  42110. * MIT Licensed
  42111. */
  42112. /**
  42113. * Module exports.
  42114. * @public
  42115. */
  42116. var etag_1 = etag;
  42117. /**
  42118. * Module dependencies.
  42119. * @private
  42120. */
  42121. var crypto = require$$5$1;
  42122. var Stats = require$$0__default.Stats;
  42123. /**
  42124. * Module variables.
  42125. * @private
  42126. */
  42127. var toString = Object.prototype.toString;
  42128. /**
  42129. * Generate an entity tag.
  42130. *
  42131. * @param {Buffer|string} entity
  42132. * @return {string}
  42133. * @private
  42134. */
  42135. function entitytag (entity) {
  42136. if (entity.length === 0) {
  42137. // fast-path empty
  42138. return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
  42139. }
  42140. // compute hash of entity
  42141. var hash = crypto
  42142. .createHash('sha1')
  42143. .update(entity, 'utf8')
  42144. .digest('base64')
  42145. .substring(0, 27);
  42146. // compute length of entity
  42147. var len = typeof entity === 'string'
  42148. ? Buffer.byteLength(entity, 'utf8')
  42149. : entity.length;
  42150. return '"' + len.toString(16) + '-' + hash + '"'
  42151. }
  42152. /**
  42153. * Create a simple ETag.
  42154. *
  42155. * @param {string|Buffer|Stats} entity
  42156. * @param {object} [options]
  42157. * @param {boolean} [options.weak]
  42158. * @return {String}
  42159. * @public
  42160. */
  42161. function etag (entity, options) {
  42162. if (entity == null) {
  42163. throw new TypeError('argument entity is required')
  42164. }
  42165. // support fs.Stats object
  42166. var isStats = isstats(entity);
  42167. var weak = options && typeof options.weak === 'boolean'
  42168. ? options.weak
  42169. : isStats;
  42170. // validate argument
  42171. if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
  42172. throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
  42173. }
  42174. // generate entity tag
  42175. var tag = isStats
  42176. ? stattag(entity)
  42177. : entitytag(entity);
  42178. return weak
  42179. ? 'W/' + tag
  42180. : tag
  42181. }
  42182. /**
  42183. * Determine if object is a Stats object.
  42184. *
  42185. * @param {object} obj
  42186. * @return {boolean}
  42187. * @api private
  42188. */
  42189. function isstats (obj) {
  42190. // genuine fs.Stats
  42191. if (typeof Stats === 'function' && obj instanceof Stats) {
  42192. return true
  42193. }
  42194. // quack quack
  42195. return obj && typeof obj === 'object' &&
  42196. 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&
  42197. 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&
  42198. 'ino' in obj && typeof obj.ino === 'number' &&
  42199. 'size' in obj && typeof obj.size === 'number'
  42200. }
  42201. /**
  42202. * Generate a tag for a stat.
  42203. *
  42204. * @param {object} stat
  42205. * @return {string}
  42206. * @private
  42207. */
  42208. function stattag (stat) {
  42209. var mtime = stat.mtime.getTime().toString(16);
  42210. var size = stat.size.toString(16);
  42211. return '"' + size + '-' + mtime + '"'
  42212. }
  42213. var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1);
  42214. const alias = {
  42215. js: 'application/javascript',
  42216. css: 'text/css',
  42217. html: 'text/html',
  42218. json: 'application/json',
  42219. };
  42220. function send$2(req, res, content, type, options) {
  42221. const { etag = getEtag(content, { weak: true }), cacheControl = 'no-cache', headers, map, } = options;
  42222. if (res.writableEnded) {
  42223. return;
  42224. }
  42225. if (req.headers['if-none-match'] === etag) {
  42226. res.statusCode = 304;
  42227. res.end();
  42228. return;
  42229. }
  42230. res.setHeader('Content-Type', alias[type] || type);
  42231. res.setHeader('Cache-Control', cacheControl);
  42232. res.setHeader('Etag', etag);
  42233. if (headers) {
  42234. for (const name in headers) {
  42235. res.setHeader(name, headers[name]);
  42236. }
  42237. }
  42238. // inject source map reference
  42239. if (map && map.mappings) {
  42240. if (type === 'js' || type === 'css') {
  42241. content = getCodeWithSourcemap(type, content.toString(), map);
  42242. }
  42243. }
  42244. res.statusCode = 200;
  42245. res.end(content);
  42246. return;
  42247. }
  42248. function totalist(dir, callback, pre='') {
  42249. dir = resolve$3('.', dir);
  42250. let arr = readdirSync(dir);
  42251. let i=0, abs, stats;
  42252. for (; i < arr.length; i++) {
  42253. abs = join$1(dir, arr[i]);
  42254. stats = statSync$1(abs);
  42255. stats.isDirectory()
  42256. ? totalist(abs, callback, join$1(pre, arr[i]))
  42257. : callback(join$1(pre, arr[i]), abs, stats);
  42258. }
  42259. }
  42260. /**
  42261. * @typedef ParsedURL
  42262. * @type {import('.').ParsedURL}
  42263. */
  42264. /**
  42265. * @typedef Request
  42266. * @property {string} url
  42267. * @property {ParsedURL} _parsedUrl
  42268. */
  42269. /**
  42270. * @param {Request} req
  42271. * @returns {ParsedURL|void}
  42272. */
  42273. function parse$8(req) {
  42274. let raw = req.url;
  42275. if (raw == null) return;
  42276. let prev = req._parsedUrl;
  42277. if (prev && prev.raw === raw) return prev;
  42278. let pathname=raw, search='', query;
  42279. if (raw.length > 1) {
  42280. let idx = raw.indexOf('?', 1);
  42281. if (idx !== -1) {
  42282. search = raw.substring(idx);
  42283. pathname = raw.substring(0, idx);
  42284. if (search.length > 1) {
  42285. query = qs.parse(search.substring(1));
  42286. }
  42287. }
  42288. }
  42289. return req._parsedUrl = { pathname, search, query, raw };
  42290. }
  42291. const noop$2 = () => {};
  42292. function isMatch(uri, arr) {
  42293. for (let i=0; i < arr.length; i++) {
  42294. if (arr[i].test(uri)) return true;
  42295. }
  42296. }
  42297. function toAssume(uri, extns) {
  42298. let i=0, x, len=uri.length - 1;
  42299. if (uri.charCodeAt(len) === 47) {
  42300. uri = uri.substring(0, len);
  42301. }
  42302. let arr=[], tmp=`${uri}/index`;
  42303. for (; i < extns.length; i++) {
  42304. x = extns[i] ? `.${extns[i]}` : '';
  42305. if (uri) arr.push(uri + x);
  42306. arr.push(tmp + x);
  42307. }
  42308. return arr;
  42309. }
  42310. function viaCache(cache, uri, extns) {
  42311. let i=0, data, arr=toAssume(uri, extns);
  42312. for (; i < arr.length; i++) {
  42313. if (data = cache[arr[i]]) return data;
  42314. }
  42315. }
  42316. function viaLocal(dir, isEtag, uri, extns, shouldServe) {
  42317. let i=0, arr=toAssume(uri, extns);
  42318. let abs, stats, name, headers;
  42319. for (; i < arr.length; i++) {
  42320. abs = normalize(join$1(dir, name=arr[i]));
  42321. if (abs.startsWith(dir) && require$$0$2.existsSync(abs)) {
  42322. stats = require$$0$2.statSync(abs);
  42323. if (stats.isDirectory()) continue;
  42324. if (shouldServe && !shouldServe(abs)) continue;
  42325. headers = toHeaders(name, stats, isEtag);
  42326. headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
  42327. return { abs, stats, headers };
  42328. }
  42329. }
  42330. }
  42331. function is404(req, res) {
  42332. return (res.statusCode=404,res.end());
  42333. }
  42334. function send$1(req, res, file, stats, headers) {
  42335. let code=200, tmp, opts={};
  42336. headers = { ...headers };
  42337. for (let key in headers) {
  42338. tmp = res.getHeader(key);
  42339. if (tmp) headers[key] = tmp;
  42340. }
  42341. if (tmp = res.getHeader('content-type')) {
  42342. headers['Content-Type'] = tmp;
  42343. }
  42344. if (req.headers.range) {
  42345. code = 206;
  42346. let [x, y] = req.headers.range.replace('bytes=', '').split('-');
  42347. let end = opts.end = parseInt(y, 10) || stats.size - 1;
  42348. let start = opts.start = parseInt(x, 10) || 0;
  42349. if (start >= stats.size || end >= stats.size) {
  42350. res.setHeader('Content-Range', `bytes */${stats.size}`);
  42351. res.statusCode = 416;
  42352. return res.end();
  42353. }
  42354. headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
  42355. headers['Content-Length'] = (end - start + 1);
  42356. headers['Accept-Ranges'] = 'bytes';
  42357. }
  42358. res.writeHead(code, headers);
  42359. require$$0$2.createReadStream(file, opts).pipe(res);
  42360. }
  42361. const ENCODING = {
  42362. '.br': 'br',
  42363. '.gz': 'gzip',
  42364. };
  42365. function toHeaders(name, stats, isEtag) {
  42366. let enc = ENCODING[name.slice(-3)];
  42367. let ctype = lookup(name.slice(0, enc && -3)) || '';
  42368. if (ctype === 'text/html') ctype += ';charset=utf-8';
  42369. let headers = {
  42370. 'Content-Length': stats.size,
  42371. 'Content-Type': ctype,
  42372. 'Last-Modified': stats.mtime.toUTCString(),
  42373. };
  42374. if (enc) headers['Content-Encoding'] = enc;
  42375. if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  42376. return headers;
  42377. }
  42378. function sirv (dir, opts={}) {
  42379. dir = resolve$3(dir || '.');
  42380. let isNotFound = opts.onNoMatch || is404;
  42381. let setHeaders = opts.setHeaders || noop$2;
  42382. let extensions = opts.extensions || ['html', 'htm'];
  42383. let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
  42384. let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
  42385. const FILES = {};
  42386. let fallback = '/';
  42387. let isEtag = !!opts.etag;
  42388. let isSPA = !!opts.single;
  42389. if (typeof opts.single === 'string') {
  42390. let idx = opts.single.lastIndexOf('.');
  42391. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  42392. }
  42393. let ignores = [];
  42394. if (opts.ignores !== false) {
  42395. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
  42396. if (opts.dotfiles) ignores.push(/\/\.\w/);
  42397. else ignores.push(/\/\.well-known/);
  42398. [].concat(opts.ignores || []).forEach(x => {
  42399. ignores.push(new RegExp(x, 'i'));
  42400. });
  42401. }
  42402. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  42403. if (cc && opts.immutable) cc += ',immutable';
  42404. else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
  42405. if (!opts.dev) {
  42406. totalist(dir, (name, abs, stats) => {
  42407. if (/\.well-known[\\+\/]/.test(name)) ; // keep
  42408. else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  42409. let headers = toHeaders(name, stats, isEtag);
  42410. if (cc) headers['Cache-Control'] = cc;
  42411. FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
  42412. });
  42413. }
  42414. let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
  42415. return function (req, res, next) {
  42416. let extns = [''];
  42417. let pathname = parse$8(req).pathname;
  42418. let val = req.headers['accept-encoding'] || '';
  42419. if (gzips && val.includes('gzip')) extns.unshift(...gzips);
  42420. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  42421. extns.push(...extensions); // [...br, ...gz, orig, ...exts]
  42422. if (pathname.indexOf('%') !== -1) {
  42423. try { pathname = decodeURIComponent(pathname); }
  42424. catch (err) { /* malform uri */ }
  42425. }
  42426. let data = lookup(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns, opts.shouldServe);
  42427. if (!data) return next ? next() : isNotFound(req, res);
  42428. if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
  42429. res.writeHead(304);
  42430. return res.end();
  42431. }
  42432. if (gzips || brots) {
  42433. res.setHeader('Vary', 'Accept-Encoding');
  42434. }
  42435. setHeaders(res, pathname, data.stats);
  42436. send$1(req, res, data.abs, data.stats, data.headers);
  42437. };
  42438. }
  42439. /*!
  42440. * escape-html
  42441. * Copyright(c) 2012-2013 TJ Holowaychuk
  42442. * Copyright(c) 2015 Andreas Lubbe
  42443. * Copyright(c) 2015 Tiancheng "Timothy" Gu
  42444. * MIT Licensed
  42445. */
  42446. /**
  42447. * Module variables.
  42448. * @private
  42449. */
  42450. var matchHtmlRegExp = /["'&<>]/;
  42451. /**
  42452. * Module exports.
  42453. * @public
  42454. */
  42455. var escapeHtml_1 = escapeHtml$1;
  42456. /**
  42457. * Escape special characters in the given string of html.
  42458. *
  42459. * @param {string} string The string to escape for inserting into HTML
  42460. * @return {string}
  42461. * @public
  42462. */
  42463. function escapeHtml$1(string) {
  42464. var str = '' + string;
  42465. var match = matchHtmlRegExp.exec(str);
  42466. if (!match) {
  42467. return str;
  42468. }
  42469. var escape;
  42470. var html = '';
  42471. var index = 0;
  42472. var lastIndex = 0;
  42473. for (index = match.index; index < str.length; index++) {
  42474. switch (str.charCodeAt(index)) {
  42475. case 34: // "
  42476. escape = '&quot;';
  42477. break;
  42478. case 38: // &
  42479. escape = '&amp;';
  42480. break;
  42481. case 39: // '
  42482. escape = '&#39;';
  42483. break;
  42484. case 60: // <
  42485. escape = '&lt;';
  42486. break;
  42487. case 62: // >
  42488. escape = '&gt;';
  42489. break;
  42490. default:
  42491. continue;
  42492. }
  42493. if (lastIndex !== index) {
  42494. html += str.substring(lastIndex, index);
  42495. }
  42496. lastIndex = index + 1;
  42497. html += escape;
  42498. }
  42499. return lastIndex !== index
  42500. ? html + str.substring(lastIndex, index)
  42501. : html;
  42502. }
  42503. var escapeHtml$2 = /*@__PURE__*/getDefaultExportFromCjs(escapeHtml_1);
  42504. const knownJavascriptExtensionRE = /\.[tj]sx?$/;
  42505. const sirvOptions = ({ headers, shouldServe, }) => {
  42506. return {
  42507. dev: true,
  42508. etag: true,
  42509. extensions: [],
  42510. setHeaders(res, pathname) {
  42511. // Matches js, jsx, ts, tsx.
  42512. // The reason this is done, is that the .ts file extension is reserved
  42513. // for the MIME type video/mp2t. In almost all cases, we can expect
  42514. // these files to be TypeScript files, and for Vite to serve them with
  42515. // this Content-Type.
  42516. if (knownJavascriptExtensionRE.test(pathname)) {
  42517. res.setHeader('Content-Type', 'application/javascript');
  42518. }
  42519. if (headers) {
  42520. for (const name in headers) {
  42521. res.setHeader(name, headers[name]);
  42522. }
  42523. }
  42524. },
  42525. shouldServe,
  42526. };
  42527. };
  42528. function servePublicMiddleware(dir, headers) {
  42529. const serve = sirv(dir, sirvOptions({
  42530. headers,
  42531. shouldServe: (filePath) => shouldServeFile(filePath, dir),
  42532. }));
  42533. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  42534. return function viteServePublicMiddleware(req, res, next) {
  42535. // skip import request and internal requests `/@fs/ /@vite-client` etc...
  42536. if (isImportRequest(req.url) || isInternalRequest(req.url)) {
  42537. return next();
  42538. }
  42539. serve(req, res, next);
  42540. };
  42541. }
  42542. function serveStaticMiddleware(dir, server) {
  42543. const serve = sirv(dir, sirvOptions({
  42544. headers: server.config.server.headers,
  42545. }));
  42546. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  42547. return function viteServeStaticMiddleware(req, res, next) {
  42548. // only serve the file if it's not an html request or ends with `/`
  42549. // so that html requests can fallthrough to our html middleware for
  42550. // special processing
  42551. // also skip internal requests `/@fs/ /@vite-client` etc...
  42552. const cleanedUrl = cleanUrl(req.url);
  42553. if (cleanedUrl[cleanedUrl.length - 1] === '/' ||
  42554. path$o.extname(cleanedUrl) === '.html' ||
  42555. isInternalRequest(req.url)) {
  42556. return next();
  42557. }
  42558. const url = new URL(req.url, 'http://example.com');
  42559. const pathname = decodeURIComponent(url.pathname);
  42560. // apply aliases to static requests as well
  42561. let redirectedPathname;
  42562. for (const { find, replacement } of server.config.resolve.alias) {
  42563. const matches = typeof find === 'string'
  42564. ? pathname.startsWith(find)
  42565. : find.test(pathname);
  42566. if (matches) {
  42567. redirectedPathname = pathname.replace(find, replacement);
  42568. break;
  42569. }
  42570. }
  42571. if (redirectedPathname) {
  42572. // dir is pre-normalized to posix style
  42573. if (redirectedPathname.startsWith(dir)) {
  42574. redirectedPathname = redirectedPathname.slice(dir.length);
  42575. }
  42576. }
  42577. const resolvedPathname = redirectedPathname || pathname;
  42578. let fileUrl = path$o.resolve(dir, removeLeadingSlash(resolvedPathname));
  42579. if (resolvedPathname[resolvedPathname.length - 1] === '/' &&
  42580. fileUrl[fileUrl.length - 1] !== '/') {
  42581. fileUrl = fileUrl + '/';
  42582. }
  42583. if (!ensureServingAccess(fileUrl, server, res, next)) {
  42584. return;
  42585. }
  42586. if (redirectedPathname) {
  42587. url.pathname = encodeURIComponent(redirectedPathname);
  42588. req.url = url.href.slice(url.origin.length);
  42589. }
  42590. serve(req, res, next);
  42591. };
  42592. }
  42593. function serveRawFsMiddleware(server) {
  42594. const serveFromRoot = sirv('/', sirvOptions({ headers: server.config.server.headers }));
  42595. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  42596. return function viteServeRawFsMiddleware(req, res, next) {
  42597. const url = new URL(req.url, 'http://example.com');
  42598. // In some cases (e.g. linked monorepos) files outside of root will
  42599. // reference assets that are also out of served root. In such cases
  42600. // the paths are rewritten to `/@fs/` prefixed paths and must be served by
  42601. // searching based from fs root.
  42602. if (url.pathname.startsWith(FS_PREFIX)) {
  42603. const pathname = decodeURIComponent(url.pathname);
  42604. // restrict files outside of `fs.allow`
  42605. if (!ensureServingAccess(slash$1(path$o.resolve(fsPathFromId(pathname))), server, res, next)) {
  42606. return;
  42607. }
  42608. let newPathname = pathname.slice(FS_PREFIX.length);
  42609. if (isWindows$4)
  42610. newPathname = newPathname.replace(/^[A-Z]:/i, '');
  42611. url.pathname = encodeURIComponent(newPathname);
  42612. req.url = url.href.slice(url.origin.length);
  42613. serveFromRoot(req, res, next);
  42614. }
  42615. else {
  42616. next();
  42617. }
  42618. };
  42619. }
  42620. /**
  42621. * Check if the url is allowed to be served, via the `server.fs` config.
  42622. */
  42623. function isFileServingAllowed(url, server) {
  42624. if (!server.config.server.fs.strict)
  42625. return true;
  42626. const file = fsPathFromUrl(url);
  42627. if (server._fsDenyGlob(file))
  42628. return false;
  42629. if (server.moduleGraph.safeModulesPath.has(file))
  42630. return true;
  42631. if (server.config.server.fs.allow.some((dir) => isParentDirectory(dir, file)))
  42632. return true;
  42633. return false;
  42634. }
  42635. function ensureServingAccess(url, server, res, next) {
  42636. if (isFileServingAllowed(url, server)) {
  42637. return true;
  42638. }
  42639. if (isFileReadable(cleanUrl(url))) {
  42640. const urlMessage = `The request url "${url}" is outside of Vite serving allow list.`;
  42641. const hintMessage = `
  42642. ${server.config.server.fs.allow.map((i) => `- ${i}`).join('\n')}
  42643. Refer to docs https://vitejs.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
  42644. server.config.logger.error(urlMessage);
  42645. server.config.logger.warnOnce(hintMessage + '\n');
  42646. res.statusCode = 403;
  42647. res.write(renderRestrictedErrorHTML(urlMessage + '\n' + hintMessage));
  42648. res.end();
  42649. }
  42650. else {
  42651. // if the file doesn't exist, we shouldn't restrict this path as it can
  42652. // be an API call. Middlewares would issue a 404 if the file isn't handled
  42653. next();
  42654. }
  42655. return false;
  42656. }
  42657. function renderRestrictedErrorHTML(msg) {
  42658. // to have syntax highlighting and autocompletion in IDE
  42659. const html = String.raw;
  42660. return html `
  42661. <body>
  42662. <h1>403 Restricted</h1>
  42663. <p>${escapeHtml$2(msg).replace(/\n/g, '<br/>')}</p>
  42664. <style>
  42665. body {
  42666. padding: 1em 2em;
  42667. }
  42668. </style>
  42669. </body>
  42670. `;
  42671. }
  42672. function resolveBuildOptions(raw, logger, root) {
  42673. const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload;
  42674. if (raw) {
  42675. const { polyfillModulePreload, ...rest } = raw;
  42676. raw = rest;
  42677. if (deprecatedPolyfillModulePreload !== undefined) {
  42678. logger.warn('polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.');
  42679. }
  42680. if (deprecatedPolyfillModulePreload === false &&
  42681. raw.modulePreload === undefined) {
  42682. raw.modulePreload = { polyfill: false };
  42683. }
  42684. }
  42685. const modulePreload = raw?.modulePreload;
  42686. const defaultModulePreload = {
  42687. polyfill: true,
  42688. };
  42689. const defaultBuildOptions = {
  42690. outDir: 'dist',
  42691. assetsDir: 'assets',
  42692. assetsInlineLimit: 4096,
  42693. cssCodeSplit: !raw?.lib,
  42694. sourcemap: false,
  42695. rollupOptions: {},
  42696. minify: raw?.ssr ? false : 'esbuild',
  42697. terserOptions: {},
  42698. write: true,
  42699. emptyOutDir: null,
  42700. copyPublicDir: true,
  42701. manifest: false,
  42702. lib: false,
  42703. ssr: false,
  42704. ssrManifest: false,
  42705. ssrEmitAssets: false,
  42706. reportCompressedSize: true,
  42707. chunkSizeWarningLimit: 500,
  42708. watch: null,
  42709. };
  42710. const userBuildOptions = raw
  42711. ? mergeConfig(defaultBuildOptions, raw)
  42712. : defaultBuildOptions;
  42713. // @ts-expect-error Fallback options instead of merging
  42714. const resolved = {
  42715. target: 'modules',
  42716. cssTarget: false,
  42717. ...userBuildOptions,
  42718. commonjsOptions: {
  42719. include: [/node_modules/],
  42720. extensions: ['.js', '.cjs'],
  42721. ...userBuildOptions.commonjsOptions,
  42722. },
  42723. dynamicImportVarsOptions: {
  42724. warnOnError: true,
  42725. exclude: [/node_modules/],
  42726. ...userBuildOptions.dynamicImportVarsOptions,
  42727. },
  42728. // Resolve to false | object
  42729. modulePreload: modulePreload === false
  42730. ? false
  42731. : typeof modulePreload === 'object'
  42732. ? {
  42733. ...defaultModulePreload,
  42734. ...modulePreload,
  42735. }
  42736. : defaultModulePreload,
  42737. };
  42738. // handle special build targets
  42739. if (resolved.target === 'modules') {
  42740. resolved.target = ESBUILD_MODULES_TARGET;
  42741. }
  42742. else if (resolved.target === 'esnext' && resolved.minify === 'terser') {
  42743. try {
  42744. const terserPackageJsonPath = requireResolveFromRootWithFallback(root, 'terser/package.json');
  42745. const terserPackageJson = JSON.parse(fs$l.readFileSync(terserPackageJsonPath, 'utf-8'));
  42746. const v = terserPackageJson.version.split('.');
  42747. if (v[0] === '5' && v[1] < 16) {
  42748. // esnext + terser 5.16<: limit to es2021 so it can be minified by terser
  42749. resolved.target = 'es2021';
  42750. }
  42751. }
  42752. catch { }
  42753. }
  42754. if (!resolved.cssTarget) {
  42755. resolved.cssTarget = resolved.target;
  42756. }
  42757. // normalize false string into actual false
  42758. if (resolved.minify === 'false') {
  42759. resolved.minify = false;
  42760. }
  42761. if (resolved.minify === true) {
  42762. resolved.minify = 'esbuild';
  42763. }
  42764. if (resolved.cssMinify == null) {
  42765. resolved.cssMinify = !!resolved.minify;
  42766. }
  42767. return resolved;
  42768. }
  42769. async function resolveBuildPlugins(config) {
  42770. const options = config.build;
  42771. const { commonjsOptions } = options;
  42772. const usePluginCommonjs = !Array.isArray(commonjsOptions?.include) ||
  42773. commonjsOptions?.include.length !== 0;
  42774. const rollupOptionsPlugins = options.rollupOptions.plugins;
  42775. return {
  42776. pre: [
  42777. completeSystemWrapPlugin(),
  42778. ...(options.watch ? [ensureWatchPlugin()] : []),
  42779. ...(usePluginCommonjs ? [commonjs(options.commonjsOptions)] : []),
  42780. dataURIPlugin(),
  42781. ...(await asyncFlatten(Array.isArray(rollupOptionsPlugins)
  42782. ? rollupOptionsPlugins
  42783. : [rollupOptionsPlugins])).filter(Boolean),
  42784. ...(config.isWorker ? [webWorkerPostPlugin()] : []),
  42785. ],
  42786. post: [
  42787. buildImportAnalysisPlugin(config),
  42788. ...(config.esbuild !== false ? [buildEsbuildPlugin(config)] : []),
  42789. ...(options.minify ? [terserPlugin(config)] : []),
  42790. ...(!config.isWorker
  42791. ? [
  42792. ...(options.manifest ? [manifestPlugin(config)] : []),
  42793. ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),
  42794. buildReporterPlugin(config),
  42795. ]
  42796. : []),
  42797. loadFallbackPlugin(),
  42798. ],
  42799. };
  42800. }
  42801. /**
  42802. * Bundles the app for production.
  42803. * Returns a Promise containing the build result.
  42804. */
  42805. async function build(inlineConfig = {}) {
  42806. const config = await resolveConfig(inlineConfig, 'build', 'production', 'production');
  42807. const options = config.build;
  42808. const ssr = !!options.ssr;
  42809. const libOptions = options.lib;
  42810. config.logger.info(colors$1.cyan(`vite v${VERSION$1} ${colors$1.green(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)}`));
  42811. const resolve = (p) => path$o.resolve(config.root, p);
  42812. const input = libOptions
  42813. ? options.rollupOptions?.input ||
  42814. (typeof libOptions.entry === 'string'
  42815. ? resolve(libOptions.entry)
  42816. : Array.isArray(libOptions.entry)
  42817. ? libOptions.entry.map(resolve)
  42818. : Object.fromEntries(Object.entries(libOptions.entry).map(([alias, file]) => [
  42819. alias,
  42820. resolve(file),
  42821. ])))
  42822. : typeof options.ssr === 'string'
  42823. ? resolve(options.ssr)
  42824. : options.rollupOptions?.input || resolve('index.html');
  42825. if (ssr && typeof input === 'string' && input.endsWith('.html')) {
  42826. throw new Error(`rollupOptions.input should not be an html file when building for SSR. ` +
  42827. `Please specify a dedicated SSR entry.`);
  42828. }
  42829. const outDir = resolve(options.outDir);
  42830. // inject ssr arg to plugin load/transform hooks
  42831. const plugins = (ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins);
  42832. const userExternal = options.rollupOptions?.external;
  42833. let external = userExternal;
  42834. // In CJS, we can pass the externals to rollup as is. In ESM, we need to
  42835. // do it in the resolve plugin so we can add the resolved extension for
  42836. // deep node_modules imports
  42837. if (ssr && config.legacy?.buildSsrCjsExternalHeuristics) {
  42838. external = await cjsSsrResolveExternal(config, userExternal);
  42839. }
  42840. if (isDepsOptimizerEnabled(config, ssr)) {
  42841. await initDepsOptimizer(config);
  42842. }
  42843. const rollupOptions = {
  42844. context: 'globalThis',
  42845. preserveEntrySignatures: ssr
  42846. ? 'allow-extension'
  42847. : libOptions
  42848. ? 'strict'
  42849. : false,
  42850. cache: config.build.watch ? undefined : false,
  42851. ...options.rollupOptions,
  42852. input,
  42853. plugins,
  42854. external,
  42855. onwarn(warning, warn) {
  42856. onRollupWarning(warning, warn, config);
  42857. },
  42858. };
  42859. const outputBuildError = (e) => {
  42860. let msg = colors$1.red((e.plugin ? `[${e.plugin}] ` : '') + e.message);
  42861. if (e.id) {
  42862. msg += `\nfile: ${colors$1.cyan(e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ''))}`;
  42863. }
  42864. if (e.frame) {
  42865. msg += `\n` + colors$1.yellow(e.frame);
  42866. }
  42867. config.logger.error(msg, { error: e });
  42868. };
  42869. let bundle;
  42870. try {
  42871. const buildOutputOptions = (output = {}) => {
  42872. // @ts-expect-error See https://github.com/vitejs/vite/issues/5812#issuecomment-984345618
  42873. if (output.output) {
  42874. config.logger.warn(`You've set "rollupOptions.output.output" in your config. ` +
  42875. `This is deprecated and will override all Vite.js default output options. ` +
  42876. `Please use "rollupOptions.output" instead.`);
  42877. }
  42878. const ssrNodeBuild = ssr && config.ssr.target === 'node';
  42879. const ssrWorkerBuild = ssr && config.ssr.target === 'webworker';
  42880. const cjsSsrBuild = ssr && config.ssr.format === 'cjs';
  42881. const format = output.format || (cjsSsrBuild ? 'cjs' : 'es');
  42882. const jsExt = ssrNodeBuild || libOptions
  42883. ? resolveOutputJsExtension(format, findNearestPackageData(config.root, config.packageCache)?.data
  42884. .type)
  42885. : 'js';
  42886. return {
  42887. dir: outDir,
  42888. // Default format is 'es' for regular and for SSR builds
  42889. format,
  42890. exports: cjsSsrBuild ? 'named' : 'auto',
  42891. sourcemap: options.sourcemap,
  42892. name: libOptions ? libOptions.name : undefined,
  42893. // es2015 enables `generatedCode.symbols`
  42894. // - #764 add `Symbol.toStringTag` when build es module into cjs chunk
  42895. // - #1048 add `Symbol.toStringTag` for module default export
  42896. generatedCode: 'es2015',
  42897. entryFileNames: ssr
  42898. ? `[name].${jsExt}`
  42899. : libOptions
  42900. ? ({ name }) => resolveLibFilename(libOptions, format, name, config.root, jsExt, config.packageCache)
  42901. : path$o.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  42902. chunkFileNames: libOptions
  42903. ? `[name]-[hash].${jsExt}`
  42904. : path$o.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  42905. assetFileNames: libOptions
  42906. ? `[name].[ext]`
  42907. : path$o.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
  42908. inlineDynamicImports: output.format === 'umd' ||
  42909. output.format === 'iife' ||
  42910. (ssrWorkerBuild &&
  42911. (typeof input === 'string' || Object.keys(input).length === 1)),
  42912. ...output,
  42913. };
  42914. };
  42915. // resolve lib mode outputs
  42916. const outputs = resolveBuildOutputs(options.rollupOptions?.output, libOptions, config.logger);
  42917. const normalizedOutputs = [];
  42918. if (Array.isArray(outputs)) {
  42919. for (const resolvedOutput of outputs) {
  42920. normalizedOutputs.push(buildOutputOptions(resolvedOutput));
  42921. }
  42922. }
  42923. else {
  42924. normalizedOutputs.push(buildOutputOptions(outputs));
  42925. }
  42926. const outDirs = normalizedOutputs.map(({ dir }) => resolve(dir));
  42927. // watch file changes with rollup
  42928. if (config.build.watch) {
  42929. config.logger.info(colors$1.cyan(`\nwatching for file changes...`));
  42930. const resolvedChokidarOptions = resolveChokidarOptions(config, config.build.watch.chokidar);
  42931. const { watch } = await import('rollup');
  42932. const watcher = watch({
  42933. ...rollupOptions,
  42934. output: normalizedOutputs,
  42935. watch: {
  42936. ...config.build.watch,
  42937. chokidar: resolvedChokidarOptions,
  42938. },
  42939. });
  42940. watcher.on('event', (event) => {
  42941. if (event.code === 'BUNDLE_START') {
  42942. config.logger.info(colors$1.cyan(`\nbuild started...`));
  42943. if (options.write) {
  42944. prepareOutDir(outDirs, options.emptyOutDir, config);
  42945. }
  42946. }
  42947. else if (event.code === 'BUNDLE_END') {
  42948. event.result.close();
  42949. config.logger.info(colors$1.cyan(`built in ${event.duration}ms.`));
  42950. }
  42951. else if (event.code === 'ERROR') {
  42952. outputBuildError(event.error);
  42953. }
  42954. });
  42955. return watcher;
  42956. }
  42957. // write or generate files with rollup
  42958. const { rollup } = await import('rollup');
  42959. bundle = await rollup(rollupOptions);
  42960. if (options.write) {
  42961. prepareOutDir(outDirs, options.emptyOutDir, config);
  42962. }
  42963. const res = [];
  42964. for (const output of normalizedOutputs) {
  42965. res.push(await bundle[options.write ? 'write' : 'generate'](output));
  42966. }
  42967. return Array.isArray(outputs) ? res : res[0];
  42968. }
  42969. catch (e) {
  42970. outputBuildError(e);
  42971. throw e;
  42972. }
  42973. finally {
  42974. if (bundle)
  42975. await bundle.close();
  42976. }
  42977. }
  42978. function prepareOutDir(outDirs, emptyOutDir, config) {
  42979. const nonDuplicateDirs = new Set(outDirs);
  42980. let outside = false;
  42981. if (emptyOutDir == null) {
  42982. for (const outDir of nonDuplicateDirs) {
  42983. if (fs$l.existsSync(outDir) &&
  42984. !normalizePath$3(outDir).startsWith(config.root + '/')) {
  42985. // warn if outDir is outside of root
  42986. config.logger.warn(colors$1.yellow(`\n${colors$1.bold(`(!)`)} outDir ${colors$1.white(colors$1.dim(outDir))} is not inside project root and will not be emptied.\n` +
  42987. `Use --emptyOutDir to override.\n`));
  42988. outside = true;
  42989. break;
  42990. }
  42991. }
  42992. }
  42993. for (const outDir of nonDuplicateDirs) {
  42994. if (!outside && emptyOutDir !== false && fs$l.existsSync(outDir)) {
  42995. // skip those other outDirs which are nested in current outDir
  42996. const skipDirs = outDirs
  42997. .map((dir) => {
  42998. const relative = path$o.relative(outDir, dir);
  42999. if (relative &&
  43000. !relative.startsWith('..') &&
  43001. !path$o.isAbsolute(relative)) {
  43002. return relative;
  43003. }
  43004. return '';
  43005. })
  43006. .filter(Boolean);
  43007. emptyDir(outDir, [...skipDirs, '.git']);
  43008. }
  43009. if (config.build.copyPublicDir &&
  43010. config.publicDir &&
  43011. fs$l.existsSync(config.publicDir)) {
  43012. copyDir(config.publicDir, outDir);
  43013. }
  43014. }
  43015. }
  43016. function getPkgName(name) {
  43017. return name?.[0] === '@' ? name.split('/')[1] : name;
  43018. }
  43019. function resolveOutputJsExtension(format, type = 'commonjs') {
  43020. if (type === 'module') {
  43021. return format === 'cjs' || format === 'umd' ? 'cjs' : 'js';
  43022. }
  43023. else {
  43024. return format === 'es' ? 'mjs' : 'js';
  43025. }
  43026. }
  43027. function resolveLibFilename(libOptions, format, entryName, root, extension, packageCache) {
  43028. if (typeof libOptions.fileName === 'function') {
  43029. return libOptions.fileName(format, entryName);
  43030. }
  43031. const packageJson = findNearestPackageData(root, packageCache)?.data;
  43032. const name = libOptions.fileName ||
  43033. (packageJson && typeof libOptions.entry === 'string'
  43034. ? getPkgName(packageJson.name)
  43035. : entryName);
  43036. if (!name)
  43037. throw new Error('Name in package.json is required if option "build.lib.fileName" is not provided.');
  43038. extension ?? (extension = resolveOutputJsExtension(format, packageJson?.type));
  43039. if (format === 'cjs' || format === 'es') {
  43040. return `${name}.${extension}`;
  43041. }
  43042. return `${name}.${format}.${extension}`;
  43043. }
  43044. function resolveBuildOutputs(outputs, libOptions, logger) {
  43045. if (libOptions) {
  43046. const libHasMultipleEntries = typeof libOptions.entry !== 'string' &&
  43047. Object.values(libOptions.entry).length > 1;
  43048. const libFormats = libOptions.formats ||
  43049. (libHasMultipleEntries ? ['es', 'cjs'] : ['es', 'umd']);
  43050. if (!Array.isArray(outputs)) {
  43051. if (libFormats.includes('umd') || libFormats.includes('iife')) {
  43052. if (libHasMultipleEntries) {
  43053. throw new Error('Multiple entry points are not supported when output formats include "umd" or "iife".');
  43054. }
  43055. if (!libOptions.name) {
  43056. throw new Error('Option "build.lib.name" is required when output formats include "umd" or "iife".');
  43057. }
  43058. }
  43059. return libFormats.map((format) => ({ ...outputs, format }));
  43060. }
  43061. // By this point, we know "outputs" is an Array.
  43062. if (libOptions.formats) {
  43063. logger.warn(colors$1.yellow('"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.'));
  43064. }
  43065. outputs.forEach((output) => {
  43066. if (['umd', 'iife'].includes(output.format) && !output.name) {
  43067. throw new Error('Entries in "build.rollupOptions.output" must specify "name" when the format is "umd" or "iife".');
  43068. }
  43069. });
  43070. }
  43071. return outputs;
  43072. }
  43073. const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
  43074. const dynamicImportWarningIgnoreList = [
  43075. `Unsupported expression`,
  43076. `statically analyzed`,
  43077. ];
  43078. function onRollupWarning(warning, warn, config) {
  43079. function viteWarn(warning) {
  43080. if (warning.code === 'UNRESOLVED_IMPORT') {
  43081. const id = warning.id;
  43082. const exporter = warning.exporter;
  43083. // throw unless it's commonjs external...
  43084. if (!id || !/\?commonjs-external$/.test(id)) {
  43085. throw new Error(`[vite]: Rollup failed to resolve import "${exporter}" from "${id}".\n` +
  43086. `This is most likely unintended because it can break your application at runtime.\n` +
  43087. `If you do want to externalize this module explicitly add it to\n` +
  43088. `\`build.rollupOptions.external\``);
  43089. }
  43090. }
  43091. if (warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
  43092. dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))) {
  43093. return;
  43094. }
  43095. if (warningIgnoreList.includes(warning.code)) {
  43096. return;
  43097. }
  43098. if (warning.code === 'PLUGIN_WARNING') {
  43099. config.logger.warn(`${colors$1.bold(colors$1.yellow(`[plugin:${warning.plugin}]`))} ${colors$1.yellow(warning.message)}`);
  43100. return;
  43101. }
  43102. warn(warning);
  43103. }
  43104. const userOnWarn = config.build.rollupOptions?.onwarn;
  43105. if (userOnWarn) {
  43106. userOnWarn(warning, viteWarn);
  43107. }
  43108. else {
  43109. viteWarn(warning);
  43110. }
  43111. }
  43112. async function cjsSsrResolveExternal(config, user) {
  43113. // see if we have cached deps data available
  43114. let knownImports;
  43115. const dataPath = path$o.join(getDepsCacheDir(config, false), '_metadata.json');
  43116. try {
  43117. const data = JSON.parse(fs$l.readFileSync(dataPath, 'utf-8'));
  43118. knownImports = Object.keys(data.optimized);
  43119. }
  43120. catch (e) { }
  43121. if (!knownImports) {
  43122. // no dev deps optimization data, do a fresh scan
  43123. knownImports = await findKnownImports(config, false); // needs to use non-ssr
  43124. }
  43125. const ssrExternals = cjsSsrResolveExternals(config, knownImports);
  43126. return (id, parentId, isResolved) => {
  43127. const isExternal = cjsShouldExternalizeForSSR(id, ssrExternals);
  43128. if (isExternal) {
  43129. return true;
  43130. }
  43131. if (user) {
  43132. return resolveUserExternal(user, id, parentId, isResolved);
  43133. }
  43134. };
  43135. }
  43136. function resolveUserExternal(user, id, parentId, isResolved) {
  43137. if (typeof user === 'function') {
  43138. return user(id, parentId, isResolved);
  43139. }
  43140. else if (Array.isArray(user)) {
  43141. return user.some((test) => isExternal(id, test));
  43142. }
  43143. else {
  43144. return isExternal(id, user);
  43145. }
  43146. }
  43147. function isExternal(id, test) {
  43148. if (typeof test === 'string') {
  43149. return id === test;
  43150. }
  43151. else {
  43152. return test.test(id);
  43153. }
  43154. }
  43155. function injectSsrFlagToHooks(plugin) {
  43156. const { resolveId, load, transform } = plugin;
  43157. return {
  43158. ...plugin,
  43159. resolveId: wrapSsrResolveId(resolveId),
  43160. load: wrapSsrLoad(load),
  43161. transform: wrapSsrTransform(transform),
  43162. };
  43163. }
  43164. function wrapSsrResolveId(hook) {
  43165. if (!hook)
  43166. return;
  43167. const fn = 'handler' in hook ? hook.handler : hook;
  43168. const handler = function (id, importer, options) {
  43169. return fn.call(this, id, importer, injectSsrFlag(options));
  43170. };
  43171. if ('handler' in hook) {
  43172. return {
  43173. ...hook,
  43174. handler,
  43175. };
  43176. }
  43177. else {
  43178. return handler;
  43179. }
  43180. }
  43181. function wrapSsrLoad(hook) {
  43182. if (!hook)
  43183. return;
  43184. const fn = 'handler' in hook ? hook.handler : hook;
  43185. const handler = function (id, ...args) {
  43186. // @ts-expect-error: Receiving options param to be future-proof if Rollup adds it
  43187. return fn.call(this, id, injectSsrFlag(args[0]));
  43188. };
  43189. if ('handler' in hook) {
  43190. return {
  43191. ...hook,
  43192. handler,
  43193. };
  43194. }
  43195. else {
  43196. return handler;
  43197. }
  43198. }
  43199. function wrapSsrTransform(hook) {
  43200. if (!hook)
  43201. return;
  43202. const fn = 'handler' in hook ? hook.handler : hook;
  43203. const handler = function (code, importer, ...args) {
  43204. // @ts-expect-error: Receiving options param to be future-proof if Rollup adds it
  43205. return fn.call(this, code, importer, injectSsrFlag(args[0]));
  43206. };
  43207. if ('handler' in hook) {
  43208. return {
  43209. ...hook,
  43210. handler,
  43211. };
  43212. }
  43213. else {
  43214. return handler;
  43215. }
  43216. }
  43217. function injectSsrFlag(options) {
  43218. return { ...(options ?? {}), ssr: true };
  43219. }
  43220. /*
  43221. The following functions are copied from rollup
  43222. https://github.com/rollup/rollup/blob/0bcf0a672ac087ff2eb88fbba45ec62389a4f45f/src/ast/nodes/MetaProperty.ts#L145-L193
  43223. https://github.com/rollup/rollup
  43224. The MIT License (MIT)
  43225. Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/contributors)
  43226. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  43227. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  43228. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  43229. */
  43230. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  43231. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  43232. const backSlashRegEx = /\\/g;
  43233. function escapeId(id) {
  43234. if (!needsEscapeRegEx.test(id))
  43235. return id;
  43236. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  43237. }
  43238. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  43239. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  43240. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  43241. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${path}'`);
  43242. const relativeUrlMechanisms = {
  43243. amd: (relativePath) => {
  43244. if (relativePath[0] !== '.')
  43245. relativePath = './' + relativePath;
  43246. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  43247. },
  43248. cjs: (relativePath) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  43249. es: (relativePath) => getResolveUrl(`'${relativePath}', import.meta.url`),
  43250. iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
  43251. // NOTE: make sure rollup generate `module` params
  43252. system: (relativePath) => getResolveUrl(`'${relativePath}', module.meta.url`),
  43253. umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`,
  43254. };
  43255. /* end of copy */
  43256. const customRelativeUrlMechanisms = {
  43257. ...relativeUrlMechanisms,
  43258. 'worker-iife': (relativePath) => getResolveUrl(`'${relativePath}', self.location.href`),
  43259. };
  43260. function toOutputFilePathInJS(filename, type, hostId, hostType, config, toRelative) {
  43261. const { renderBuiltUrl } = config.experimental;
  43262. let relative = config.base === '' || config.base === './';
  43263. if (renderBuiltUrl) {
  43264. const result = renderBuiltUrl(filename, {
  43265. hostId,
  43266. hostType,
  43267. type,
  43268. ssr: !!config.build.ssr,
  43269. });
  43270. if (typeof result === 'object') {
  43271. if (result.runtime) {
  43272. return { runtime: result.runtime };
  43273. }
  43274. if (typeof result.relative === 'boolean') {
  43275. relative = result.relative;
  43276. }
  43277. }
  43278. else if (result) {
  43279. return result;
  43280. }
  43281. }
  43282. if (relative && !config.build.ssr) {
  43283. return toRelative(filename, hostId);
  43284. }
  43285. return joinUrlSegments(config.base, filename);
  43286. }
  43287. function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
  43288. const formatLong = isWorker && format === 'iife' ? 'worker-iife' : format;
  43289. const toRelativePath = customRelativeUrlMechanisms[formatLong];
  43290. return (filename, importer) => ({
  43291. runtime: toRelativePath(path$o.posix.relative(path$o.dirname(importer), filename)),
  43292. });
  43293. }
  43294. function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
  43295. const { renderBuiltUrl } = config.experimental;
  43296. let relative = config.base === '' || config.base === './';
  43297. if (renderBuiltUrl) {
  43298. const result = renderBuiltUrl(filename, {
  43299. hostId,
  43300. hostType,
  43301. type,
  43302. ssr: !!config.build.ssr,
  43303. });
  43304. if (typeof result === 'object') {
  43305. if (result.runtime) {
  43306. throw new Error(`{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`);
  43307. }
  43308. if (typeof result.relative === 'boolean') {
  43309. relative = result.relative;
  43310. }
  43311. }
  43312. else if (result) {
  43313. return result;
  43314. }
  43315. }
  43316. if (relative && !config.build.ssr) {
  43317. return toRelative(filename, hostId);
  43318. }
  43319. else {
  43320. return joinUrlSegments(config.base, filename);
  43321. }
  43322. }
  43323. const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
  43324. const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
  43325. var build$1 = {
  43326. __proto__: null,
  43327. build: build,
  43328. createToImportMetaURLBasedRelativeRuntime: createToImportMetaURLBasedRelativeRuntime,
  43329. onRollupWarning: onRollupWarning,
  43330. resolveBuildOptions: resolveBuildOptions,
  43331. resolveBuildOutputs: resolveBuildOutputs,
  43332. resolveBuildPlugins: resolveBuildPlugins,
  43333. resolveLibFilename: resolveLibFilename,
  43334. resolveUserExternal: resolveUserExternal,
  43335. toOutputFilePathInCss: toOutputFilePathInCss,
  43336. toOutputFilePathInHtml: toOutputFilePathInHtml,
  43337. toOutputFilePathInJS: toOutputFilePathInJS,
  43338. toOutputFilePathWithoutRuntime: toOutputFilePathWithoutRuntime
  43339. };
  43340. var src = {exports: {}};
  43341. var browser = {exports: {}};
  43342. var debug$6 = {exports: {}};
  43343. /**
  43344. * Helpers.
  43345. */
  43346. var ms;
  43347. var hasRequiredMs;
  43348. function requireMs () {
  43349. if (hasRequiredMs) return ms;
  43350. hasRequiredMs = 1;
  43351. var s = 1000;
  43352. var m = s * 60;
  43353. var h = m * 60;
  43354. var d = h * 24;
  43355. var y = d * 365.25;
  43356. /**
  43357. * Parse or format the given `val`.
  43358. *
  43359. * Options:
  43360. *
  43361. * - `long` verbose formatting [false]
  43362. *
  43363. * @param {String|Number} val
  43364. * @param {Object} [options]
  43365. * @throws {Error} throw an error if val is not a non-empty string or a number
  43366. * @return {String|Number}
  43367. * @api public
  43368. */
  43369. ms = function(val, options) {
  43370. options = options || {};
  43371. var type = typeof val;
  43372. if (type === 'string' && val.length > 0) {
  43373. return parse(val);
  43374. } else if (type === 'number' && isNaN(val) === false) {
  43375. return options.long ? fmtLong(val) : fmtShort(val);
  43376. }
  43377. throw new Error(
  43378. 'val is not a non-empty string or a valid number. val=' +
  43379. JSON.stringify(val)
  43380. );
  43381. };
  43382. /**
  43383. * Parse the given `str` and return milliseconds.
  43384. *
  43385. * @param {String} str
  43386. * @return {Number}
  43387. * @api private
  43388. */
  43389. function parse(str) {
  43390. str = String(str);
  43391. if (str.length > 100) {
  43392. return;
  43393. }
  43394. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
  43395. str
  43396. );
  43397. if (!match) {
  43398. return;
  43399. }
  43400. var n = parseFloat(match[1]);
  43401. var type = (match[2] || 'ms').toLowerCase();
  43402. switch (type) {
  43403. case 'years':
  43404. case 'year':
  43405. case 'yrs':
  43406. case 'yr':
  43407. case 'y':
  43408. return n * y;
  43409. case 'days':
  43410. case 'day':
  43411. case 'd':
  43412. return n * d;
  43413. case 'hours':
  43414. case 'hour':
  43415. case 'hrs':
  43416. case 'hr':
  43417. case 'h':
  43418. return n * h;
  43419. case 'minutes':
  43420. case 'minute':
  43421. case 'mins':
  43422. case 'min':
  43423. case 'm':
  43424. return n * m;
  43425. case 'seconds':
  43426. case 'second':
  43427. case 'secs':
  43428. case 'sec':
  43429. case 's':
  43430. return n * s;
  43431. case 'milliseconds':
  43432. case 'millisecond':
  43433. case 'msecs':
  43434. case 'msec':
  43435. case 'ms':
  43436. return n;
  43437. default:
  43438. return undefined;
  43439. }
  43440. }
  43441. /**
  43442. * Short format for `ms`.
  43443. *
  43444. * @param {Number} ms
  43445. * @return {String}
  43446. * @api private
  43447. */
  43448. function fmtShort(ms) {
  43449. if (ms >= d) {
  43450. return Math.round(ms / d) + 'd';
  43451. }
  43452. if (ms >= h) {
  43453. return Math.round(ms / h) + 'h';
  43454. }
  43455. if (ms >= m) {
  43456. return Math.round(ms / m) + 'm';
  43457. }
  43458. if (ms >= s) {
  43459. return Math.round(ms / s) + 's';
  43460. }
  43461. return ms + 'ms';
  43462. }
  43463. /**
  43464. * Long format for `ms`.
  43465. *
  43466. * @param {Number} ms
  43467. * @return {String}
  43468. * @api private
  43469. */
  43470. function fmtLong(ms) {
  43471. return plural(ms, d, 'day') ||
  43472. plural(ms, h, 'hour') ||
  43473. plural(ms, m, 'minute') ||
  43474. plural(ms, s, 'second') ||
  43475. ms + ' ms';
  43476. }
  43477. /**
  43478. * Pluralization helper.
  43479. */
  43480. function plural(ms, n, name) {
  43481. if (ms < n) {
  43482. return;
  43483. }
  43484. if (ms < n * 1.5) {
  43485. return Math.floor(ms / n) + ' ' + name;
  43486. }
  43487. return Math.ceil(ms / n) + ' ' + name + 's';
  43488. }
  43489. return ms;
  43490. }
  43491. var hasRequiredDebug;
  43492. function requireDebug () {
  43493. if (hasRequiredDebug) return debug$6.exports;
  43494. hasRequiredDebug = 1;
  43495. (function (module, exports) {
  43496. /**
  43497. * This is the common logic for both the Node.js and web browser
  43498. * implementations of `debug()`.
  43499. *
  43500. * Expose `debug()` as the module.
  43501. */
  43502. exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
  43503. exports.coerce = coerce;
  43504. exports.disable = disable;
  43505. exports.enable = enable;
  43506. exports.enabled = enabled;
  43507. exports.humanize = requireMs();
  43508. /**
  43509. * The currently active debug mode names, and names to skip.
  43510. */
  43511. exports.names = [];
  43512. exports.skips = [];
  43513. /**
  43514. * Map of special "%n" handling functions, for the debug "format" argument.
  43515. *
  43516. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  43517. */
  43518. exports.formatters = {};
  43519. /**
  43520. * Previous log timestamp.
  43521. */
  43522. var prevTime;
  43523. /**
  43524. * Select a color.
  43525. * @param {String} namespace
  43526. * @return {Number}
  43527. * @api private
  43528. */
  43529. function selectColor(namespace) {
  43530. var hash = 0, i;
  43531. for (i in namespace) {
  43532. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  43533. hash |= 0; // Convert to 32bit integer
  43534. }
  43535. return exports.colors[Math.abs(hash) % exports.colors.length];
  43536. }
  43537. /**
  43538. * Create a debugger with the given `namespace`.
  43539. *
  43540. * @param {String} namespace
  43541. * @return {Function}
  43542. * @api public
  43543. */
  43544. function createDebug(namespace) {
  43545. function debug() {
  43546. // disabled?
  43547. if (!debug.enabled) return;
  43548. var self = debug;
  43549. // set `diff` timestamp
  43550. var curr = +new Date();
  43551. var ms = curr - (prevTime || curr);
  43552. self.diff = ms;
  43553. self.prev = prevTime;
  43554. self.curr = curr;
  43555. prevTime = curr;
  43556. // turn the `arguments` into a proper Array
  43557. var args = new Array(arguments.length);
  43558. for (var i = 0; i < args.length; i++) {
  43559. args[i] = arguments[i];
  43560. }
  43561. args[0] = exports.coerce(args[0]);
  43562. if ('string' !== typeof args[0]) {
  43563. // anything else let's inspect with %O
  43564. args.unshift('%O');
  43565. }
  43566. // apply any `formatters` transformations
  43567. var index = 0;
  43568. args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
  43569. // if we encounter an escaped % then don't increase the array index
  43570. if (match === '%%') return match;
  43571. index++;
  43572. var formatter = exports.formatters[format];
  43573. if ('function' === typeof formatter) {
  43574. var val = args[index];
  43575. match = formatter.call(self, val);
  43576. // now we need to remove `args[index]` since it's inlined in the `format`
  43577. args.splice(index, 1);
  43578. index--;
  43579. }
  43580. return match;
  43581. });
  43582. // apply env-specific formatting (colors, etc.)
  43583. exports.formatArgs.call(self, args);
  43584. var logFn = debug.log || exports.log || console.log.bind(console);
  43585. logFn.apply(self, args);
  43586. }
  43587. debug.namespace = namespace;
  43588. debug.enabled = exports.enabled(namespace);
  43589. debug.useColors = exports.useColors();
  43590. debug.color = selectColor(namespace);
  43591. // env-specific initialization logic for debug instances
  43592. if ('function' === typeof exports.init) {
  43593. exports.init(debug);
  43594. }
  43595. return debug;
  43596. }
  43597. /**
  43598. * Enables a debug mode by namespaces. This can include modes
  43599. * separated by a colon and wildcards.
  43600. *
  43601. * @param {String} namespaces
  43602. * @api public
  43603. */
  43604. function enable(namespaces) {
  43605. exports.save(namespaces);
  43606. exports.names = [];
  43607. exports.skips = [];
  43608. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  43609. var len = split.length;
  43610. for (var i = 0; i < len; i++) {
  43611. if (!split[i]) continue; // ignore empty strings
  43612. namespaces = split[i].replace(/\*/g, '.*?');
  43613. if (namespaces[0] === '-') {
  43614. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  43615. } else {
  43616. exports.names.push(new RegExp('^' + namespaces + '$'));
  43617. }
  43618. }
  43619. }
  43620. /**
  43621. * Disable debug output.
  43622. *
  43623. * @api public
  43624. */
  43625. function disable() {
  43626. exports.enable('');
  43627. }
  43628. /**
  43629. * Returns true if the given mode name is enabled, false otherwise.
  43630. *
  43631. * @param {String} name
  43632. * @return {Boolean}
  43633. * @api public
  43634. */
  43635. function enabled(name) {
  43636. var i, len;
  43637. for (i = 0, len = exports.skips.length; i < len; i++) {
  43638. if (exports.skips[i].test(name)) {
  43639. return false;
  43640. }
  43641. }
  43642. for (i = 0, len = exports.names.length; i < len; i++) {
  43643. if (exports.names[i].test(name)) {
  43644. return true;
  43645. }
  43646. }
  43647. return false;
  43648. }
  43649. /**
  43650. * Coerce `val`.
  43651. *
  43652. * @param {Mixed} val
  43653. * @return {Mixed}
  43654. * @api private
  43655. */
  43656. function coerce(val) {
  43657. if (val instanceof Error) return val.stack || val.message;
  43658. return val;
  43659. }
  43660. } (debug$6, debug$6.exports));
  43661. return debug$6.exports;
  43662. }
  43663. /**
  43664. * This is the web browser implementation of `debug()`.
  43665. *
  43666. * Expose `debug()` as the module.
  43667. */
  43668. var hasRequiredBrowser;
  43669. function requireBrowser () {
  43670. if (hasRequiredBrowser) return browser.exports;
  43671. hasRequiredBrowser = 1;
  43672. (function (module, exports) {
  43673. exports = module.exports = requireDebug();
  43674. exports.log = log;
  43675. exports.formatArgs = formatArgs;
  43676. exports.save = save;
  43677. exports.load = load;
  43678. exports.useColors = useColors;
  43679. exports.storage = 'undefined' != typeof chrome
  43680. && 'undefined' != typeof chrome.storage
  43681. ? chrome.storage.local
  43682. : localstorage();
  43683. /**
  43684. * Colors.
  43685. */
  43686. exports.colors = [
  43687. 'lightseagreen',
  43688. 'forestgreen',
  43689. 'goldenrod',
  43690. 'dodgerblue',
  43691. 'darkorchid',
  43692. 'crimson'
  43693. ];
  43694. /**
  43695. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  43696. * and the Firebug extension (any Firefox version) are known
  43697. * to support "%c" CSS customizations.
  43698. *
  43699. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  43700. */
  43701. function useColors() {
  43702. // NB: In an Electron preload script, document will be defined but not fully
  43703. // initialized. Since we know we're in Chrome, we'll just detect this case
  43704. // explicitly
  43705. if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
  43706. return true;
  43707. }
  43708. // is webkit? http://stackoverflow.com/a/16459606/376773
  43709. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  43710. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  43711. // is firebug? http://stackoverflow.com/a/398120/376773
  43712. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  43713. // is firefox >= v31?
  43714. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  43715. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  43716. // double check webkit in userAgent just in case we are in a worker
  43717. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  43718. }
  43719. /**
  43720. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  43721. */
  43722. exports.formatters.j = function(v) {
  43723. try {
  43724. return JSON.stringify(v);
  43725. } catch (err) {
  43726. return '[UnexpectedJSONParseError]: ' + err.message;
  43727. }
  43728. };
  43729. /**
  43730. * Colorize log arguments if enabled.
  43731. *
  43732. * @api public
  43733. */
  43734. function formatArgs(args) {
  43735. var useColors = this.useColors;
  43736. args[0] = (useColors ? '%c' : '')
  43737. + this.namespace
  43738. + (useColors ? ' %c' : ' ')
  43739. + args[0]
  43740. + (useColors ? '%c ' : ' ')
  43741. + '+' + exports.humanize(this.diff);
  43742. if (!useColors) return;
  43743. var c = 'color: ' + this.color;
  43744. args.splice(1, 0, c, 'color: inherit');
  43745. // the final "%c" is somewhat tricky, because there could be other
  43746. // arguments passed either before or after the %c, so we need to
  43747. // figure out the correct index to insert the CSS into
  43748. var index = 0;
  43749. var lastC = 0;
  43750. args[0].replace(/%[a-zA-Z%]/g, function(match) {
  43751. if ('%%' === match) return;
  43752. index++;
  43753. if ('%c' === match) {
  43754. // we only are interested in the *last* %c
  43755. // (the user may have provided their own)
  43756. lastC = index;
  43757. }
  43758. });
  43759. args.splice(lastC, 0, c);
  43760. }
  43761. /**
  43762. * Invokes `console.log()` when available.
  43763. * No-op when `console.log` is not a "function".
  43764. *
  43765. * @api public
  43766. */
  43767. function log() {
  43768. // this hackery is required for IE8/9, where
  43769. // the `console.log` function doesn't have 'apply'
  43770. return 'object' === typeof console
  43771. && console.log
  43772. && Function.prototype.apply.call(console.log, console, arguments);
  43773. }
  43774. /**
  43775. * Save `namespaces`.
  43776. *
  43777. * @param {String} namespaces
  43778. * @api private
  43779. */
  43780. function save(namespaces) {
  43781. try {
  43782. if (null == namespaces) {
  43783. exports.storage.removeItem('debug');
  43784. } else {
  43785. exports.storage.debug = namespaces;
  43786. }
  43787. } catch(e) {}
  43788. }
  43789. /**
  43790. * Load `namespaces`.
  43791. *
  43792. * @return {String} returns the previously persisted debug modes
  43793. * @api private
  43794. */
  43795. function load() {
  43796. var r;
  43797. try {
  43798. r = exports.storage.debug;
  43799. } catch(e) {}
  43800. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  43801. if (!r && typeof process !== 'undefined' && 'env' in process) {
  43802. r = process.env.DEBUG;
  43803. }
  43804. return r;
  43805. }
  43806. /**
  43807. * Enable namespaces listed in `localStorage.debug` initially.
  43808. */
  43809. exports.enable(load());
  43810. /**
  43811. * Localstorage attempts to return the localstorage.
  43812. *
  43813. * This is necessary because safari throws
  43814. * when a user disables cookies/localstorage
  43815. * and you attempt to access it.
  43816. *
  43817. * @return {LocalStorage}
  43818. * @api private
  43819. */
  43820. function localstorage() {
  43821. try {
  43822. return window.localStorage;
  43823. } catch (e) {}
  43824. }
  43825. } (browser, browser.exports));
  43826. return browser.exports;
  43827. }
  43828. var node = {exports: {}};
  43829. /**
  43830. * Module dependencies.
  43831. */
  43832. var hasRequiredNode;
  43833. function requireNode () {
  43834. if (hasRequiredNode) return node.exports;
  43835. hasRequiredNode = 1;
  43836. (function (module, exports) {
  43837. var tty = require$$0$3;
  43838. var util = require$$0$6;
  43839. /**
  43840. * This is the Node.js implementation of `debug()`.
  43841. *
  43842. * Expose `debug()` as the module.
  43843. */
  43844. exports = module.exports = requireDebug();
  43845. exports.init = init;
  43846. exports.log = log;
  43847. exports.formatArgs = formatArgs;
  43848. exports.save = save;
  43849. exports.load = load;
  43850. exports.useColors = useColors;
  43851. /**
  43852. * Colors.
  43853. */
  43854. exports.colors = [6, 2, 3, 4, 5, 1];
  43855. /**
  43856. * Build up the default `inspectOpts` object from the environment variables.
  43857. *
  43858. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  43859. */
  43860. exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  43861. return /^debug_/i.test(key);
  43862. }).reduce(function (obj, key) {
  43863. // camel-case
  43864. var prop = key
  43865. .substring(6)
  43866. .toLowerCase()
  43867. .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
  43868. // coerce string value into JS value
  43869. var val = process.env[key];
  43870. if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  43871. else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  43872. else if (val === 'null') val = null;
  43873. else val = Number(val);
  43874. obj[prop] = val;
  43875. return obj;
  43876. }, {});
  43877. /**
  43878. * The file descriptor to write the `debug()` calls to.
  43879. * Set the `DEBUG_FD` env variable to override with another value. i.e.:
  43880. *
  43881. * $ DEBUG_FD=3 node script.js 3>debug.log
  43882. */
  43883. var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
  43884. if (1 !== fd && 2 !== fd) {
  43885. util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
  43886. }
  43887. var stream = 1 === fd ? process.stdout :
  43888. 2 === fd ? process.stderr :
  43889. createWritableStdioStream(fd);
  43890. /**
  43891. * Is stdout a TTY? Colored output is enabled when `true`.
  43892. */
  43893. function useColors() {
  43894. return 'colors' in exports.inspectOpts
  43895. ? Boolean(exports.inspectOpts.colors)
  43896. : tty.isatty(fd);
  43897. }
  43898. /**
  43899. * Map %o to `util.inspect()`, all on a single line.
  43900. */
  43901. exports.formatters.o = function(v) {
  43902. this.inspectOpts.colors = this.useColors;
  43903. return util.inspect(v, this.inspectOpts)
  43904. .split('\n').map(function(str) {
  43905. return str.trim()
  43906. }).join(' ');
  43907. };
  43908. /**
  43909. * Map %o to `util.inspect()`, allowing multiple lines if needed.
  43910. */
  43911. exports.formatters.O = function(v) {
  43912. this.inspectOpts.colors = this.useColors;
  43913. return util.inspect(v, this.inspectOpts);
  43914. };
  43915. /**
  43916. * Adds ANSI color escape codes if enabled.
  43917. *
  43918. * @api public
  43919. */
  43920. function formatArgs(args) {
  43921. var name = this.namespace;
  43922. var useColors = this.useColors;
  43923. if (useColors) {
  43924. var c = this.color;
  43925. var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
  43926. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  43927. args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  43928. } else {
  43929. args[0] = new Date().toUTCString()
  43930. + ' ' + name + ' ' + args[0];
  43931. }
  43932. }
  43933. /**
  43934. * Invokes `util.format()` with the specified arguments and writes to `stream`.
  43935. */
  43936. function log() {
  43937. return stream.write(util.format.apply(util, arguments) + '\n');
  43938. }
  43939. /**
  43940. * Save `namespaces`.
  43941. *
  43942. * @param {String} namespaces
  43943. * @api private
  43944. */
  43945. function save(namespaces) {
  43946. if (null == namespaces) {
  43947. // If you set a process.env field to null or undefined, it gets cast to the
  43948. // string 'null' or 'undefined'. Just delete instead.
  43949. delete process.env.DEBUG;
  43950. } else {
  43951. process.env.DEBUG = namespaces;
  43952. }
  43953. }
  43954. /**
  43955. * Load `namespaces`.
  43956. *
  43957. * @return {String} returns the previously persisted debug modes
  43958. * @api private
  43959. */
  43960. function load() {
  43961. return process.env.DEBUG;
  43962. }
  43963. /**
  43964. * Copied from `node/src/node.js`.
  43965. *
  43966. * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
  43967. * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
  43968. */
  43969. function createWritableStdioStream (fd) {
  43970. var stream;
  43971. var tty_wrap = process.binding('tty_wrap');
  43972. // Note stream._type is used for test-module-load-list.js
  43973. switch (tty_wrap.guessHandleType(fd)) {
  43974. case 'TTY':
  43975. stream = new tty.WriteStream(fd);
  43976. stream._type = 'tty';
  43977. // Hack to have stream not keep the event loop alive.
  43978. // See https://github.com/joyent/node/issues/1726
  43979. if (stream._handle && stream._handle.unref) {
  43980. stream._handle.unref();
  43981. }
  43982. break;
  43983. case 'FILE':
  43984. var fs = require$$0__default;
  43985. stream = new fs.SyncWriteStream(fd, { autoClose: false });
  43986. stream._type = 'fs';
  43987. break;
  43988. case 'PIPE':
  43989. case 'TCP':
  43990. var net = require$$3$2;
  43991. stream = new net.Socket({
  43992. fd: fd,
  43993. readable: false,
  43994. writable: true
  43995. });
  43996. // FIXME Should probably have an option in net.Socket to create a
  43997. // stream from an existing fd which is writable only. But for now
  43998. // we'll just add this hack and set the `readable` member to false.
  43999. // Test: ./node test/fixtures/echo.js < /etc/passwd
  44000. stream.readable = false;
  44001. stream.read = null;
  44002. stream._type = 'pipe';
  44003. // FIXME Hack to have stream not keep the event loop alive.
  44004. // See https://github.com/joyent/node/issues/1726
  44005. if (stream._handle && stream._handle.unref) {
  44006. stream._handle.unref();
  44007. }
  44008. break;
  44009. default:
  44010. // Probably an error on in uv_guess_handle()
  44011. throw new Error('Implement me. Unknown stream file type!');
  44012. }
  44013. // For supporting legacy API we put the FD here.
  44014. stream.fd = fd;
  44015. stream._isStdio = true;
  44016. return stream;
  44017. }
  44018. /**
  44019. * Init logic for `debug` instances.
  44020. *
  44021. * Create a new `inspectOpts` object in case `useColors` is set
  44022. * differently for a particular `debug` instance.
  44023. */
  44024. function init (debug) {
  44025. debug.inspectOpts = {};
  44026. var keys = Object.keys(exports.inspectOpts);
  44027. for (var i = 0; i < keys.length; i++) {
  44028. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  44029. }
  44030. }
  44031. /**
  44032. * Enable namespaces listed in `process.env.DEBUG` initially.
  44033. */
  44034. exports.enable(load());
  44035. } (node, node.exports));
  44036. return node.exports;
  44037. }
  44038. /**
  44039. * Detect Electron renderer process, which is node, but we should
  44040. * treat as a browser.
  44041. */
  44042. if (typeof process !== 'undefined' && process.type === 'renderer') {
  44043. src.exports = requireBrowser();
  44044. } else {
  44045. src.exports = requireNode();
  44046. }
  44047. var srcExports = src.exports;
  44048. /*!
  44049. * encodeurl
  44050. * Copyright(c) 2016 Douglas Christopher Wilson
  44051. * MIT Licensed
  44052. */
  44053. /**
  44054. * Module exports.
  44055. * @public
  44056. */
  44057. var encodeurl = encodeUrl$1;
  44058. /**
  44059. * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
  44060. * and including invalid escape sequences.
  44061. * @private
  44062. */
  44063. var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
  44064. /**
  44065. * RegExp to match unmatched surrogate pair.
  44066. * @private
  44067. */
  44068. var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
  44069. /**
  44070. * String to replace unmatched surrogate pair with.
  44071. * @private
  44072. */
  44073. var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2';
  44074. /**
  44075. * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
  44076. *
  44077. * This function will take an already-encoded URL and encode all the non-URL
  44078. * code points. This function will not encode the "%" character unless it is
  44079. * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
  44080. * be encoded as `%25foo`).
  44081. *
  44082. * This encode is meant to be "safe" and does not throw errors. It will try as
  44083. * hard as it can to properly encode the given URL, including replacing any raw,
  44084. * unpaired surrogate pairs with the Unicode replacement character prior to
  44085. * encoding.
  44086. *
  44087. * @param {string} url
  44088. * @return {string}
  44089. * @public
  44090. */
  44091. function encodeUrl$1 (url) {
  44092. return String(url)
  44093. .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)
  44094. .replace(ENCODE_CHARS_REGEXP, encodeURI)
  44095. }
  44096. var onFinished$2 = {exports: {}};
  44097. /*!
  44098. * ee-first
  44099. * Copyright(c) 2014 Jonathan Ong
  44100. * MIT Licensed
  44101. */
  44102. /**
  44103. * Module exports.
  44104. * @public
  44105. */
  44106. var eeFirst = first$1;
  44107. /**
  44108. * Get the first event in a set of event emitters and event pairs.
  44109. *
  44110. * @param {array} stuff
  44111. * @param {function} done
  44112. * @public
  44113. */
  44114. function first$1(stuff, done) {
  44115. if (!Array.isArray(stuff))
  44116. throw new TypeError('arg must be an array of [ee, events...] arrays')
  44117. var cleanups = [];
  44118. for (var i = 0; i < stuff.length; i++) {
  44119. var arr = stuff[i];
  44120. if (!Array.isArray(arr) || arr.length < 2)
  44121. throw new TypeError('each array member must be [ee, events...]')
  44122. var ee = arr[0];
  44123. for (var j = 1; j < arr.length; j++) {
  44124. var event = arr[j];
  44125. var fn = listener(event, callback);
  44126. // listen to the event
  44127. ee.on(event, fn);
  44128. // push this listener to the list of cleanups
  44129. cleanups.push({
  44130. ee: ee,
  44131. event: event,
  44132. fn: fn,
  44133. });
  44134. }
  44135. }
  44136. function callback() {
  44137. cleanup();
  44138. done.apply(null, arguments);
  44139. }
  44140. function cleanup() {
  44141. var x;
  44142. for (var i = 0; i < cleanups.length; i++) {
  44143. x = cleanups[i];
  44144. x.ee.removeListener(x.event, x.fn);
  44145. }
  44146. }
  44147. function thunk(fn) {
  44148. done = fn;
  44149. }
  44150. thunk.cancel = cleanup;
  44151. return thunk
  44152. }
  44153. /**
  44154. * Create the event listener.
  44155. * @private
  44156. */
  44157. function listener(event, done) {
  44158. return function onevent(arg1) {
  44159. var args = new Array(arguments.length);
  44160. var ee = this;
  44161. var err = event === 'error'
  44162. ? arg1
  44163. : null;
  44164. // copy args to prevent arguments escaping scope
  44165. for (var i = 0; i < args.length; i++) {
  44166. args[i] = arguments[i];
  44167. }
  44168. done(err, ee, event, args);
  44169. }
  44170. }
  44171. /*!
  44172. * on-finished
  44173. * Copyright(c) 2013 Jonathan Ong
  44174. * Copyright(c) 2014 Douglas Christopher Wilson
  44175. * MIT Licensed
  44176. */
  44177. /**
  44178. * Module exports.
  44179. * @public
  44180. */
  44181. onFinished$2.exports = onFinished$1;
  44182. onFinished$2.exports.isFinished = isFinished$1;
  44183. /**
  44184. * Module dependencies.
  44185. * @private
  44186. */
  44187. var first = eeFirst;
  44188. /**
  44189. * Variables.
  44190. * @private
  44191. */
  44192. /* istanbul ignore next */
  44193. var defer$2 = typeof setImmediate === 'function'
  44194. ? setImmediate
  44195. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  44196. /**
  44197. * Invoke callback when the response has finished, useful for
  44198. * cleaning up resources afterwards.
  44199. *
  44200. * @param {object} msg
  44201. * @param {function} listener
  44202. * @return {object}
  44203. * @public
  44204. */
  44205. function onFinished$1(msg, listener) {
  44206. if (isFinished$1(msg) !== false) {
  44207. defer$2(listener, null, msg);
  44208. return msg
  44209. }
  44210. // attach the listener to the message
  44211. attachListener(msg, listener);
  44212. return msg
  44213. }
  44214. /**
  44215. * Determine if message is already finished.
  44216. *
  44217. * @param {object} msg
  44218. * @return {boolean}
  44219. * @public
  44220. */
  44221. function isFinished$1(msg) {
  44222. var socket = msg.socket;
  44223. if (typeof msg.finished === 'boolean') {
  44224. // OutgoingMessage
  44225. return Boolean(msg.finished || (socket && !socket.writable))
  44226. }
  44227. if (typeof msg.complete === 'boolean') {
  44228. // IncomingMessage
  44229. return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
  44230. }
  44231. // don't know
  44232. return undefined
  44233. }
  44234. /**
  44235. * Attach a finished listener to the message.
  44236. *
  44237. * @param {object} msg
  44238. * @param {function} callback
  44239. * @private
  44240. */
  44241. function attachFinishedListener(msg, callback) {
  44242. var eeMsg;
  44243. var eeSocket;
  44244. var finished = false;
  44245. function onFinish(error) {
  44246. eeMsg.cancel();
  44247. eeSocket.cancel();
  44248. finished = true;
  44249. callback(error);
  44250. }
  44251. // finished on first message event
  44252. eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish);
  44253. function onSocket(socket) {
  44254. // remove listener
  44255. msg.removeListener('socket', onSocket);
  44256. if (finished) return
  44257. if (eeMsg !== eeSocket) return
  44258. // finished on first socket event
  44259. eeSocket = first([[socket, 'error', 'close']], onFinish);
  44260. }
  44261. if (msg.socket) {
  44262. // socket already assigned
  44263. onSocket(msg.socket);
  44264. return
  44265. }
  44266. // wait for socket to be assigned
  44267. msg.on('socket', onSocket);
  44268. if (msg.socket === undefined) {
  44269. // node.js 0.8 patch
  44270. patchAssignSocket(msg, onSocket);
  44271. }
  44272. }
  44273. /**
  44274. * Attach the listener to the message.
  44275. *
  44276. * @param {object} msg
  44277. * @return {function}
  44278. * @private
  44279. */
  44280. function attachListener(msg, listener) {
  44281. var attached = msg.__onFinished;
  44282. // create a private single listener with queue
  44283. if (!attached || !attached.queue) {
  44284. attached = msg.__onFinished = createListener(msg);
  44285. attachFinishedListener(msg, attached);
  44286. }
  44287. attached.queue.push(listener);
  44288. }
  44289. /**
  44290. * Create listener on message.
  44291. *
  44292. * @param {object} msg
  44293. * @return {function}
  44294. * @private
  44295. */
  44296. function createListener(msg) {
  44297. function listener(err) {
  44298. if (msg.__onFinished === listener) msg.__onFinished = null;
  44299. if (!listener.queue) return
  44300. var queue = listener.queue;
  44301. listener.queue = null;
  44302. for (var i = 0; i < queue.length; i++) {
  44303. queue[i](err, msg);
  44304. }
  44305. }
  44306. listener.queue = [];
  44307. return listener
  44308. }
  44309. /**
  44310. * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
  44311. *
  44312. * @param {ServerResponse} res
  44313. * @param {function} callback
  44314. * @private
  44315. */
  44316. function patchAssignSocket(res, callback) {
  44317. var assignSocket = res.assignSocket;
  44318. if (typeof assignSocket !== 'function') return
  44319. // res.on('socket', callback) is broken in 0.8
  44320. res.assignSocket = function _assignSocket(socket) {
  44321. assignSocket.call(this, socket);
  44322. callback(socket);
  44323. };
  44324. }
  44325. var onFinishedExports = onFinished$2.exports;
  44326. var parseurl$1 = {exports: {}};
  44327. /*!
  44328. * parseurl
  44329. * Copyright(c) 2014 Jonathan Ong
  44330. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  44331. * MIT Licensed
  44332. */
  44333. /**
  44334. * Module dependencies.
  44335. * @private
  44336. */
  44337. var url$3 = require$$0$9;
  44338. var parse$7 = url$3.parse;
  44339. var Url = url$3.Url;
  44340. /**
  44341. * Module exports.
  44342. * @public
  44343. */
  44344. parseurl$1.exports = parseurl;
  44345. parseurl$1.exports.original = originalurl;
  44346. /**
  44347. * Parse the `req` url with memoization.
  44348. *
  44349. * @param {ServerRequest} req
  44350. * @return {Object}
  44351. * @public
  44352. */
  44353. function parseurl (req) {
  44354. var url = req.url;
  44355. if (url === undefined) {
  44356. // URL is undefined
  44357. return undefined
  44358. }
  44359. var parsed = req._parsedUrl;
  44360. if (fresh(url, parsed)) {
  44361. // Return cached URL parse
  44362. return parsed
  44363. }
  44364. // Parse the URL
  44365. parsed = fastparse(url);
  44366. parsed._raw = url;
  44367. return (req._parsedUrl = parsed)
  44368. }
  44369. /**
  44370. * Parse the `req` original url with fallback and memoization.
  44371. *
  44372. * @param {ServerRequest} req
  44373. * @return {Object}
  44374. * @public
  44375. */
  44376. function originalurl (req) {
  44377. var url = req.originalUrl;
  44378. if (typeof url !== 'string') {
  44379. // Fallback
  44380. return parseurl(req)
  44381. }
  44382. var parsed = req._parsedOriginalUrl;
  44383. if (fresh(url, parsed)) {
  44384. // Return cached URL parse
  44385. return parsed
  44386. }
  44387. // Parse the URL
  44388. parsed = fastparse(url);
  44389. parsed._raw = url;
  44390. return (req._parsedOriginalUrl = parsed)
  44391. }
  44392. /**
  44393. * Parse the `str` url with fast-path short-cut.
  44394. *
  44395. * @param {string} str
  44396. * @return {Object}
  44397. * @private
  44398. */
  44399. function fastparse (str) {
  44400. if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
  44401. return parse$7(str)
  44402. }
  44403. var pathname = str;
  44404. var query = null;
  44405. var search = null;
  44406. // This takes the regexp from https://github.com/joyent/node/pull/7878
  44407. // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/
  44408. // And unrolls it into a for loop
  44409. for (var i = 1; i < str.length; i++) {
  44410. switch (str.charCodeAt(i)) {
  44411. case 0x3f: /* ? */
  44412. if (search === null) {
  44413. pathname = str.substring(0, i);
  44414. query = str.substring(i + 1);
  44415. search = str.substring(i);
  44416. }
  44417. break
  44418. case 0x09: /* \t */
  44419. case 0x0a: /* \n */
  44420. case 0x0c: /* \f */
  44421. case 0x0d: /* \r */
  44422. case 0x20: /* */
  44423. case 0x23: /* # */
  44424. case 0xa0:
  44425. case 0xfeff:
  44426. return parse$7(str)
  44427. }
  44428. }
  44429. var url = Url !== undefined
  44430. ? new Url()
  44431. : {};
  44432. url.path = str;
  44433. url.href = str;
  44434. url.pathname = pathname;
  44435. if (search !== null) {
  44436. url.query = query;
  44437. url.search = search;
  44438. }
  44439. return url
  44440. }
  44441. /**
  44442. * Determine if parsed is still fresh for url.
  44443. *
  44444. * @param {string} url
  44445. * @param {object} parsedUrl
  44446. * @return {boolean}
  44447. * @private
  44448. */
  44449. function fresh (url, parsedUrl) {
  44450. return typeof parsedUrl === 'object' &&
  44451. parsedUrl !== null &&
  44452. (Url === undefined || parsedUrl instanceof Url) &&
  44453. parsedUrl._raw === url
  44454. }
  44455. var parseurlExports = parseurl$1.exports;
  44456. var require$$0$1 = {
  44457. "100": "Continue",
  44458. "101": "Switching Protocols",
  44459. "102": "Processing",
  44460. "103": "Early Hints",
  44461. "200": "OK",
  44462. "201": "Created",
  44463. "202": "Accepted",
  44464. "203": "Non-Authoritative Information",
  44465. "204": "No Content",
  44466. "205": "Reset Content",
  44467. "206": "Partial Content",
  44468. "207": "Multi-Status",
  44469. "208": "Already Reported",
  44470. "226": "IM Used",
  44471. "300": "Multiple Choices",
  44472. "301": "Moved Permanently",
  44473. "302": "Found",
  44474. "303": "See Other",
  44475. "304": "Not Modified",
  44476. "305": "Use Proxy",
  44477. "306": "(Unused)",
  44478. "307": "Temporary Redirect",
  44479. "308": "Permanent Redirect",
  44480. "400": "Bad Request",
  44481. "401": "Unauthorized",
  44482. "402": "Payment Required",
  44483. "403": "Forbidden",
  44484. "404": "Not Found",
  44485. "405": "Method Not Allowed",
  44486. "406": "Not Acceptable",
  44487. "407": "Proxy Authentication Required",
  44488. "408": "Request Timeout",
  44489. "409": "Conflict",
  44490. "410": "Gone",
  44491. "411": "Length Required",
  44492. "412": "Precondition Failed",
  44493. "413": "Payload Too Large",
  44494. "414": "URI Too Long",
  44495. "415": "Unsupported Media Type",
  44496. "416": "Range Not Satisfiable",
  44497. "417": "Expectation Failed",
  44498. "418": "I'm a teapot",
  44499. "421": "Misdirected Request",
  44500. "422": "Unprocessable Entity",
  44501. "423": "Locked",
  44502. "424": "Failed Dependency",
  44503. "425": "Unordered Collection",
  44504. "426": "Upgrade Required",
  44505. "428": "Precondition Required",
  44506. "429": "Too Many Requests",
  44507. "431": "Request Header Fields Too Large",
  44508. "451": "Unavailable For Legal Reasons",
  44509. "500": "Internal Server Error",
  44510. "501": "Not Implemented",
  44511. "502": "Bad Gateway",
  44512. "503": "Service Unavailable",
  44513. "504": "Gateway Timeout",
  44514. "505": "HTTP Version Not Supported",
  44515. "506": "Variant Also Negotiates",
  44516. "507": "Insufficient Storage",
  44517. "508": "Loop Detected",
  44518. "509": "Bandwidth Limit Exceeded",
  44519. "510": "Not Extended",
  44520. "511": "Network Authentication Required"
  44521. };
  44522. /*!
  44523. * statuses
  44524. * Copyright(c) 2014 Jonathan Ong
  44525. * Copyright(c) 2016 Douglas Christopher Wilson
  44526. * MIT Licensed
  44527. */
  44528. /**
  44529. * Module dependencies.
  44530. * @private
  44531. */
  44532. var codes = require$$0$1;
  44533. /**
  44534. * Module exports.
  44535. * @public
  44536. */
  44537. var statuses$1 = status;
  44538. // status code to message map
  44539. status.STATUS_CODES = codes;
  44540. // array of status codes
  44541. status.codes = populateStatusesMap(status, codes);
  44542. // status codes for redirects
  44543. status.redirect = {
  44544. 300: true,
  44545. 301: true,
  44546. 302: true,
  44547. 303: true,
  44548. 305: true,
  44549. 307: true,
  44550. 308: true
  44551. };
  44552. // status codes for empty bodies
  44553. status.empty = {
  44554. 204: true,
  44555. 205: true,
  44556. 304: true
  44557. };
  44558. // status codes for when you should retry the request
  44559. status.retry = {
  44560. 502: true,
  44561. 503: true,
  44562. 504: true
  44563. };
  44564. /**
  44565. * Populate the statuses map for given codes.
  44566. * @private
  44567. */
  44568. function populateStatusesMap (statuses, codes) {
  44569. var arr = [];
  44570. Object.keys(codes).forEach(function forEachCode (code) {
  44571. var message = codes[code];
  44572. var status = Number(code);
  44573. // Populate properties
  44574. statuses[status] = message;
  44575. statuses[message] = status;
  44576. statuses[message.toLowerCase()] = status;
  44577. // Add to array
  44578. arr.push(status);
  44579. });
  44580. return arr
  44581. }
  44582. /**
  44583. * Get the status code.
  44584. *
  44585. * Given a number, this will throw if it is not a known status
  44586. * code, otherwise the code will be returned. Given a string,
  44587. * the string will be parsed for a number and return the code
  44588. * if valid, otherwise will lookup the code assuming this is
  44589. * the status message.
  44590. *
  44591. * @param {string|number} code
  44592. * @returns {number}
  44593. * @public
  44594. */
  44595. function status (code) {
  44596. if (typeof code === 'number') {
  44597. if (!status[code]) throw new Error('invalid status code: ' + code)
  44598. return code
  44599. }
  44600. if (typeof code !== 'string') {
  44601. throw new TypeError('code must be a number or string')
  44602. }
  44603. // '403'
  44604. var n = parseInt(code, 10);
  44605. if (!isNaN(n)) {
  44606. if (!status[n]) throw new Error('invalid status code: ' + n)
  44607. return n
  44608. }
  44609. n = status[code.toLowerCase()];
  44610. if (!n) throw new Error('invalid status message: "' + code + '"')
  44611. return n
  44612. }
  44613. /*!
  44614. * unpipe
  44615. * Copyright(c) 2015 Douglas Christopher Wilson
  44616. * MIT Licensed
  44617. */
  44618. /**
  44619. * Module exports.
  44620. * @public
  44621. */
  44622. var unpipe_1 = unpipe$1;
  44623. /**
  44624. * Determine if there are Node.js pipe-like data listeners.
  44625. * @private
  44626. */
  44627. function hasPipeDataListeners(stream) {
  44628. var listeners = stream.listeners('data');
  44629. for (var i = 0; i < listeners.length; i++) {
  44630. if (listeners[i].name === 'ondata') {
  44631. return true
  44632. }
  44633. }
  44634. return false
  44635. }
  44636. /**
  44637. * Unpipe a stream from all destinations.
  44638. *
  44639. * @param {object} stream
  44640. * @public
  44641. */
  44642. function unpipe$1(stream) {
  44643. if (!stream) {
  44644. throw new TypeError('argument stream is required')
  44645. }
  44646. if (typeof stream.unpipe === 'function') {
  44647. // new-style
  44648. stream.unpipe();
  44649. return
  44650. }
  44651. // Node.js 0.8 hack
  44652. if (!hasPipeDataListeners(stream)) {
  44653. return
  44654. }
  44655. var listener;
  44656. var listeners = stream.listeners('close');
  44657. for (var i = 0; i < listeners.length; i++) {
  44658. listener = listeners[i];
  44659. if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
  44660. continue
  44661. }
  44662. // invoke the listener
  44663. listener.call(stream);
  44664. }
  44665. }
  44666. /*!
  44667. * finalhandler
  44668. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  44669. * MIT Licensed
  44670. */
  44671. /**
  44672. * Module dependencies.
  44673. * @private
  44674. */
  44675. var debug$5 = srcExports('finalhandler');
  44676. var encodeUrl = encodeurl;
  44677. var escapeHtml = escapeHtml_1;
  44678. var onFinished = onFinishedExports;
  44679. var parseUrl$1 = parseurlExports;
  44680. var statuses = statuses$1;
  44681. var unpipe = unpipe_1;
  44682. /**
  44683. * Module variables.
  44684. * @private
  44685. */
  44686. var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
  44687. var NEWLINE_REGEXP = /\n/g;
  44688. /* istanbul ignore next */
  44689. var defer$1 = typeof setImmediate === 'function'
  44690. ? setImmediate
  44691. : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)); };
  44692. var isFinished = onFinished.isFinished;
  44693. /**
  44694. * Create a minimal HTML document.
  44695. *
  44696. * @param {string} message
  44697. * @private
  44698. */
  44699. function createHtmlDocument (message) {
  44700. var body = escapeHtml(message)
  44701. .replace(NEWLINE_REGEXP, '<br>')
  44702. .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;');
  44703. return '<!DOCTYPE html>\n' +
  44704. '<html lang="en">\n' +
  44705. '<head>\n' +
  44706. '<meta charset="utf-8">\n' +
  44707. '<title>Error</title>\n' +
  44708. '</head>\n' +
  44709. '<body>\n' +
  44710. '<pre>' + body + '</pre>\n' +
  44711. '</body>\n' +
  44712. '</html>\n'
  44713. }
  44714. /**
  44715. * Module exports.
  44716. * @public
  44717. */
  44718. var finalhandler_1 = finalhandler$1;
  44719. /**
  44720. * Create a function to handle the final response.
  44721. *
  44722. * @param {Request} req
  44723. * @param {Response} res
  44724. * @param {Object} [options]
  44725. * @return {Function}
  44726. * @public
  44727. */
  44728. function finalhandler$1 (req, res, options) {
  44729. var opts = options || {};
  44730. // get environment
  44731. var env = opts.env || process.env.NODE_ENV || 'development';
  44732. // get error callback
  44733. var onerror = opts.onerror;
  44734. return function (err) {
  44735. var headers;
  44736. var msg;
  44737. var status;
  44738. // ignore 404 on in-flight response
  44739. if (!err && headersSent(res)) {
  44740. debug$5('cannot 404 after headers sent');
  44741. return
  44742. }
  44743. // unhandled error
  44744. if (err) {
  44745. // respect status code from error
  44746. status = getErrorStatusCode(err);
  44747. if (status === undefined) {
  44748. // fallback to status code on response
  44749. status = getResponseStatusCode(res);
  44750. } else {
  44751. // respect headers from error
  44752. headers = getErrorHeaders(err);
  44753. }
  44754. // get error message
  44755. msg = getErrorMessage(err, status, env);
  44756. } else {
  44757. // not found
  44758. status = 404;
  44759. msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req));
  44760. }
  44761. debug$5('default %s', status);
  44762. // schedule onerror callback
  44763. if (err && onerror) {
  44764. defer$1(onerror, err, req, res);
  44765. }
  44766. // cannot actually respond
  44767. if (headersSent(res)) {
  44768. debug$5('cannot %d after headers sent', status);
  44769. req.socket.destroy();
  44770. return
  44771. }
  44772. // send response
  44773. send(req, res, status, headers, msg);
  44774. }
  44775. }
  44776. /**
  44777. * Get headers from Error object.
  44778. *
  44779. * @param {Error} err
  44780. * @return {object}
  44781. * @private
  44782. */
  44783. function getErrorHeaders (err) {
  44784. if (!err.headers || typeof err.headers !== 'object') {
  44785. return undefined
  44786. }
  44787. var headers = Object.create(null);
  44788. var keys = Object.keys(err.headers);
  44789. for (var i = 0; i < keys.length; i++) {
  44790. var key = keys[i];
  44791. headers[key] = err.headers[key];
  44792. }
  44793. return headers
  44794. }
  44795. /**
  44796. * Get message from Error object, fallback to status message.
  44797. *
  44798. * @param {Error} err
  44799. * @param {number} status
  44800. * @param {string} env
  44801. * @return {string}
  44802. * @private
  44803. */
  44804. function getErrorMessage (err, status, env) {
  44805. var msg;
  44806. if (env !== 'production') {
  44807. // use err.stack, which typically includes err.message
  44808. msg = err.stack;
  44809. // fallback to err.toString() when possible
  44810. if (!msg && typeof err.toString === 'function') {
  44811. msg = err.toString();
  44812. }
  44813. }
  44814. return msg || statuses[status]
  44815. }
  44816. /**
  44817. * Get status code from Error object.
  44818. *
  44819. * @param {Error} err
  44820. * @return {number}
  44821. * @private
  44822. */
  44823. function getErrorStatusCode (err) {
  44824. // check err.status
  44825. if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
  44826. return err.status
  44827. }
  44828. // check err.statusCode
  44829. if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
  44830. return err.statusCode
  44831. }
  44832. return undefined
  44833. }
  44834. /**
  44835. * Get resource name for the request.
  44836. *
  44837. * This is typically just the original pathname of the request
  44838. * but will fallback to "resource" is that cannot be determined.
  44839. *
  44840. * @param {IncomingMessage} req
  44841. * @return {string}
  44842. * @private
  44843. */
  44844. function getResourceName (req) {
  44845. try {
  44846. return parseUrl$1.original(req).pathname
  44847. } catch (e) {
  44848. return 'resource'
  44849. }
  44850. }
  44851. /**
  44852. * Get status code from response.
  44853. *
  44854. * @param {OutgoingMessage} res
  44855. * @return {number}
  44856. * @private
  44857. */
  44858. function getResponseStatusCode (res) {
  44859. var status = res.statusCode;
  44860. // default status code to 500 if outside valid range
  44861. if (typeof status !== 'number' || status < 400 || status > 599) {
  44862. status = 500;
  44863. }
  44864. return status
  44865. }
  44866. /**
  44867. * Determine if the response headers have been sent.
  44868. *
  44869. * @param {object} res
  44870. * @returns {boolean}
  44871. * @private
  44872. */
  44873. function headersSent (res) {
  44874. return typeof res.headersSent !== 'boolean'
  44875. ? Boolean(res._header)
  44876. : res.headersSent
  44877. }
  44878. /**
  44879. * Send response.
  44880. *
  44881. * @param {IncomingMessage} req
  44882. * @param {OutgoingMessage} res
  44883. * @param {number} status
  44884. * @param {object} headers
  44885. * @param {string} message
  44886. * @private
  44887. */
  44888. function send (req, res, status, headers, message) {
  44889. function write () {
  44890. // response body
  44891. var body = createHtmlDocument(message);
  44892. // response status
  44893. res.statusCode = status;
  44894. res.statusMessage = statuses[status];
  44895. // response headers
  44896. setHeaders(res, headers);
  44897. // security headers
  44898. res.setHeader('Content-Security-Policy', "default-src 'none'");
  44899. res.setHeader('X-Content-Type-Options', 'nosniff');
  44900. // standard headers
  44901. res.setHeader('Content-Type', 'text/html; charset=utf-8');
  44902. res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'));
  44903. if (req.method === 'HEAD') {
  44904. res.end();
  44905. return
  44906. }
  44907. res.end(body, 'utf8');
  44908. }
  44909. if (isFinished(req)) {
  44910. write();
  44911. return
  44912. }
  44913. // unpipe everything from the request
  44914. unpipe(req);
  44915. // flush the request
  44916. onFinished(req, write);
  44917. req.resume();
  44918. }
  44919. /**
  44920. * Set response headers from an object.
  44921. *
  44922. * @param {OutgoingMessage} res
  44923. * @param {object} headers
  44924. * @private
  44925. */
  44926. function setHeaders (res, headers) {
  44927. if (!headers) {
  44928. return
  44929. }
  44930. var keys = Object.keys(headers);
  44931. for (var i = 0; i < keys.length; i++) {
  44932. var key = keys[i];
  44933. res.setHeader(key, headers[key]);
  44934. }
  44935. }
  44936. var utilsMerge = {exports: {}};
  44937. /**
  44938. * Merge object b with object a.
  44939. *
  44940. * var a = { foo: 'bar' }
  44941. * , b = { bar: 'baz' };
  44942. *
  44943. * merge(a, b);
  44944. * // => { foo: 'bar', bar: 'baz' }
  44945. *
  44946. * @param {Object} a
  44947. * @param {Object} b
  44948. * @return {Object}
  44949. * @api public
  44950. */
  44951. (function (module, exports) {
  44952. module.exports = function(a, b){
  44953. if (a && b) {
  44954. for (var key in b) {
  44955. a[key] = b[key];
  44956. }
  44957. }
  44958. return a;
  44959. };
  44960. } (utilsMerge));
  44961. var utilsMergeExports = utilsMerge.exports;
  44962. /*!
  44963. * connect
  44964. * Copyright(c) 2010 Sencha Inc.
  44965. * Copyright(c) 2011 TJ Holowaychuk
  44966. * Copyright(c) 2015 Douglas Christopher Wilson
  44967. * MIT Licensed
  44968. */
  44969. /**
  44970. * Module dependencies.
  44971. * @private
  44972. */
  44973. var debug$4 = srcExports('connect:dispatcher');
  44974. var EventEmitter$3 = require$$0$5.EventEmitter;
  44975. var finalhandler = finalhandler_1;
  44976. var http$4 = require$$1$1;
  44977. var merge = utilsMergeExports;
  44978. var parseUrl = parseurlExports;
  44979. /**
  44980. * Module exports.
  44981. * @public
  44982. */
  44983. var connect = createServer$1;
  44984. /**
  44985. * Module variables.
  44986. * @private
  44987. */
  44988. var env = process.env.NODE_ENV || 'development';
  44989. var proto = {};
  44990. /* istanbul ignore next */
  44991. var defer = typeof setImmediate === 'function'
  44992. ? setImmediate
  44993. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  44994. /**
  44995. * Create a new connect server.
  44996. *
  44997. * @return {function}
  44998. * @public
  44999. */
  45000. function createServer$1() {
  45001. function app(req, res, next){ app.handle(req, res, next); }
  45002. merge(app, proto);
  45003. merge(app, EventEmitter$3.prototype);
  45004. app.route = '/';
  45005. app.stack = [];
  45006. return app;
  45007. }
  45008. /**
  45009. * Utilize the given middleware `handle` to the given `route`,
  45010. * defaulting to _/_. This "route" is the mount-point for the
  45011. * middleware, when given a value other than _/_ the middleware
  45012. * is only effective when that segment is present in the request's
  45013. * pathname.
  45014. *
  45015. * For example if we were to mount a function at _/admin_, it would
  45016. * be invoked on _/admin_, and _/admin/settings_, however it would
  45017. * not be invoked for _/_, or _/posts_.
  45018. *
  45019. * @param {String|Function|Server} route, callback or server
  45020. * @param {Function|Server} callback or server
  45021. * @return {Server} for chaining
  45022. * @public
  45023. */
  45024. proto.use = function use(route, fn) {
  45025. var handle = fn;
  45026. var path = route;
  45027. // default route to '/'
  45028. if (typeof route !== 'string') {
  45029. handle = route;
  45030. path = '/';
  45031. }
  45032. // wrap sub-apps
  45033. if (typeof handle.handle === 'function') {
  45034. var server = handle;
  45035. server.route = path;
  45036. handle = function (req, res, next) {
  45037. server.handle(req, res, next);
  45038. };
  45039. }
  45040. // wrap vanilla http.Servers
  45041. if (handle instanceof http$4.Server) {
  45042. handle = handle.listeners('request')[0];
  45043. }
  45044. // strip trailing slash
  45045. if (path[path.length - 1] === '/') {
  45046. path = path.slice(0, -1);
  45047. }
  45048. // add the middleware
  45049. debug$4('use %s %s', path || '/', handle.name || 'anonymous');
  45050. this.stack.push({ route: path, handle: handle });
  45051. return this;
  45052. };
  45053. /**
  45054. * Handle server requests, punting them down
  45055. * the middleware stack.
  45056. *
  45057. * @private
  45058. */
  45059. proto.handle = function handle(req, res, out) {
  45060. var index = 0;
  45061. var protohost = getProtohost(req.url) || '';
  45062. var removed = '';
  45063. var slashAdded = false;
  45064. var stack = this.stack;
  45065. // final function handler
  45066. var done = out || finalhandler(req, res, {
  45067. env: env,
  45068. onerror: logerror
  45069. });
  45070. // store the original URL
  45071. req.originalUrl = req.originalUrl || req.url;
  45072. function next(err) {
  45073. if (slashAdded) {
  45074. req.url = req.url.substr(1);
  45075. slashAdded = false;
  45076. }
  45077. if (removed.length !== 0) {
  45078. req.url = protohost + removed + req.url.substr(protohost.length);
  45079. removed = '';
  45080. }
  45081. // next callback
  45082. var layer = stack[index++];
  45083. // all done
  45084. if (!layer) {
  45085. defer(done, err);
  45086. return;
  45087. }
  45088. // route data
  45089. var path = parseUrl(req).pathname || '/';
  45090. var route = layer.route;
  45091. // skip this layer if the route doesn't match
  45092. if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
  45093. return next(err);
  45094. }
  45095. // skip if route match does not border "/", ".", or end
  45096. var c = path.length > route.length && path[route.length];
  45097. if (c && c !== '/' && c !== '.') {
  45098. return next(err);
  45099. }
  45100. // trim off the part of the url that matches the route
  45101. if (route.length !== 0 && route !== '/') {
  45102. removed = route;
  45103. req.url = protohost + req.url.substr(protohost.length + removed.length);
  45104. // ensure leading slash
  45105. if (!protohost && req.url[0] !== '/') {
  45106. req.url = '/' + req.url;
  45107. slashAdded = true;
  45108. }
  45109. }
  45110. // call the layer handle
  45111. call(layer.handle, route, err, req, res, next);
  45112. }
  45113. next();
  45114. };
  45115. /**
  45116. * Listen for connections.
  45117. *
  45118. * This method takes the same arguments
  45119. * as node's `http.Server#listen()`.
  45120. *
  45121. * HTTP and HTTPS:
  45122. *
  45123. * If you run your application both as HTTP
  45124. * and HTTPS you may wrap them individually,
  45125. * since your Connect "server" is really just
  45126. * a JavaScript `Function`.
  45127. *
  45128. * var connect = require('connect')
  45129. * , http = require('http')
  45130. * , https = require('https');
  45131. *
  45132. * var app = connect();
  45133. *
  45134. * http.createServer(app).listen(80);
  45135. * https.createServer(options, app).listen(443);
  45136. *
  45137. * @return {http.Server}
  45138. * @api public
  45139. */
  45140. proto.listen = function listen() {
  45141. var server = http$4.createServer(this);
  45142. return server.listen.apply(server, arguments);
  45143. };
  45144. /**
  45145. * Invoke a route handle.
  45146. * @private
  45147. */
  45148. function call(handle, route, err, req, res, next) {
  45149. var arity = handle.length;
  45150. var error = err;
  45151. var hasError = Boolean(err);
  45152. debug$4('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
  45153. try {
  45154. if (hasError && arity === 4) {
  45155. // error-handling middleware
  45156. handle(err, req, res, next);
  45157. return;
  45158. } else if (!hasError && arity < 4) {
  45159. // request-handling middleware
  45160. handle(req, res, next);
  45161. return;
  45162. }
  45163. } catch (e) {
  45164. // replace the error
  45165. error = e;
  45166. }
  45167. // continue
  45168. next(error);
  45169. }
  45170. /**
  45171. * Log error using console.error.
  45172. *
  45173. * @param {Error} err
  45174. * @private
  45175. */
  45176. function logerror(err) {
  45177. if (env !== 'test') console.error(err.stack || err.toString());
  45178. }
  45179. /**
  45180. * Get get protocol + host for a URL.
  45181. *
  45182. * @param {string} url
  45183. * @private
  45184. */
  45185. function getProtohost(url) {
  45186. if (url.length === 0 || url[0] === '/') {
  45187. return undefined;
  45188. }
  45189. var fqdnIndex = url.indexOf('://');
  45190. return fqdnIndex !== -1 && url.lastIndexOf('?', fqdnIndex) === -1
  45191. ? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
  45192. : undefined;
  45193. }
  45194. var connect$1 = /*@__PURE__*/getDefaultExportFromCjs(connect);
  45195. var lib$1 = {exports: {}};
  45196. /*
  45197. object-assign
  45198. (c) Sindre Sorhus
  45199. @license MIT
  45200. */
  45201. /* eslint-disable no-unused-vars */
  45202. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  45203. var hasOwnProperty = Object.prototype.hasOwnProperty;
  45204. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  45205. function toObject(val) {
  45206. if (val === null || val === undefined) {
  45207. throw new TypeError('Object.assign cannot be called with null or undefined');
  45208. }
  45209. return Object(val);
  45210. }
  45211. function shouldUseNative() {
  45212. try {
  45213. if (!Object.assign) {
  45214. return false;
  45215. }
  45216. // Detect buggy property enumeration order in older V8 versions.
  45217. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  45218. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  45219. test1[5] = 'de';
  45220. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  45221. return false;
  45222. }
  45223. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  45224. var test2 = {};
  45225. for (var i = 0; i < 10; i++) {
  45226. test2['_' + String.fromCharCode(i)] = i;
  45227. }
  45228. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  45229. return test2[n];
  45230. });
  45231. if (order2.join('') !== '0123456789') {
  45232. return false;
  45233. }
  45234. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  45235. var test3 = {};
  45236. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  45237. test3[letter] = letter;
  45238. });
  45239. if (Object.keys(Object.assign({}, test3)).join('') !==
  45240. 'abcdefghijklmnopqrst') {
  45241. return false;
  45242. }
  45243. return true;
  45244. } catch (err) {
  45245. // We don't expect any of the above to throw, but better to be safe.
  45246. return false;
  45247. }
  45248. }
  45249. var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  45250. var from;
  45251. var to = toObject(target);
  45252. var symbols;
  45253. for (var s = 1; s < arguments.length; s++) {
  45254. from = Object(arguments[s]);
  45255. for (var key in from) {
  45256. if (hasOwnProperty.call(from, key)) {
  45257. to[key] = from[key];
  45258. }
  45259. }
  45260. if (getOwnPropertySymbols) {
  45261. symbols = getOwnPropertySymbols(from);
  45262. for (var i = 0; i < symbols.length; i++) {
  45263. if (propIsEnumerable.call(from, symbols[i])) {
  45264. to[symbols[i]] = from[symbols[i]];
  45265. }
  45266. }
  45267. }
  45268. }
  45269. return to;
  45270. };
  45271. var vary$1 = {exports: {}};
  45272. /*!
  45273. * vary
  45274. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  45275. * MIT Licensed
  45276. */
  45277. /**
  45278. * Module exports.
  45279. */
  45280. vary$1.exports = vary;
  45281. vary$1.exports.append = append;
  45282. /**
  45283. * RegExp to match field-name in RFC 7230 sec 3.2
  45284. *
  45285. * field-name = token
  45286. * token = 1*tchar
  45287. * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  45288. * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  45289. * / DIGIT / ALPHA
  45290. * ; any VCHAR, except delimiters
  45291. */
  45292. var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  45293. /**
  45294. * Append a field to a vary header.
  45295. *
  45296. * @param {String} header
  45297. * @param {String|Array} field
  45298. * @return {String}
  45299. * @public
  45300. */
  45301. function append (header, field) {
  45302. if (typeof header !== 'string') {
  45303. throw new TypeError('header argument is required')
  45304. }
  45305. if (!field) {
  45306. throw new TypeError('field argument is required')
  45307. }
  45308. // get fields array
  45309. var fields = !Array.isArray(field)
  45310. ? parse$6(String(field))
  45311. : field;
  45312. // assert on invalid field names
  45313. for (var j = 0; j < fields.length; j++) {
  45314. if (!FIELD_NAME_REGEXP.test(fields[j])) {
  45315. throw new TypeError('field argument contains an invalid header name')
  45316. }
  45317. }
  45318. // existing, unspecified vary
  45319. if (header === '*') {
  45320. return header
  45321. }
  45322. // enumerate current values
  45323. var val = header;
  45324. var vals = parse$6(header.toLowerCase());
  45325. // unspecified vary
  45326. if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
  45327. return '*'
  45328. }
  45329. for (var i = 0; i < fields.length; i++) {
  45330. var fld = fields[i].toLowerCase();
  45331. // append value (case-preserving)
  45332. if (vals.indexOf(fld) === -1) {
  45333. vals.push(fld);
  45334. val = val
  45335. ? val + ', ' + fields[i]
  45336. : fields[i];
  45337. }
  45338. }
  45339. return val
  45340. }
  45341. /**
  45342. * Parse a vary header into an array.
  45343. *
  45344. * @param {String} header
  45345. * @return {Array}
  45346. * @private
  45347. */
  45348. function parse$6 (header) {
  45349. var end = 0;
  45350. var list = [];
  45351. var start = 0;
  45352. // gather tokens
  45353. for (var i = 0, len = header.length; i < len; i++) {
  45354. switch (header.charCodeAt(i)) {
  45355. case 0x20: /* */
  45356. if (start === end) {
  45357. start = end = i + 1;
  45358. }
  45359. break
  45360. case 0x2c: /* , */
  45361. list.push(header.substring(start, end));
  45362. start = end = i + 1;
  45363. break
  45364. default:
  45365. end = i + 1;
  45366. break
  45367. }
  45368. }
  45369. // final token
  45370. list.push(header.substring(start, end));
  45371. return list
  45372. }
  45373. /**
  45374. * Mark that a request is varied on a header field.
  45375. *
  45376. * @param {Object} res
  45377. * @param {String|Array} field
  45378. * @public
  45379. */
  45380. function vary (res, field) {
  45381. if (!res || !res.getHeader || !res.setHeader) {
  45382. // quack quack
  45383. throw new TypeError('res argument is required')
  45384. }
  45385. // get existing header
  45386. var val = res.getHeader('Vary') || '';
  45387. var header = Array.isArray(val)
  45388. ? val.join(', ')
  45389. : String(val);
  45390. // set new header
  45391. if ((val = append(header, field))) {
  45392. res.setHeader('Vary', val);
  45393. }
  45394. }
  45395. var varyExports = vary$1.exports;
  45396. (function () {
  45397. var assign = objectAssign;
  45398. var vary = varyExports;
  45399. var defaults = {
  45400. origin: '*',
  45401. methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  45402. preflightContinue: false,
  45403. optionsSuccessStatus: 204
  45404. };
  45405. function isString(s) {
  45406. return typeof s === 'string' || s instanceof String;
  45407. }
  45408. function isOriginAllowed(origin, allowedOrigin) {
  45409. if (Array.isArray(allowedOrigin)) {
  45410. for (var i = 0; i < allowedOrigin.length; ++i) {
  45411. if (isOriginAllowed(origin, allowedOrigin[i])) {
  45412. return true;
  45413. }
  45414. }
  45415. return false;
  45416. } else if (isString(allowedOrigin)) {
  45417. return origin === allowedOrigin;
  45418. } else if (allowedOrigin instanceof RegExp) {
  45419. return allowedOrigin.test(origin);
  45420. } else {
  45421. return !!allowedOrigin;
  45422. }
  45423. }
  45424. function configureOrigin(options, req) {
  45425. var requestOrigin = req.headers.origin,
  45426. headers = [],
  45427. isAllowed;
  45428. if (!options.origin || options.origin === '*') {
  45429. // allow any origin
  45430. headers.push([{
  45431. key: 'Access-Control-Allow-Origin',
  45432. value: '*'
  45433. }]);
  45434. } else if (isString(options.origin)) {
  45435. // fixed origin
  45436. headers.push([{
  45437. key: 'Access-Control-Allow-Origin',
  45438. value: options.origin
  45439. }]);
  45440. headers.push([{
  45441. key: 'Vary',
  45442. value: 'Origin'
  45443. }]);
  45444. } else {
  45445. isAllowed = isOriginAllowed(requestOrigin, options.origin);
  45446. // reflect origin
  45447. headers.push([{
  45448. key: 'Access-Control-Allow-Origin',
  45449. value: isAllowed ? requestOrigin : false
  45450. }]);
  45451. headers.push([{
  45452. key: 'Vary',
  45453. value: 'Origin'
  45454. }]);
  45455. }
  45456. return headers;
  45457. }
  45458. function configureMethods(options) {
  45459. var methods = options.methods;
  45460. if (methods.join) {
  45461. methods = options.methods.join(','); // .methods is an array, so turn it into a string
  45462. }
  45463. return {
  45464. key: 'Access-Control-Allow-Methods',
  45465. value: methods
  45466. };
  45467. }
  45468. function configureCredentials(options) {
  45469. if (options.credentials === true) {
  45470. return {
  45471. key: 'Access-Control-Allow-Credentials',
  45472. value: 'true'
  45473. };
  45474. }
  45475. return null;
  45476. }
  45477. function configureAllowedHeaders(options, req) {
  45478. var allowedHeaders = options.allowedHeaders || options.headers;
  45479. var headers = [];
  45480. if (!allowedHeaders) {
  45481. allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
  45482. headers.push([{
  45483. key: 'Vary',
  45484. value: 'Access-Control-Request-Headers'
  45485. }]);
  45486. } else if (allowedHeaders.join) {
  45487. allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
  45488. }
  45489. if (allowedHeaders && allowedHeaders.length) {
  45490. headers.push([{
  45491. key: 'Access-Control-Allow-Headers',
  45492. value: allowedHeaders
  45493. }]);
  45494. }
  45495. return headers;
  45496. }
  45497. function configureExposedHeaders(options) {
  45498. var headers = options.exposedHeaders;
  45499. if (!headers) {
  45500. return null;
  45501. } else if (headers.join) {
  45502. headers = headers.join(','); // .headers is an array, so turn it into a string
  45503. }
  45504. if (headers && headers.length) {
  45505. return {
  45506. key: 'Access-Control-Expose-Headers',
  45507. value: headers
  45508. };
  45509. }
  45510. return null;
  45511. }
  45512. function configureMaxAge(options) {
  45513. var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString();
  45514. if (maxAge && maxAge.length) {
  45515. return {
  45516. key: 'Access-Control-Max-Age',
  45517. value: maxAge
  45518. };
  45519. }
  45520. return null;
  45521. }
  45522. function applyHeaders(headers, res) {
  45523. for (var i = 0, n = headers.length; i < n; i++) {
  45524. var header = headers[i];
  45525. if (header) {
  45526. if (Array.isArray(header)) {
  45527. applyHeaders(header, res);
  45528. } else if (header.key === 'Vary' && header.value) {
  45529. vary(res, header.value);
  45530. } else if (header.value) {
  45531. res.setHeader(header.key, header.value);
  45532. }
  45533. }
  45534. }
  45535. }
  45536. function cors(options, req, res, next) {
  45537. var headers = [],
  45538. method = req.method && req.method.toUpperCase && req.method.toUpperCase();
  45539. if (method === 'OPTIONS') {
  45540. // preflight
  45541. headers.push(configureOrigin(options, req));
  45542. headers.push(configureCredentials(options));
  45543. headers.push(configureMethods(options));
  45544. headers.push(configureAllowedHeaders(options, req));
  45545. headers.push(configureMaxAge(options));
  45546. headers.push(configureExposedHeaders(options));
  45547. applyHeaders(headers, res);
  45548. if (options.preflightContinue) {
  45549. next();
  45550. } else {
  45551. // Safari (and potentially other browsers) need content-length 0,
  45552. // for 204 or they just hang waiting for a body
  45553. res.statusCode = options.optionsSuccessStatus;
  45554. res.setHeader('Content-Length', '0');
  45555. res.end();
  45556. }
  45557. } else {
  45558. // actual response
  45559. headers.push(configureOrigin(options, req));
  45560. headers.push(configureCredentials(options));
  45561. headers.push(configureExposedHeaders(options));
  45562. applyHeaders(headers, res);
  45563. next();
  45564. }
  45565. }
  45566. function middlewareWrapper(o) {
  45567. // if options are static (either via defaults or custom options passed in), wrap in a function
  45568. var optionsCallback = null;
  45569. if (typeof o === 'function') {
  45570. optionsCallback = o;
  45571. } else {
  45572. optionsCallback = function (req, cb) {
  45573. cb(null, o);
  45574. };
  45575. }
  45576. return function corsMiddleware(req, res, next) {
  45577. optionsCallback(req, function (err, options) {
  45578. if (err) {
  45579. next(err);
  45580. } else {
  45581. var corsOptions = assign({}, defaults, options);
  45582. var originCallback = null;
  45583. if (corsOptions.origin && typeof corsOptions.origin === 'function') {
  45584. originCallback = corsOptions.origin;
  45585. } else if (corsOptions.origin) {
  45586. originCallback = function (origin, cb) {
  45587. cb(null, corsOptions.origin);
  45588. };
  45589. }
  45590. if (originCallback) {
  45591. originCallback(req.headers.origin, function (err2, origin) {
  45592. if (err2 || !origin) {
  45593. next(err2);
  45594. } else {
  45595. corsOptions.origin = origin;
  45596. cors(corsOptions, req, res, next);
  45597. }
  45598. });
  45599. } else {
  45600. next();
  45601. }
  45602. }
  45603. });
  45604. };
  45605. }
  45606. // can pass either an options hash, an options delegate, or nothing
  45607. lib$1.exports = middlewareWrapper;
  45608. }());
  45609. var libExports$1 = lib$1.exports;
  45610. var corsMiddleware = /*@__PURE__*/getDefaultExportFromCjs(libExports$1);
  45611. var chokidar = {};
  45612. const fs$8 = require$$0__default;
  45613. const { Readable } = require$$0$7;
  45614. const sysPath$3 = require$$0$4;
  45615. const { promisify: promisify$3 } = require$$0$6;
  45616. const picomatch$1 = picomatch$3;
  45617. const readdir$1 = promisify$3(fs$8.readdir);
  45618. const stat$3 = promisify$3(fs$8.stat);
  45619. const lstat$2 = promisify$3(fs$8.lstat);
  45620. const realpath$1 = promisify$3(fs$8.realpath);
  45621. /**
  45622. * @typedef {Object} EntryInfo
  45623. * @property {String} path
  45624. * @property {String} fullPath
  45625. * @property {fs.Stats=} stats
  45626. * @property {fs.Dirent=} dirent
  45627. * @property {String} basename
  45628. */
  45629. const BANG$2 = '!';
  45630. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  45631. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  45632. const FILE_TYPE = 'files';
  45633. const DIR_TYPE = 'directories';
  45634. const FILE_DIR_TYPE = 'files_directories';
  45635. const EVERYTHING_TYPE = 'all';
  45636. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  45637. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  45638. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  45639. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  45640. const normalizeFilter = filter => {
  45641. if (filter === undefined) return;
  45642. if (typeof filter === 'function') return filter;
  45643. if (typeof filter === 'string') {
  45644. const glob = picomatch$1(filter.trim());
  45645. return entry => glob(entry.basename);
  45646. }
  45647. if (Array.isArray(filter)) {
  45648. const positive = [];
  45649. const negative = [];
  45650. for (const item of filter) {
  45651. const trimmed = item.trim();
  45652. if (trimmed.charAt(0) === BANG$2) {
  45653. negative.push(picomatch$1(trimmed.slice(1)));
  45654. } else {
  45655. positive.push(picomatch$1(trimmed));
  45656. }
  45657. }
  45658. if (negative.length > 0) {
  45659. if (positive.length > 0) {
  45660. return entry =>
  45661. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  45662. }
  45663. return entry => !negative.some(f => f(entry.basename));
  45664. }
  45665. return entry => positive.some(f => f(entry.basename));
  45666. }
  45667. };
  45668. class ReaddirpStream extends Readable {
  45669. static get defaultOptions() {
  45670. return {
  45671. root: '.',
  45672. /* eslint-disable no-unused-vars */
  45673. fileFilter: (path) => true,
  45674. directoryFilter: (path) => true,
  45675. /* eslint-enable no-unused-vars */
  45676. type: FILE_TYPE,
  45677. lstat: false,
  45678. depth: 2147483648,
  45679. alwaysStat: false
  45680. };
  45681. }
  45682. constructor(options = {}) {
  45683. super({
  45684. objectMode: true,
  45685. autoDestroy: true,
  45686. highWaterMark: options.highWaterMark || 4096
  45687. });
  45688. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  45689. const { root, type } = opts;
  45690. this._fileFilter = normalizeFilter(opts.fileFilter);
  45691. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  45692. const statMethod = opts.lstat ? lstat$2 : stat$3;
  45693. // Use bigint stats if it's windows and stat() supports options (node 10+).
  45694. if (wantBigintFsStats) {
  45695. this._stat = path => statMethod(path, { bigint: true });
  45696. } else {
  45697. this._stat = statMethod;
  45698. }
  45699. this._maxDepth = opts.depth;
  45700. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  45701. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  45702. this._wantsEverything = type === EVERYTHING_TYPE;
  45703. this._root = sysPath$3.resolve(root);
  45704. this._isDirent = ('Dirent' in fs$8) && !opts.alwaysStat;
  45705. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  45706. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  45707. // Launch stream with one parent, the root dir.
  45708. this.parents = [this._exploreDir(root, 1)];
  45709. this.reading = false;
  45710. this.parent = undefined;
  45711. }
  45712. async _read(batch) {
  45713. if (this.reading) return;
  45714. this.reading = true;
  45715. try {
  45716. while (!this.destroyed && batch > 0) {
  45717. const { path, depth, files = [] } = this.parent || {};
  45718. if (files.length > 0) {
  45719. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  45720. for (const entry of await Promise.all(slice)) {
  45721. if (this.destroyed) return;
  45722. const entryType = await this._getEntryType(entry);
  45723. if (entryType === 'directory' && this._directoryFilter(entry)) {
  45724. if (depth <= this._maxDepth) {
  45725. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  45726. }
  45727. if (this._wantsDir) {
  45728. this.push(entry);
  45729. batch--;
  45730. }
  45731. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  45732. if (this._wantsFile) {
  45733. this.push(entry);
  45734. batch--;
  45735. }
  45736. }
  45737. }
  45738. } else {
  45739. const parent = this.parents.pop();
  45740. if (!parent) {
  45741. this.push(null);
  45742. break;
  45743. }
  45744. this.parent = await parent;
  45745. if (this.destroyed) return;
  45746. }
  45747. }
  45748. } catch (error) {
  45749. this.destroy(error);
  45750. } finally {
  45751. this.reading = false;
  45752. }
  45753. }
  45754. async _exploreDir(path, depth) {
  45755. let files;
  45756. try {
  45757. files = await readdir$1(path, this._rdOptions);
  45758. } catch (error) {
  45759. this._onError(error);
  45760. }
  45761. return { files, depth, path };
  45762. }
  45763. async _formatEntry(dirent, path) {
  45764. let entry;
  45765. try {
  45766. const basename = this._isDirent ? dirent.name : dirent;
  45767. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  45768. entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
  45769. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  45770. } catch (err) {
  45771. this._onError(err);
  45772. }
  45773. return entry;
  45774. }
  45775. _onError(err) {
  45776. if (isNormalFlowError(err) && !this.destroyed) {
  45777. this.emit('warn', err);
  45778. } else {
  45779. this.destroy(err);
  45780. }
  45781. }
  45782. async _getEntryType(entry) {
  45783. // entry may be undefined, because a warning or an error were emitted
  45784. // and the statsProp is undefined
  45785. const stats = entry && entry[this._statsProp];
  45786. if (!stats) {
  45787. return;
  45788. }
  45789. if (stats.isFile()) {
  45790. return 'file';
  45791. }
  45792. if (stats.isDirectory()) {
  45793. return 'directory';
  45794. }
  45795. if (stats && stats.isSymbolicLink()) {
  45796. const full = entry.fullPath;
  45797. try {
  45798. const entryRealPath = await realpath$1(full);
  45799. const entryRealPathStats = await lstat$2(entryRealPath);
  45800. if (entryRealPathStats.isFile()) {
  45801. return 'file';
  45802. }
  45803. if (entryRealPathStats.isDirectory()) {
  45804. const len = entryRealPath.length;
  45805. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  45806. const recursiveError = new Error(
  45807. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  45808. );
  45809. recursiveError.code = RECURSIVE_ERROR_CODE;
  45810. return this._onError(recursiveError);
  45811. }
  45812. return 'directory';
  45813. }
  45814. } catch (error) {
  45815. this._onError(error);
  45816. }
  45817. }
  45818. }
  45819. _includeAsFile(entry) {
  45820. const stats = entry && entry[this._statsProp];
  45821. return stats && this._wantsEverything && !stats.isDirectory();
  45822. }
  45823. }
  45824. /**
  45825. * @typedef {Object} ReaddirpArguments
  45826. * @property {Function=} fileFilter
  45827. * @property {Function=} directoryFilter
  45828. * @property {String=} type
  45829. * @property {Number=} depth
  45830. * @property {String=} root
  45831. * @property {Boolean=} lstat
  45832. * @property {Boolean=} bigint
  45833. */
  45834. /**
  45835. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  45836. * @param {String} root Root directory
  45837. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  45838. */
  45839. const readdirp$1 = (root, options = {}) => {
  45840. let type = options.entryType || options.type;
  45841. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  45842. if (type) options.type = type;
  45843. if (!root) {
  45844. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  45845. } else if (typeof root !== 'string') {
  45846. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  45847. } else if (type && !ALL_TYPES.includes(type)) {
  45848. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  45849. }
  45850. options.root = root;
  45851. return new ReaddirpStream(options);
  45852. };
  45853. const readdirpPromise = (root, options = {}) => {
  45854. return new Promise((resolve, reject) => {
  45855. const files = [];
  45856. readdirp$1(root, options)
  45857. .on('data', entry => files.push(entry))
  45858. .on('end', () => resolve(files))
  45859. .on('error', error => reject(error));
  45860. });
  45861. };
  45862. readdirp$1.promise = readdirpPromise;
  45863. readdirp$1.ReaddirpStream = ReaddirpStream;
  45864. readdirp$1.default = readdirp$1;
  45865. var readdirp_1 = readdirp$1;
  45866. var anymatch$2 = {exports: {}};
  45867. /*!
  45868. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  45869. *
  45870. * Copyright (c) 2014-2018, Jon Schlinkert.
  45871. * Released under the MIT License.
  45872. */
  45873. var normalizePath$2 = function(path, stripTrailing) {
  45874. if (typeof path !== 'string') {
  45875. throw new TypeError('expected path to be a string');
  45876. }
  45877. if (path === '\\' || path === '/') return '/';
  45878. var len = path.length;
  45879. if (len <= 1) return path;
  45880. // ensure that win32 namespaces has two leading slashes, so that the path is
  45881. // handled properly by the win32 version of path.parse() after being normalized
  45882. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  45883. var prefix = '';
  45884. if (len > 4 && path[3] === '\\') {
  45885. var ch = path[2];
  45886. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  45887. path = path.slice(2);
  45888. prefix = '//';
  45889. }
  45890. }
  45891. var segs = path.split(/[/\\]+/);
  45892. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  45893. segs.pop();
  45894. }
  45895. return prefix + segs.join('/');
  45896. };
  45897. var anymatch_1 = anymatch$2.exports;
  45898. Object.defineProperty(anymatch_1, "__esModule", { value: true });
  45899. const picomatch = picomatch$3;
  45900. const normalizePath$1 = normalizePath$2;
  45901. /**
  45902. * @typedef {(testString: string) => boolean} AnymatchFn
  45903. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  45904. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  45905. */
  45906. const BANG$1 = '!';
  45907. const DEFAULT_OPTIONS = {returnIndex: false};
  45908. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  45909. /**
  45910. * @param {AnymatchPattern} matcher
  45911. * @param {object} options
  45912. * @returns {AnymatchFn}
  45913. */
  45914. const createPattern = (matcher, options) => {
  45915. if (typeof matcher === 'function') {
  45916. return matcher;
  45917. }
  45918. if (typeof matcher === 'string') {
  45919. const glob = picomatch(matcher, options);
  45920. return (string) => matcher === string || glob(string);
  45921. }
  45922. if (matcher instanceof RegExp) {
  45923. return (string) => matcher.test(string);
  45924. }
  45925. return (string) => false;
  45926. };
  45927. /**
  45928. * @param {Array<Function>} patterns
  45929. * @param {Array<Function>} negPatterns
  45930. * @param {String|Array} args
  45931. * @param {Boolean} returnIndex
  45932. * @returns {boolean|number}
  45933. */
  45934. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  45935. const isList = Array.isArray(args);
  45936. const _path = isList ? args[0] : args;
  45937. if (!isList && typeof _path !== 'string') {
  45938. throw new TypeError('anymatch: second argument must be a string: got ' +
  45939. Object.prototype.toString.call(_path))
  45940. }
  45941. const path = normalizePath$1(_path);
  45942. for (let index = 0; index < negPatterns.length; index++) {
  45943. const nglob = negPatterns[index];
  45944. if (nglob(path)) {
  45945. return returnIndex ? -1 : false;
  45946. }
  45947. }
  45948. const applied = isList && [path].concat(args.slice(1));
  45949. for (let index = 0; index < patterns.length; index++) {
  45950. const pattern = patterns[index];
  45951. if (isList ? pattern(...applied) : pattern(path)) {
  45952. return returnIndex ? index : true;
  45953. }
  45954. }
  45955. return returnIndex ? -1 : false;
  45956. };
  45957. /**
  45958. * @param {AnymatchMatcher} matchers
  45959. * @param {Array|string} testString
  45960. * @param {object} options
  45961. * @returns {boolean|number|Function}
  45962. */
  45963. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  45964. if (matchers == null) {
  45965. throw new TypeError('anymatch: specify first argument');
  45966. }
  45967. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  45968. const returnIndex = opts.returnIndex || false;
  45969. // Early cache for matchers.
  45970. const mtchers = arrify$1(matchers);
  45971. const negatedGlobs = mtchers
  45972. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  45973. .map(item => item.slice(1))
  45974. .map(item => picomatch(item, opts));
  45975. const patterns = mtchers
  45976. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
  45977. .map(matcher => createPattern(matcher, opts));
  45978. if (testString == null) {
  45979. return (testString, ri = false) => {
  45980. const returnIndex = typeof ri === 'boolean' ? ri : false;
  45981. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  45982. }
  45983. }
  45984. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  45985. };
  45986. anymatch$1.default = anymatch$1;
  45987. anymatch$2.exports = anymatch$1;
  45988. var anymatchExports = anymatch$2.exports;
  45989. var require$$0 = [
  45990. "3dm",
  45991. "3ds",
  45992. "3g2",
  45993. "3gp",
  45994. "7z",
  45995. "a",
  45996. "aac",
  45997. "adp",
  45998. "ai",
  45999. "aif",
  46000. "aiff",
  46001. "alz",
  46002. "ape",
  46003. "apk",
  46004. "appimage",
  46005. "ar",
  46006. "arj",
  46007. "asf",
  46008. "au",
  46009. "avi",
  46010. "bak",
  46011. "baml",
  46012. "bh",
  46013. "bin",
  46014. "bk",
  46015. "bmp",
  46016. "btif",
  46017. "bz2",
  46018. "bzip2",
  46019. "cab",
  46020. "caf",
  46021. "cgm",
  46022. "class",
  46023. "cmx",
  46024. "cpio",
  46025. "cr2",
  46026. "cur",
  46027. "dat",
  46028. "dcm",
  46029. "deb",
  46030. "dex",
  46031. "djvu",
  46032. "dll",
  46033. "dmg",
  46034. "dng",
  46035. "doc",
  46036. "docm",
  46037. "docx",
  46038. "dot",
  46039. "dotm",
  46040. "dra",
  46041. "DS_Store",
  46042. "dsk",
  46043. "dts",
  46044. "dtshd",
  46045. "dvb",
  46046. "dwg",
  46047. "dxf",
  46048. "ecelp4800",
  46049. "ecelp7470",
  46050. "ecelp9600",
  46051. "egg",
  46052. "eol",
  46053. "eot",
  46054. "epub",
  46055. "exe",
  46056. "f4v",
  46057. "fbs",
  46058. "fh",
  46059. "fla",
  46060. "flac",
  46061. "flatpak",
  46062. "fli",
  46063. "flv",
  46064. "fpx",
  46065. "fst",
  46066. "fvt",
  46067. "g3",
  46068. "gh",
  46069. "gif",
  46070. "graffle",
  46071. "gz",
  46072. "gzip",
  46073. "h261",
  46074. "h263",
  46075. "h264",
  46076. "icns",
  46077. "ico",
  46078. "ief",
  46079. "img",
  46080. "ipa",
  46081. "iso",
  46082. "jar",
  46083. "jpeg",
  46084. "jpg",
  46085. "jpgv",
  46086. "jpm",
  46087. "jxr",
  46088. "key",
  46089. "ktx",
  46090. "lha",
  46091. "lib",
  46092. "lvp",
  46093. "lz",
  46094. "lzh",
  46095. "lzma",
  46096. "lzo",
  46097. "m3u",
  46098. "m4a",
  46099. "m4v",
  46100. "mar",
  46101. "mdi",
  46102. "mht",
  46103. "mid",
  46104. "midi",
  46105. "mj2",
  46106. "mka",
  46107. "mkv",
  46108. "mmr",
  46109. "mng",
  46110. "mobi",
  46111. "mov",
  46112. "movie",
  46113. "mp3",
  46114. "mp4",
  46115. "mp4a",
  46116. "mpeg",
  46117. "mpg",
  46118. "mpga",
  46119. "mxu",
  46120. "nef",
  46121. "npx",
  46122. "numbers",
  46123. "nupkg",
  46124. "o",
  46125. "odp",
  46126. "ods",
  46127. "odt",
  46128. "oga",
  46129. "ogg",
  46130. "ogv",
  46131. "otf",
  46132. "ott",
  46133. "pages",
  46134. "pbm",
  46135. "pcx",
  46136. "pdb",
  46137. "pdf",
  46138. "pea",
  46139. "pgm",
  46140. "pic",
  46141. "png",
  46142. "pnm",
  46143. "pot",
  46144. "potm",
  46145. "potx",
  46146. "ppa",
  46147. "ppam",
  46148. "ppm",
  46149. "pps",
  46150. "ppsm",
  46151. "ppsx",
  46152. "ppt",
  46153. "pptm",
  46154. "pptx",
  46155. "psd",
  46156. "pya",
  46157. "pyc",
  46158. "pyo",
  46159. "pyv",
  46160. "qt",
  46161. "rar",
  46162. "ras",
  46163. "raw",
  46164. "resources",
  46165. "rgb",
  46166. "rip",
  46167. "rlc",
  46168. "rmf",
  46169. "rmvb",
  46170. "rpm",
  46171. "rtf",
  46172. "rz",
  46173. "s3m",
  46174. "s7z",
  46175. "scpt",
  46176. "sgi",
  46177. "shar",
  46178. "snap",
  46179. "sil",
  46180. "sketch",
  46181. "slk",
  46182. "smv",
  46183. "snk",
  46184. "so",
  46185. "stl",
  46186. "suo",
  46187. "sub",
  46188. "swf",
  46189. "tar",
  46190. "tbz",
  46191. "tbz2",
  46192. "tga",
  46193. "tgz",
  46194. "thmx",
  46195. "tif",
  46196. "tiff",
  46197. "tlz",
  46198. "ttc",
  46199. "ttf",
  46200. "txz",
  46201. "udf",
  46202. "uvh",
  46203. "uvi",
  46204. "uvm",
  46205. "uvp",
  46206. "uvs",
  46207. "uvu",
  46208. "viv",
  46209. "vob",
  46210. "war",
  46211. "wav",
  46212. "wax",
  46213. "wbmp",
  46214. "wdp",
  46215. "weba",
  46216. "webm",
  46217. "webp",
  46218. "whl",
  46219. "wim",
  46220. "wm",
  46221. "wma",
  46222. "wmv",
  46223. "wmx",
  46224. "woff",
  46225. "woff2",
  46226. "wrm",
  46227. "wvx",
  46228. "xbm",
  46229. "xif",
  46230. "xla",
  46231. "xlam",
  46232. "xls",
  46233. "xlsb",
  46234. "xlsm",
  46235. "xlsx",
  46236. "xlt",
  46237. "xltm",
  46238. "xltx",
  46239. "xm",
  46240. "xmind",
  46241. "xpi",
  46242. "xpm",
  46243. "xwd",
  46244. "xz",
  46245. "z",
  46246. "zip",
  46247. "zipx"
  46248. ];
  46249. var binaryExtensions$1 = require$$0;
  46250. const path$8 = require$$0$4;
  46251. const binaryExtensions = binaryExtensions$1;
  46252. const extensions = new Set(binaryExtensions);
  46253. var isBinaryPath$1 = filePath => extensions.has(path$8.extname(filePath).slice(1).toLowerCase());
  46254. var constants$1 = {};
  46255. (function (exports) {
  46256. const {sep} = require$$0$4;
  46257. const {platform} = process;
  46258. const os = require$$2;
  46259. exports.EV_ALL = 'all';
  46260. exports.EV_READY = 'ready';
  46261. exports.EV_ADD = 'add';
  46262. exports.EV_CHANGE = 'change';
  46263. exports.EV_ADD_DIR = 'addDir';
  46264. exports.EV_UNLINK = 'unlink';
  46265. exports.EV_UNLINK_DIR = 'unlinkDir';
  46266. exports.EV_RAW = 'raw';
  46267. exports.EV_ERROR = 'error';
  46268. exports.STR_DATA = 'data';
  46269. exports.STR_END = 'end';
  46270. exports.STR_CLOSE = 'close';
  46271. exports.FSEVENT_CREATED = 'created';
  46272. exports.FSEVENT_MODIFIED = 'modified';
  46273. exports.FSEVENT_DELETED = 'deleted';
  46274. exports.FSEVENT_MOVED = 'moved';
  46275. exports.FSEVENT_CLONED = 'cloned';
  46276. exports.FSEVENT_UNKNOWN = 'unknown';
  46277. exports.FSEVENT_TYPE_FILE = 'file';
  46278. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  46279. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  46280. exports.KEY_LISTENERS = 'listeners';
  46281. exports.KEY_ERR = 'errHandlers';
  46282. exports.KEY_RAW = 'rawEmitters';
  46283. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  46284. exports.DOT_SLASH = `.${sep}`;
  46285. exports.BACK_SLASH_RE = /\\/g;
  46286. exports.DOUBLE_SLASH_RE = /\/\//;
  46287. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  46288. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  46289. exports.REPLACER_RE = /^\.[/\\]/;
  46290. exports.SLASH = '/';
  46291. exports.SLASH_SLASH = '//';
  46292. exports.BRACE_START = '{';
  46293. exports.BANG = '!';
  46294. exports.ONE_DOT = '.';
  46295. exports.TWO_DOTS = '..';
  46296. exports.STAR = '*';
  46297. exports.GLOBSTAR = '**';
  46298. exports.ROOT_GLOBSTAR = '/**/*';
  46299. exports.SLASH_GLOBSTAR = '/**';
  46300. exports.DIR_SUFFIX = 'Dir';
  46301. exports.ANYMATCH_OPTS = {dot: true};
  46302. exports.STRING_TYPE = 'string';
  46303. exports.FUNCTION_TYPE = 'function';
  46304. exports.EMPTY_STR = '';
  46305. exports.EMPTY_FN = () => {};
  46306. exports.IDENTITY_FN = val => val;
  46307. exports.isWindows = platform === 'win32';
  46308. exports.isMacos = platform === 'darwin';
  46309. exports.isLinux = platform === 'linux';
  46310. exports.isIBMi = os.type() === 'OS400';
  46311. } (constants$1));
  46312. const fs$7 = require$$0__default;
  46313. const sysPath$2 = require$$0$4;
  46314. const { promisify: promisify$2 } = require$$0$6;
  46315. const isBinaryPath = isBinaryPath$1;
  46316. const {
  46317. isWindows: isWindows$2,
  46318. isLinux,
  46319. EMPTY_FN: EMPTY_FN$2,
  46320. EMPTY_STR: EMPTY_STR$1,
  46321. KEY_LISTENERS,
  46322. KEY_ERR,
  46323. KEY_RAW,
  46324. HANDLER_KEYS,
  46325. EV_CHANGE: EV_CHANGE$2,
  46326. EV_ADD: EV_ADD$2,
  46327. EV_ADD_DIR: EV_ADD_DIR$2,
  46328. EV_ERROR: EV_ERROR$2,
  46329. STR_DATA: STR_DATA$1,
  46330. STR_END: STR_END$2,
  46331. BRACE_START: BRACE_START$1,
  46332. STAR
  46333. } = constants$1;
  46334. const THROTTLE_MODE_WATCH = 'watch';
  46335. const open$2 = promisify$2(fs$7.open);
  46336. const stat$2 = promisify$2(fs$7.stat);
  46337. const lstat$1 = promisify$2(fs$7.lstat);
  46338. const close = promisify$2(fs$7.close);
  46339. const fsrealpath = promisify$2(fs$7.realpath);
  46340. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  46341. // TODO: emit errors properly. Example: EMFILE on Macos.
  46342. const foreach = (val, fn) => {
  46343. if (val instanceof Set) {
  46344. val.forEach(fn);
  46345. } else {
  46346. fn(val);
  46347. }
  46348. };
  46349. const addAndConvert = (main, prop, item) => {
  46350. let container = main[prop];
  46351. if (!(container instanceof Set)) {
  46352. main[prop] = container = new Set([container]);
  46353. }
  46354. container.add(item);
  46355. };
  46356. const clearItem = cont => key => {
  46357. const set = cont[key];
  46358. if (set instanceof Set) {
  46359. set.clear();
  46360. } else {
  46361. delete cont[key];
  46362. }
  46363. };
  46364. const delFromSet = (main, prop, item) => {
  46365. const container = main[prop];
  46366. if (container instanceof Set) {
  46367. container.delete(item);
  46368. } else if (container === item) {
  46369. delete main[prop];
  46370. }
  46371. };
  46372. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  46373. /**
  46374. * @typedef {String} Path
  46375. */
  46376. // fs_watch helpers
  46377. // object to hold per-process fs_watch instances
  46378. // (may be shared across chokidar FSWatcher instances)
  46379. /**
  46380. * @typedef {Object} FsWatchContainer
  46381. * @property {Set} listeners
  46382. * @property {Set} errHandlers
  46383. * @property {Set} rawEmitters
  46384. * @property {fs.FSWatcher=} watcher
  46385. * @property {Boolean=} watcherUnusable
  46386. */
  46387. /**
  46388. * @type {Map<String,FsWatchContainer>}
  46389. */
  46390. const FsWatchInstances = new Map();
  46391. /**
  46392. * Instantiates the fs_watch interface
  46393. * @param {String} path to be watched
  46394. * @param {Object} options to be passed to fs_watch
  46395. * @param {Function} listener main event handler
  46396. * @param {Function} errHandler emits info about errors
  46397. * @param {Function} emitRaw emits raw event data
  46398. * @returns {fs.FSWatcher} new fsevents instance
  46399. */
  46400. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  46401. const handleEvent = (rawEvent, evPath) => {
  46402. listener(path);
  46403. emitRaw(rawEvent, evPath, {watchedPath: path});
  46404. // emit based on events occurring for files from a directory's watcher in
  46405. // case the file's watcher misses it (and rely on throttling to de-dupe)
  46406. if (evPath && path !== evPath) {
  46407. fsWatchBroadcast(
  46408. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  46409. );
  46410. }
  46411. };
  46412. try {
  46413. return fs$7.watch(path, options, handleEvent);
  46414. } catch (error) {
  46415. errHandler(error);
  46416. }
  46417. }
  46418. /**
  46419. * Helper for passing fs_watch event data to a collection of listeners
  46420. * @param {Path} fullPath absolute path bound to fs_watch instance
  46421. * @param {String} type listener type
  46422. * @param {*=} val1 arguments to be passed to listeners
  46423. * @param {*=} val2
  46424. * @param {*=} val3
  46425. */
  46426. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  46427. const cont = FsWatchInstances.get(fullPath);
  46428. if (!cont) return;
  46429. foreach(cont[type], (listener) => {
  46430. listener(val1, val2, val3);
  46431. });
  46432. };
  46433. /**
  46434. * Instantiates the fs_watch interface or binds listeners
  46435. * to an existing one covering the same file system entry
  46436. * @param {String} path
  46437. * @param {String} fullPath absolute path
  46438. * @param {Object} options to be passed to fs_watch
  46439. * @param {Object} handlers container for event listener functions
  46440. */
  46441. const setFsWatchListener = (path, fullPath, options, handlers) => {
  46442. const {listener, errHandler, rawEmitter} = handlers;
  46443. let cont = FsWatchInstances.get(fullPath);
  46444. /** @type {fs.FSWatcher=} */
  46445. let watcher;
  46446. if (!options.persistent) {
  46447. watcher = createFsWatchInstance(
  46448. path, options, listener, errHandler, rawEmitter
  46449. );
  46450. return watcher.close.bind(watcher);
  46451. }
  46452. if (cont) {
  46453. addAndConvert(cont, KEY_LISTENERS, listener);
  46454. addAndConvert(cont, KEY_ERR, errHandler);
  46455. addAndConvert(cont, KEY_RAW, rawEmitter);
  46456. } else {
  46457. watcher = createFsWatchInstance(
  46458. path,
  46459. options,
  46460. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  46461. errHandler, // no need to use broadcast here
  46462. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  46463. );
  46464. if (!watcher) return;
  46465. watcher.on(EV_ERROR$2, async (error) => {
  46466. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  46467. cont.watcherUnusable = true; // documented since Node 10.4.1
  46468. // Workaround for https://github.com/joyent/node/issues/4337
  46469. if (isWindows$2 && error.code === 'EPERM') {
  46470. try {
  46471. const fd = await open$2(path, 'r');
  46472. await close(fd);
  46473. broadcastErr(error);
  46474. } catch (err) {}
  46475. } else {
  46476. broadcastErr(error);
  46477. }
  46478. });
  46479. cont = {
  46480. listeners: listener,
  46481. errHandlers: errHandler,
  46482. rawEmitters: rawEmitter,
  46483. watcher
  46484. };
  46485. FsWatchInstances.set(fullPath, cont);
  46486. }
  46487. // const index = cont.listeners.indexOf(listener);
  46488. // removes this instance's listeners and closes the underlying fs_watch
  46489. // instance if there are no more listeners left
  46490. return () => {
  46491. delFromSet(cont, KEY_LISTENERS, listener);
  46492. delFromSet(cont, KEY_ERR, errHandler);
  46493. delFromSet(cont, KEY_RAW, rawEmitter);
  46494. if (isEmptySet(cont.listeners)) {
  46495. // Check to protect against issue gh-730.
  46496. // if (cont.watcherUnusable) {
  46497. cont.watcher.close();
  46498. // }
  46499. FsWatchInstances.delete(fullPath);
  46500. HANDLER_KEYS.forEach(clearItem(cont));
  46501. cont.watcher = undefined;
  46502. Object.freeze(cont);
  46503. }
  46504. };
  46505. };
  46506. // fs_watchFile helpers
  46507. // object to hold per-process fs_watchFile instances
  46508. // (may be shared across chokidar FSWatcher instances)
  46509. const FsWatchFileInstances = new Map();
  46510. /**
  46511. * Instantiates the fs_watchFile interface or binds listeners
  46512. * to an existing one covering the same file system entry
  46513. * @param {String} path to be watched
  46514. * @param {String} fullPath absolute path
  46515. * @param {Object} options options to be passed to fs_watchFile
  46516. * @param {Object} handlers container for event listener functions
  46517. * @returns {Function} closer
  46518. */
  46519. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  46520. const {listener, rawEmitter} = handlers;
  46521. let cont = FsWatchFileInstances.get(fullPath);
  46522. const copts = cont && cont.options;
  46523. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  46524. fs$7.unwatchFile(fullPath);
  46525. cont = undefined;
  46526. }
  46527. /* eslint-enable no-unused-vars, prefer-destructuring */
  46528. if (cont) {
  46529. addAndConvert(cont, KEY_LISTENERS, listener);
  46530. addAndConvert(cont, KEY_RAW, rawEmitter);
  46531. } else {
  46532. // TODO
  46533. // listeners.add(listener);
  46534. // rawEmitters.add(rawEmitter);
  46535. cont = {
  46536. listeners: listener,
  46537. rawEmitters: rawEmitter,
  46538. options,
  46539. watcher: fs$7.watchFile(fullPath, options, (curr, prev) => {
  46540. foreach(cont.rawEmitters, (rawEmitter) => {
  46541. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  46542. });
  46543. const currmtime = curr.mtimeMs;
  46544. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  46545. foreach(cont.listeners, (listener) => listener(path, curr));
  46546. }
  46547. })
  46548. };
  46549. FsWatchFileInstances.set(fullPath, cont);
  46550. }
  46551. // const index = cont.listeners.indexOf(listener);
  46552. // Removes this instance's listeners and closes the underlying fs_watchFile
  46553. // instance if there are no more listeners left.
  46554. return () => {
  46555. delFromSet(cont, KEY_LISTENERS, listener);
  46556. delFromSet(cont, KEY_RAW, rawEmitter);
  46557. if (isEmptySet(cont.listeners)) {
  46558. FsWatchFileInstances.delete(fullPath);
  46559. fs$7.unwatchFile(fullPath);
  46560. cont.options = cont.watcher = undefined;
  46561. Object.freeze(cont);
  46562. }
  46563. };
  46564. };
  46565. /**
  46566. * @mixin
  46567. */
  46568. let NodeFsHandler$1 = class NodeFsHandler {
  46569. /**
  46570. * @param {import("../index").FSWatcher} fsW
  46571. */
  46572. constructor(fsW) {
  46573. this.fsw = fsW;
  46574. this._boundHandleError = (error) => fsW._handleError(error);
  46575. }
  46576. /**
  46577. * Watch file for changes with fs_watchFile or fs_watch.
  46578. * @param {String} path to file or dir
  46579. * @param {Function} listener on fs change
  46580. * @returns {Function} closer for the watcher instance
  46581. */
  46582. _watchWithNodeFs(path, listener) {
  46583. const opts = this.fsw.options;
  46584. const directory = sysPath$2.dirname(path);
  46585. const basename = sysPath$2.basename(path);
  46586. const parent = this.fsw._getWatchedDir(directory);
  46587. parent.add(basename);
  46588. const absolutePath = sysPath$2.resolve(path);
  46589. const options = {persistent: opts.persistent};
  46590. if (!listener) listener = EMPTY_FN$2;
  46591. let closer;
  46592. if (opts.usePolling) {
  46593. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  46594. opts.binaryInterval : opts.interval;
  46595. closer = setFsWatchFileListener(path, absolutePath, options, {
  46596. listener,
  46597. rawEmitter: this.fsw._emitRaw
  46598. });
  46599. } else {
  46600. closer = setFsWatchListener(path, absolutePath, options, {
  46601. listener,
  46602. errHandler: this._boundHandleError,
  46603. rawEmitter: this.fsw._emitRaw
  46604. });
  46605. }
  46606. return closer;
  46607. }
  46608. /**
  46609. * Watch a file and emit add event if warranted.
  46610. * @param {Path} file Path
  46611. * @param {fs.Stats} stats result of fs_stat
  46612. * @param {Boolean} initialAdd was the file added at watch instantiation?
  46613. * @returns {Function} closer for the watcher instance
  46614. */
  46615. _handleFile(file, stats, initialAdd) {
  46616. if (this.fsw.closed) {
  46617. return;
  46618. }
  46619. const dirname = sysPath$2.dirname(file);
  46620. const basename = sysPath$2.basename(file);
  46621. const parent = this.fsw._getWatchedDir(dirname);
  46622. // stats is always present
  46623. let prevStats = stats;
  46624. // if the file is already being watched, do nothing
  46625. if (parent.has(basename)) return;
  46626. const listener = async (path, newStats) => {
  46627. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  46628. if (!newStats || newStats.mtimeMs === 0) {
  46629. try {
  46630. const newStats = await stat$2(file);
  46631. if (this.fsw.closed) return;
  46632. // Check that change event was not fired because of changed only accessTime.
  46633. const at = newStats.atimeMs;
  46634. const mt = newStats.mtimeMs;
  46635. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  46636. this.fsw._emit(EV_CHANGE$2, file, newStats);
  46637. }
  46638. if (isLinux && prevStats.ino !== newStats.ino) {
  46639. this.fsw._closeFile(path);
  46640. prevStats = newStats;
  46641. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  46642. } else {
  46643. prevStats = newStats;
  46644. }
  46645. } catch (error) {
  46646. // Fix issues where mtime is null but file is still present
  46647. this.fsw._remove(dirname, basename);
  46648. }
  46649. // add is about to be emitted if file not already tracked in parent
  46650. } else if (parent.has(basename)) {
  46651. // Check that change event was not fired because of changed only accessTime.
  46652. const at = newStats.atimeMs;
  46653. const mt = newStats.mtimeMs;
  46654. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  46655. this.fsw._emit(EV_CHANGE$2, file, newStats);
  46656. }
  46657. prevStats = newStats;
  46658. }
  46659. };
  46660. // kick off the watcher
  46661. const closer = this._watchWithNodeFs(file, listener);
  46662. // emit an add event if we're supposed to
  46663. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  46664. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  46665. this.fsw._emit(EV_ADD$2, file, stats);
  46666. }
  46667. return closer;
  46668. }
  46669. /**
  46670. * Handle symlinks encountered while reading a dir.
  46671. * @param {Object} entry returned by readdirp
  46672. * @param {String} directory path of dir being read
  46673. * @param {String} path of this item
  46674. * @param {String} item basename of this item
  46675. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  46676. */
  46677. async _handleSymlink(entry, directory, path, item) {
  46678. if (this.fsw.closed) {
  46679. return;
  46680. }
  46681. const full = entry.fullPath;
  46682. const dir = this.fsw._getWatchedDir(directory);
  46683. if (!this.fsw.options.followSymlinks) {
  46684. // watch symlink directly (don't follow) and detect changes
  46685. this.fsw._incrReadyCount();
  46686. let linkPath;
  46687. try {
  46688. linkPath = await fsrealpath(path);
  46689. } catch (e) {
  46690. this.fsw._emitReady();
  46691. return true;
  46692. }
  46693. if (this.fsw.closed) return;
  46694. if (dir.has(item)) {
  46695. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  46696. this.fsw._symlinkPaths.set(full, linkPath);
  46697. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  46698. }
  46699. } else {
  46700. dir.add(item);
  46701. this.fsw._symlinkPaths.set(full, linkPath);
  46702. this.fsw._emit(EV_ADD$2, path, entry.stats);
  46703. }
  46704. this.fsw._emitReady();
  46705. return true;
  46706. }
  46707. // don't follow the same symlink more than once
  46708. if (this.fsw._symlinkPaths.has(full)) {
  46709. return true;
  46710. }
  46711. this.fsw._symlinkPaths.set(full, true);
  46712. }
  46713. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  46714. // Normalize the directory name on Windows
  46715. directory = sysPath$2.join(directory, EMPTY_STR$1);
  46716. if (!wh.hasGlob) {
  46717. throttler = this.fsw._throttle('readdir', directory, 1000);
  46718. if (!throttler) return;
  46719. }
  46720. const previous = this.fsw._getWatchedDir(wh.path);
  46721. const current = new Set();
  46722. let stream = this.fsw._readdirp(directory, {
  46723. fileFilter: entry => wh.filterPath(entry),
  46724. directoryFilter: entry => wh.filterDir(entry),
  46725. depth: 0
  46726. }).on(STR_DATA$1, async (entry) => {
  46727. if (this.fsw.closed) {
  46728. stream = undefined;
  46729. return;
  46730. }
  46731. const item = entry.path;
  46732. let path = sysPath$2.join(directory, item);
  46733. current.add(item);
  46734. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  46735. return;
  46736. }
  46737. if (this.fsw.closed) {
  46738. stream = undefined;
  46739. return;
  46740. }
  46741. // Files that present in current directory snapshot
  46742. // but absent in previous are added to watch list and
  46743. // emit `add` event.
  46744. if (item === target || !target && !previous.has(item)) {
  46745. this.fsw._incrReadyCount();
  46746. // ensure relativeness of path is preserved in case of watcher reuse
  46747. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  46748. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  46749. }
  46750. }).on(EV_ERROR$2, this._boundHandleError);
  46751. return new Promise(resolve =>
  46752. stream.once(STR_END$2, () => {
  46753. if (this.fsw.closed) {
  46754. stream = undefined;
  46755. return;
  46756. }
  46757. const wasThrottled = throttler ? throttler.clear() : false;
  46758. resolve();
  46759. // Files that absent in current directory snapshot
  46760. // but present in previous emit `remove` event
  46761. // and are removed from @watched[directory].
  46762. previous.getChildren().filter((item) => {
  46763. return item !== directory &&
  46764. !current.has(item) &&
  46765. // in case of intersecting globs;
  46766. // a path may have been filtered out of this readdir, but
  46767. // shouldn't be removed because it matches a different glob
  46768. (!wh.hasGlob || wh.filterPath({
  46769. fullPath: sysPath$2.resolve(directory, item)
  46770. }));
  46771. }).forEach((item) => {
  46772. this.fsw._remove(directory, item);
  46773. });
  46774. stream = undefined;
  46775. // one more time for any missed in case changes came in extremely quickly
  46776. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  46777. })
  46778. );
  46779. }
  46780. /**
  46781. * Read directory to add / remove files from `@watched` list and re-read it on change.
  46782. * @param {String} dir fs path
  46783. * @param {fs.Stats} stats
  46784. * @param {Boolean} initialAdd
  46785. * @param {Number} depth relative to user-supplied path
  46786. * @param {String} target child path targeted for watch
  46787. * @param {Object} wh Common watch helpers for this path
  46788. * @param {String} realpath
  46789. * @returns {Promise<Function>} closer for the watcher instance.
  46790. */
  46791. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  46792. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  46793. const tracked = parentDir.has(sysPath$2.basename(dir));
  46794. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  46795. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  46796. }
  46797. // ensure dir is tracked (harmless if redundant)
  46798. parentDir.add(sysPath$2.basename(dir));
  46799. this.fsw._getWatchedDir(dir);
  46800. let throttler;
  46801. let closer;
  46802. const oDepth = this.fsw.options.depth;
  46803. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  46804. if (!target) {
  46805. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  46806. if (this.fsw.closed) return;
  46807. }
  46808. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  46809. // if current directory is removed, do nothing
  46810. if (stats && stats.mtimeMs === 0) return;
  46811. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  46812. });
  46813. }
  46814. return closer;
  46815. }
  46816. /**
  46817. * Handle added file, directory, or glob pattern.
  46818. * Delegates call to _handleFile / _handleDir after checks.
  46819. * @param {String} path to file or ir
  46820. * @param {Boolean} initialAdd was the file added at watch instantiation?
  46821. * @param {Object} priorWh depth relative to user-supplied path
  46822. * @param {Number} depth Child path actually targeted for watch
  46823. * @param {String=} target Child path actually targeted for watch
  46824. * @returns {Promise}
  46825. */
  46826. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  46827. const ready = this.fsw._emitReady;
  46828. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  46829. ready();
  46830. return false;
  46831. }
  46832. const wh = this.fsw._getWatchHelpers(path, depth);
  46833. if (!wh.hasGlob && priorWh) {
  46834. wh.hasGlob = priorWh.hasGlob;
  46835. wh.globFilter = priorWh.globFilter;
  46836. wh.filterPath = entry => priorWh.filterPath(entry);
  46837. wh.filterDir = entry => priorWh.filterDir(entry);
  46838. }
  46839. // evaluate what is at the path we're being asked to watch
  46840. try {
  46841. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  46842. if (this.fsw.closed) return;
  46843. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  46844. ready();
  46845. return false;
  46846. }
  46847. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  46848. let closer;
  46849. if (stats.isDirectory()) {
  46850. const absPath = sysPath$2.resolve(path);
  46851. const targetPath = follow ? await fsrealpath(path) : path;
  46852. if (this.fsw.closed) return;
  46853. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  46854. if (this.fsw.closed) return;
  46855. // preserve this symlink's target path
  46856. if (absPath !== targetPath && targetPath !== undefined) {
  46857. this.fsw._symlinkPaths.set(absPath, targetPath);
  46858. }
  46859. } else if (stats.isSymbolicLink()) {
  46860. const targetPath = follow ? await fsrealpath(path) : path;
  46861. if (this.fsw.closed) return;
  46862. const parent = sysPath$2.dirname(wh.watchPath);
  46863. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  46864. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  46865. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  46866. if (this.fsw.closed) return;
  46867. // preserve this symlink's target path
  46868. if (targetPath !== undefined) {
  46869. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  46870. }
  46871. } else {
  46872. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  46873. }
  46874. ready();
  46875. this.fsw._addPathCloser(path, closer);
  46876. return false;
  46877. } catch (error) {
  46878. if (this.fsw._handleError(error)) {
  46879. ready();
  46880. return path;
  46881. }
  46882. }
  46883. }
  46884. };
  46885. var nodefsHandler = NodeFsHandler$1;
  46886. var fseventsHandler = {exports: {}};
  46887. const fs$6 = require$$0__default;
  46888. const sysPath$1 = require$$0$4;
  46889. const { promisify: promisify$1 } = require$$0$6;
  46890. let fsevents;
  46891. try {
  46892. fsevents = __require('fsevents');
  46893. } catch (error) {
  46894. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  46895. }
  46896. if (fsevents) {
  46897. // TODO: real check
  46898. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  46899. if (mtch && mtch[1] && mtch[2]) {
  46900. const maj = Number.parseInt(mtch[1], 10);
  46901. const min = Number.parseInt(mtch[2], 10);
  46902. if (maj === 8 && min < 16) {
  46903. fsevents = undefined;
  46904. }
  46905. }
  46906. }
  46907. const {
  46908. EV_ADD: EV_ADD$1,
  46909. EV_CHANGE: EV_CHANGE$1,
  46910. EV_ADD_DIR: EV_ADD_DIR$1,
  46911. EV_UNLINK: EV_UNLINK$1,
  46912. EV_ERROR: EV_ERROR$1,
  46913. STR_DATA,
  46914. STR_END: STR_END$1,
  46915. FSEVENT_CREATED,
  46916. FSEVENT_MODIFIED,
  46917. FSEVENT_DELETED,
  46918. FSEVENT_MOVED,
  46919. // FSEVENT_CLONED,
  46920. FSEVENT_UNKNOWN,
  46921. FSEVENT_TYPE_FILE,
  46922. FSEVENT_TYPE_DIRECTORY,
  46923. FSEVENT_TYPE_SYMLINK,
  46924. ROOT_GLOBSTAR,
  46925. DIR_SUFFIX,
  46926. DOT_SLASH,
  46927. FUNCTION_TYPE: FUNCTION_TYPE$1,
  46928. EMPTY_FN: EMPTY_FN$1,
  46929. IDENTITY_FN
  46930. } = constants$1;
  46931. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  46932. const stat$1 = promisify$1(fs$6.stat);
  46933. const lstat = promisify$1(fs$6.lstat);
  46934. const realpath = promisify$1(fs$6.realpath);
  46935. const statMethods = { stat: stat$1, lstat };
  46936. /**
  46937. * @typedef {String} Path
  46938. */
  46939. /**
  46940. * @typedef {Object} FsEventsWatchContainer
  46941. * @property {Set<Function>} listeners
  46942. * @property {Function} rawEmitter
  46943. * @property {{stop: Function}} watcher
  46944. */
  46945. // fsevents instance helper functions
  46946. /**
  46947. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  46948. * @type {Map<Path,FsEventsWatchContainer>}
  46949. */
  46950. const FSEventsWatchers = new Map();
  46951. // Threshold of duplicate path prefixes at which to start
  46952. // consolidating going forward
  46953. const consolidateThreshhold = 10;
  46954. const wrongEventFlags = new Set([
  46955. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  46956. ]);
  46957. /**
  46958. * Instantiates the fsevents interface
  46959. * @param {Path} path path to be watched
  46960. * @param {Function} callback called when fsevents is bound and ready
  46961. * @returns {{stop: Function}} new fsevents instance
  46962. */
  46963. const createFSEventsInstance = (path, callback) => {
  46964. const stop = fsevents.watch(path, callback);
  46965. return {stop};
  46966. };
  46967. /**
  46968. * Instantiates the fsevents interface or binds listeners to an existing one covering
  46969. * the same file tree.
  46970. * @param {Path} path - to be watched
  46971. * @param {Path} realPath - real path for symlinks
  46972. * @param {Function} listener - called when fsevents emits events
  46973. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  46974. * @returns {Function} closer
  46975. */
  46976. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  46977. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  46978. const parentPath = sysPath$1.dirname(watchPath);
  46979. let cont = FSEventsWatchers.get(watchPath);
  46980. // If we've accumulated a substantial number of paths that
  46981. // could have been consolidated by watching one directory
  46982. // above the current one, create a watcher on the parent
  46983. // path instead, so that we do consolidate going forward.
  46984. if (couldConsolidate(parentPath)) {
  46985. watchPath = parentPath;
  46986. }
  46987. const resolvedPath = sysPath$1.resolve(path);
  46988. const hasSymlink = resolvedPath !== realPath;
  46989. const filteredListener = (fullPath, flags, info) => {
  46990. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  46991. if (
  46992. fullPath === resolvedPath ||
  46993. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  46994. ) listener(fullPath, flags, info);
  46995. };
  46996. // check if there is already a watcher on a parent path
  46997. // modifies `watchPath` to the parent path when it finds a match
  46998. let watchedParent = false;
  46999. for (const watchedPath of FSEventsWatchers.keys()) {
  47000. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  47001. watchPath = watchedPath;
  47002. cont = FSEventsWatchers.get(watchPath);
  47003. watchedParent = true;
  47004. break;
  47005. }
  47006. }
  47007. if (cont || watchedParent) {
  47008. cont.listeners.add(filteredListener);
  47009. } else {
  47010. cont = {
  47011. listeners: new Set([filteredListener]),
  47012. rawEmitter,
  47013. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  47014. if (!cont.listeners.size) return;
  47015. const info = fsevents.getInfo(fullPath, flags);
  47016. cont.listeners.forEach(list => {
  47017. list(fullPath, flags, info);
  47018. });
  47019. cont.rawEmitter(info.event, fullPath, info);
  47020. })
  47021. };
  47022. FSEventsWatchers.set(watchPath, cont);
  47023. }
  47024. // removes this instance's listeners and closes the underlying fsevents
  47025. // instance if there are no more listeners left
  47026. return () => {
  47027. const lst = cont.listeners;
  47028. lst.delete(filteredListener);
  47029. if (!lst.size) {
  47030. FSEventsWatchers.delete(watchPath);
  47031. if (cont.watcher) return cont.watcher.stop().then(() => {
  47032. cont.rawEmitter = cont.watcher = undefined;
  47033. Object.freeze(cont);
  47034. });
  47035. }
  47036. };
  47037. }
  47038. // Decide whether or not we should start a new higher-level
  47039. // parent watcher
  47040. const couldConsolidate = (path) => {
  47041. let count = 0;
  47042. for (const watchPath of FSEventsWatchers.keys()) {
  47043. if (watchPath.indexOf(path) === 0) {
  47044. count++;
  47045. if (count >= consolidateThreshhold) {
  47046. return true;
  47047. }
  47048. }
  47049. }
  47050. return false;
  47051. };
  47052. // returns boolean indicating whether fsevents can be used
  47053. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  47054. // determines subdirectory traversal levels from root to path
  47055. const calcDepth = (path, root) => {
  47056. let i = 0;
  47057. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  47058. return i;
  47059. };
  47060. // returns boolean indicating whether the fsevents' event info has the same type
  47061. // as the one returned by fs.stat
  47062. const sameTypes = (info, stats) => (
  47063. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  47064. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  47065. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  47066. );
  47067. /**
  47068. * @mixin
  47069. */
  47070. let FsEventsHandler$1 = class FsEventsHandler {
  47071. /**
  47072. * @param {import('../index').FSWatcher} fsw
  47073. */
  47074. constructor(fsw) {
  47075. this.fsw = fsw;
  47076. }
  47077. checkIgnored(path, stats) {
  47078. const ipaths = this.fsw._ignoredPaths;
  47079. if (this.fsw._isIgnored(path, stats)) {
  47080. ipaths.add(path);
  47081. if (stats && stats.isDirectory()) {
  47082. ipaths.add(path + ROOT_GLOBSTAR);
  47083. }
  47084. return true;
  47085. }
  47086. ipaths.delete(path);
  47087. ipaths.delete(path + ROOT_GLOBSTAR);
  47088. }
  47089. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  47090. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  47091. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47092. }
  47093. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  47094. try {
  47095. const stats = await stat$1(path);
  47096. if (this.fsw.closed) return;
  47097. if (sameTypes(info, stats)) {
  47098. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47099. } else {
  47100. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47101. }
  47102. } catch (error) {
  47103. if (error.code === 'EACCES') {
  47104. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47105. } else {
  47106. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47107. }
  47108. }
  47109. }
  47110. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  47111. if (this.fsw.closed || this.checkIgnored(path)) return;
  47112. if (event === EV_UNLINK$1) {
  47113. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  47114. // suppress unlink events on never before seen files
  47115. if (isDirectory || watchedDir.has(item)) {
  47116. this.fsw._remove(parent, item, isDirectory);
  47117. }
  47118. } else {
  47119. if (event === EV_ADD$1) {
  47120. // track new directories
  47121. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  47122. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  47123. // push symlinks back to the top of the stack to get handled
  47124. const curDepth = opts.depth === undefined ?
  47125. undefined : calcDepth(fullPath, realPath) + 1;
  47126. return this._addToFsEvents(path, false, true, curDepth);
  47127. }
  47128. // track new paths
  47129. // (other than symlinks being followed, which will be tracked soon)
  47130. this.fsw._getWatchedDir(parent).add(item);
  47131. }
  47132. /**
  47133. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  47134. */
  47135. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  47136. this.fsw._emit(eventName, path);
  47137. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  47138. }
  47139. }
  47140. /**
  47141. * Handle symlinks encountered during directory scan
  47142. * @param {String} watchPath - file/dir path to be watched with fsevents
  47143. * @param {String} realPath - real path (in case of symlinks)
  47144. * @param {Function} transform - path transformer
  47145. * @param {Function} globFilter - path filter in case a glob pattern was provided
  47146. * @returns {Function} closer for the watcher instance
  47147. */
  47148. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  47149. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  47150. const opts = this.fsw.options;
  47151. const watchCallback = async (fullPath, flags, info) => {
  47152. // PATCH: bypass the callback for better perf when fullPath hit the ignored file list
  47153. if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
  47154. if (
  47155. opts.depth !== undefined &&
  47156. calcDepth(fullPath, realPath) > opts.depth
  47157. ) return;
  47158. const path = transform(sysPath$1.join(
  47159. watchPath, sysPath$1.relative(watchPath, fullPath)
  47160. ));
  47161. if (globFilter && !globFilter(path)) return;
  47162. // ensure directories are tracked
  47163. const parent = sysPath$1.dirname(path);
  47164. const item = sysPath$1.basename(path);
  47165. const watchedDir = this.fsw._getWatchedDir(
  47166. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  47167. );
  47168. // correct for wrong events emitted
  47169. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  47170. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  47171. let stats;
  47172. try {
  47173. stats = await stat$1(path);
  47174. } catch (error) {}
  47175. if (this.fsw.closed) return;
  47176. if (this.checkIgnored(path, stats)) return;
  47177. if (sameTypes(info, stats)) {
  47178. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47179. } else {
  47180. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47181. }
  47182. } else {
  47183. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47184. }
  47185. } else {
  47186. switch (info.event) {
  47187. case FSEVENT_CREATED:
  47188. case FSEVENT_MODIFIED:
  47189. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47190. case FSEVENT_DELETED:
  47191. case FSEVENT_MOVED:
  47192. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  47193. }
  47194. }
  47195. };
  47196. const closer = setFSEventsListener(
  47197. watchPath,
  47198. realPath,
  47199. watchCallback,
  47200. this.fsw._emitRaw
  47201. );
  47202. this.fsw._emitReady();
  47203. return closer;
  47204. }
  47205. /**
  47206. * Handle symlinks encountered during directory scan
  47207. * @param {String} linkPath path to symlink
  47208. * @param {String} fullPath absolute path to the symlink
  47209. * @param {Function} transform pre-existing path transformer
  47210. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  47211. * @returns {Promise<void>}
  47212. */
  47213. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  47214. // don't follow the same symlink more than once
  47215. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  47216. this.fsw._symlinkPaths.set(fullPath, true);
  47217. this.fsw._incrReadyCount();
  47218. try {
  47219. const linkTarget = await realpath(linkPath);
  47220. if (this.fsw.closed) return;
  47221. if (this.fsw._isIgnored(linkTarget)) {
  47222. return this.fsw._emitReady();
  47223. }
  47224. this.fsw._incrReadyCount();
  47225. // add the linkTarget for watching with a wrapper for transform
  47226. // that causes emitted paths to incorporate the link's path
  47227. this._addToFsEvents(linkTarget || linkPath, (path) => {
  47228. let aliasedPath = linkPath;
  47229. if (linkTarget && linkTarget !== DOT_SLASH) {
  47230. aliasedPath = path.replace(linkTarget, linkPath);
  47231. } else if (path !== DOT_SLASH) {
  47232. aliasedPath = sysPath$1.join(linkPath, path);
  47233. }
  47234. return transform(aliasedPath);
  47235. }, false, curDepth);
  47236. } catch(error) {
  47237. if (this.fsw._handleError(error)) {
  47238. return this.fsw._emitReady();
  47239. }
  47240. }
  47241. }
  47242. /**
  47243. *
  47244. * @param {Path} newPath
  47245. * @param {fs.Stats} stats
  47246. */
  47247. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  47248. const pp = processPath(newPath);
  47249. const isDir = stats.isDirectory();
  47250. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  47251. const base = sysPath$1.basename(pp);
  47252. // ensure empty dirs get tracked
  47253. if (isDir) this.fsw._getWatchedDir(pp);
  47254. if (dirObj.has(base)) return;
  47255. dirObj.add(base);
  47256. if (!opts.ignoreInitial || forceAdd === true) {
  47257. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  47258. }
  47259. }
  47260. initWatch(realPath, path, wh, processPath) {
  47261. if (this.fsw.closed) return;
  47262. const closer = this._watchWithFsEvents(
  47263. wh.watchPath,
  47264. sysPath$1.resolve(realPath || wh.watchPath),
  47265. processPath,
  47266. wh.globFilter
  47267. );
  47268. this.fsw._addPathCloser(path, closer);
  47269. }
  47270. /**
  47271. * Handle added path with fsevents
  47272. * @param {String} path file/dir path or glob pattern
  47273. * @param {Function|Boolean=} transform converts working path to what the user expects
  47274. * @param {Boolean=} forceAdd ensure add is emitted
  47275. * @param {Number=} priorDepth Level of subdirectories already traversed.
  47276. * @returns {Promise<void>}
  47277. */
  47278. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  47279. if (this.fsw.closed) {
  47280. return;
  47281. }
  47282. const opts = this.fsw.options;
  47283. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  47284. const wh = this.fsw._getWatchHelpers(path);
  47285. // evaluate what is at the path we're being asked to watch
  47286. try {
  47287. const stats = await statMethods[wh.statMethod](wh.watchPath);
  47288. if (this.fsw.closed) return;
  47289. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  47290. throw null;
  47291. }
  47292. if (stats.isDirectory()) {
  47293. // emit addDir unless this is a glob parent
  47294. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  47295. // don't recurse further if it would exceed depth setting
  47296. if (priorDepth && priorDepth > opts.depth) return;
  47297. // scan the contents of the dir
  47298. this.fsw._readdirp(wh.watchPath, {
  47299. fileFilter: entry => wh.filterPath(entry),
  47300. directoryFilter: entry => wh.filterDir(entry),
  47301. ...Depth(opts.depth - (priorDepth || 0))
  47302. }).on(STR_DATA, (entry) => {
  47303. // need to check filterPath on dirs b/c filterDir is less restrictive
  47304. if (this.fsw.closed) {
  47305. return;
  47306. }
  47307. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  47308. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  47309. const {fullPath} = entry;
  47310. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  47311. // preserve the current depth here since it can't be derived from
  47312. // real paths past the symlink
  47313. const curDepth = opts.depth === undefined ?
  47314. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  47315. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  47316. } else {
  47317. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  47318. }
  47319. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  47320. this.fsw._emitReady();
  47321. });
  47322. } else {
  47323. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  47324. this.fsw._emitReady();
  47325. }
  47326. } catch (error) {
  47327. if (!error || this.fsw._handleError(error)) {
  47328. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  47329. this.fsw._emitReady();
  47330. this.fsw._emitReady();
  47331. }
  47332. }
  47333. if (opts.persistent && forceAdd !== true) {
  47334. if (typeof transform === FUNCTION_TYPE$1) {
  47335. // realpath has already been resolved
  47336. this.initWatch(undefined, path, wh, processPath);
  47337. } else {
  47338. let realPath;
  47339. try {
  47340. realPath = await realpath(wh.watchPath);
  47341. } catch (e) {}
  47342. this.initWatch(realPath, path, wh, processPath);
  47343. }
  47344. }
  47345. }
  47346. };
  47347. fseventsHandler.exports = FsEventsHandler$1;
  47348. fseventsHandler.exports.canUse = canUse;
  47349. var fseventsHandlerExports = fseventsHandler.exports;
  47350. const { EventEmitter: EventEmitter$2 } = require$$0$5;
  47351. const fs$5 = require$$0__default;
  47352. const sysPath = require$$0$4;
  47353. const { promisify } = require$$0$6;
  47354. const readdirp = readdirp_1;
  47355. const anymatch = anymatchExports.default;
  47356. const globParent = globParent$2;
  47357. const isGlob = isGlob$2;
  47358. const braces = braces_1;
  47359. const normalizePath = normalizePath$2;
  47360. const NodeFsHandler = nodefsHandler;
  47361. const FsEventsHandler = fseventsHandlerExports;
  47362. const {
  47363. EV_ALL,
  47364. EV_READY,
  47365. EV_ADD,
  47366. EV_CHANGE,
  47367. EV_UNLINK,
  47368. EV_ADD_DIR,
  47369. EV_UNLINK_DIR,
  47370. EV_RAW,
  47371. EV_ERROR,
  47372. STR_CLOSE,
  47373. STR_END,
  47374. BACK_SLASH_RE,
  47375. DOUBLE_SLASH_RE,
  47376. SLASH_OR_BACK_SLASH_RE,
  47377. DOT_RE,
  47378. REPLACER_RE,
  47379. SLASH,
  47380. SLASH_SLASH,
  47381. BRACE_START,
  47382. BANG,
  47383. ONE_DOT,
  47384. TWO_DOTS,
  47385. GLOBSTAR,
  47386. SLASH_GLOBSTAR,
  47387. ANYMATCH_OPTS,
  47388. STRING_TYPE,
  47389. FUNCTION_TYPE,
  47390. EMPTY_STR,
  47391. EMPTY_FN,
  47392. isWindows: isWindows$1,
  47393. isMacos,
  47394. isIBMi
  47395. } = constants$1;
  47396. const stat = promisify(fs$5.stat);
  47397. const readdir = promisify(fs$5.readdir);
  47398. /**
  47399. * @typedef {String} Path
  47400. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  47401. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  47402. */
  47403. /**
  47404. *
  47405. * @typedef {Object} WatchHelpers
  47406. * @property {Boolean} followSymlinks
  47407. * @property {'stat'|'lstat'} statMethod
  47408. * @property {Path} path
  47409. * @property {Path} watchPath
  47410. * @property {Function} entryPath
  47411. * @property {Boolean} hasGlob
  47412. * @property {Object} globFilter
  47413. * @property {Function} filterPath
  47414. * @property {Function} filterDir
  47415. */
  47416. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  47417. const flatten = (list, result = []) => {
  47418. list.forEach(item => {
  47419. if (Array.isArray(item)) {
  47420. flatten(item, result);
  47421. } else {
  47422. result.push(item);
  47423. }
  47424. });
  47425. return result;
  47426. };
  47427. const unifyPaths = (paths_) => {
  47428. /**
  47429. * @type {Array<String>}
  47430. */
  47431. const paths = flatten(arrify(paths_));
  47432. if (!paths.every(p => typeof p === STRING_TYPE)) {
  47433. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  47434. }
  47435. return paths.map(normalizePathToUnix);
  47436. };
  47437. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  47438. // because "//StoragePC/DrivePool/Movies" is a valid network path
  47439. const toUnix = (string) => {
  47440. let str = string.replace(BACK_SLASH_RE, SLASH);
  47441. let prepend = false;
  47442. if (str.startsWith(SLASH_SLASH)) {
  47443. prepend = true;
  47444. }
  47445. while (str.match(DOUBLE_SLASH_RE)) {
  47446. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  47447. }
  47448. if (prepend) {
  47449. str = SLASH + str;
  47450. }
  47451. return str;
  47452. };
  47453. // Our version of upath.normalize
  47454. // TODO: this is not equal to path-normalize module - investigate why
  47455. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  47456. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  47457. if (typeof path !== STRING_TYPE) return path;
  47458. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  47459. };
  47460. const getAbsolutePath = (path, cwd) => {
  47461. if (sysPath.isAbsolute(path)) {
  47462. return path;
  47463. }
  47464. if (path.startsWith(BANG)) {
  47465. return BANG + sysPath.join(cwd, path.slice(1));
  47466. }
  47467. return sysPath.join(cwd, path);
  47468. };
  47469. const undef = (opts, key) => opts[key] === undefined;
  47470. /**
  47471. * Directory entry.
  47472. * @property {Path} path
  47473. * @property {Set<Path>} items
  47474. */
  47475. class DirEntry {
  47476. /**
  47477. * @param {Path} dir
  47478. * @param {Function} removeWatcher
  47479. */
  47480. constructor(dir, removeWatcher) {
  47481. this.path = dir;
  47482. this._removeWatcher = removeWatcher;
  47483. /** @type {Set<Path>} */
  47484. this.items = new Set();
  47485. }
  47486. add(item) {
  47487. const {items} = this;
  47488. if (!items) return;
  47489. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  47490. }
  47491. async remove(item) {
  47492. const {items} = this;
  47493. if (!items) return;
  47494. items.delete(item);
  47495. if (items.size > 0) return;
  47496. const dir = this.path;
  47497. try {
  47498. await readdir(dir);
  47499. } catch (err) {
  47500. if (this._removeWatcher) {
  47501. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  47502. }
  47503. }
  47504. }
  47505. has(item) {
  47506. const {items} = this;
  47507. if (!items) return;
  47508. return items.has(item);
  47509. }
  47510. /**
  47511. * @returns {Array<String>}
  47512. */
  47513. getChildren() {
  47514. const {items} = this;
  47515. if (!items) return;
  47516. return [...items.values()];
  47517. }
  47518. dispose() {
  47519. this.items.clear();
  47520. delete this.path;
  47521. delete this._removeWatcher;
  47522. delete this.items;
  47523. Object.freeze(this);
  47524. }
  47525. }
  47526. const STAT_METHOD_F = 'stat';
  47527. const STAT_METHOD_L = 'lstat';
  47528. class WatchHelper {
  47529. constructor(path, watchPath, follow, fsw) {
  47530. this.fsw = fsw;
  47531. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  47532. this.watchPath = watchPath;
  47533. this.fullWatchPath = sysPath.resolve(watchPath);
  47534. this.hasGlob = watchPath !== path;
  47535. /** @type {object|boolean} */
  47536. if (path === EMPTY_STR) this.hasGlob = false;
  47537. this.globSymlink = this.hasGlob && follow ? undefined : false;
  47538. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  47539. this.dirParts = this.getDirParts(path);
  47540. this.dirParts.forEach((parts) => {
  47541. if (parts.length > 1) parts.pop();
  47542. });
  47543. this.followSymlinks = follow;
  47544. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  47545. }
  47546. checkGlobSymlink(entry) {
  47547. // only need to resolve once
  47548. // first entry should always have entry.parentDir === EMPTY_STR
  47549. if (this.globSymlink === undefined) {
  47550. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  47551. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  47552. }
  47553. if (this.globSymlink) {
  47554. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  47555. }
  47556. return entry.fullPath;
  47557. }
  47558. entryPath(entry) {
  47559. return sysPath.join(this.watchPath,
  47560. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  47561. );
  47562. }
  47563. filterPath(entry) {
  47564. const {stats} = entry;
  47565. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  47566. const resolvedPath = this.entryPath(entry);
  47567. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  47568. this.globFilter(resolvedPath) : true;
  47569. return matchesGlob &&
  47570. this.fsw._isntIgnored(resolvedPath, stats) &&
  47571. this.fsw._hasReadPermissions(stats);
  47572. }
  47573. getDirParts(path) {
  47574. if (!this.hasGlob) return [];
  47575. const parts = [];
  47576. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  47577. expandedPath.forEach((path) => {
  47578. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  47579. });
  47580. return parts;
  47581. }
  47582. filterDir(entry) {
  47583. if (this.hasGlob) {
  47584. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  47585. let globstar = false;
  47586. this.unmatchedGlob = !this.dirParts.some((parts) => {
  47587. return parts.every((part, i) => {
  47588. if (part === GLOBSTAR) globstar = true;
  47589. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  47590. });
  47591. });
  47592. }
  47593. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  47594. }
  47595. }
  47596. /**
  47597. * Watches files & directories for changes. Emitted events:
  47598. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  47599. *
  47600. * new FSWatcher()
  47601. * .add(directories)
  47602. * .on('add', path => log('File', path, 'was added'))
  47603. */
  47604. class FSWatcher extends EventEmitter$2 {
  47605. // Not indenting methods for history sake; for now.
  47606. constructor(_opts) {
  47607. super();
  47608. const opts = {};
  47609. if (_opts) Object.assign(opts, _opts); // for frozen objects
  47610. /** @type {Map<String, DirEntry>} */
  47611. this._watched = new Map();
  47612. /** @type {Map<String, Array>} */
  47613. this._closers = new Map();
  47614. /** @type {Set<String>} */
  47615. this._ignoredPaths = new Set();
  47616. /** @type {Map<ThrottleType, Map>} */
  47617. this._throttled = new Map();
  47618. /** @type {Map<Path, String|Boolean>} */
  47619. this._symlinkPaths = new Map();
  47620. this._streams = new Set();
  47621. this.closed = false;
  47622. // Set up default options.
  47623. if (undef(opts, 'persistent')) opts.persistent = true;
  47624. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  47625. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  47626. if (undef(opts, 'interval')) opts.interval = 100;
  47627. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  47628. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  47629. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  47630. // Enable fsevents on OS X when polling isn't explicitly enabled.
  47631. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  47632. // If we can't use fsevents, ensure the options reflect it's disabled.
  47633. const canUseFsEvents = FsEventsHandler.canUse();
  47634. if (!canUseFsEvents) opts.useFsEvents = false;
  47635. // Use polling on Mac if not using fsevents.
  47636. // Other platforms use non-polling fs_watch.
  47637. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  47638. opts.usePolling = isMacos;
  47639. }
  47640. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  47641. if(isIBMi) {
  47642. opts.usePolling = true;
  47643. }
  47644. // Global override (useful for end-developers that need to force polling for all
  47645. // instances of chokidar, regardless of usage/dependency depth)
  47646. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  47647. if (envPoll !== undefined) {
  47648. const envLower = envPoll.toLowerCase();
  47649. if (envLower === 'false' || envLower === '0') {
  47650. opts.usePolling = false;
  47651. } else if (envLower === 'true' || envLower === '1') {
  47652. opts.usePolling = true;
  47653. } else {
  47654. opts.usePolling = !!envLower;
  47655. }
  47656. }
  47657. const envInterval = process.env.CHOKIDAR_INTERVAL;
  47658. if (envInterval) {
  47659. opts.interval = Number.parseInt(envInterval, 10);
  47660. }
  47661. // Editor atomic write normalization enabled by default with fs.watch
  47662. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  47663. if (opts.atomic) this._pendingUnlinks = new Map();
  47664. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  47665. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  47666. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  47667. const awf = opts.awaitWriteFinish;
  47668. if (awf) {
  47669. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  47670. if (!awf.pollInterval) awf.pollInterval = 100;
  47671. this._pendingWrites = new Map();
  47672. }
  47673. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  47674. let readyCalls = 0;
  47675. this._emitReady = () => {
  47676. readyCalls++;
  47677. if (readyCalls >= this._readyCount) {
  47678. this._emitReady = EMPTY_FN;
  47679. this._readyEmitted = true;
  47680. // use process.nextTick to allow time for listener to be bound
  47681. process.nextTick(() => this.emit(EV_READY));
  47682. }
  47683. };
  47684. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  47685. this._readyEmitted = false;
  47686. this.options = opts;
  47687. // Initialize with proper watcher.
  47688. if (opts.useFsEvents) {
  47689. this._fsEventsHandler = new FsEventsHandler(this);
  47690. } else {
  47691. this._nodeFsHandler = new NodeFsHandler(this);
  47692. }
  47693. // You’re frozen when your heart’s not open.
  47694. Object.freeze(opts);
  47695. }
  47696. // Public methods
  47697. /**
  47698. * Adds paths to be watched on an existing FSWatcher instance
  47699. * @param {Path|Array<Path>} paths_
  47700. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  47701. * @param {Boolean=} _internal private; indicates a non-user add
  47702. * @returns {FSWatcher} for chaining
  47703. */
  47704. add(paths_, _origAdd, _internal) {
  47705. const {cwd, disableGlobbing} = this.options;
  47706. this.closed = false;
  47707. let paths = unifyPaths(paths_);
  47708. if (cwd) {
  47709. paths = paths.map((path) => {
  47710. const absPath = getAbsolutePath(path, cwd);
  47711. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  47712. if (disableGlobbing || !isGlob(path)) {
  47713. return absPath;
  47714. }
  47715. return normalizePath(absPath);
  47716. });
  47717. }
  47718. // set aside negated glob strings
  47719. paths = paths.filter((path) => {
  47720. if (path.startsWith(BANG)) {
  47721. this._ignoredPaths.add(path.slice(1));
  47722. return false;
  47723. }
  47724. // if a path is being added that was previously ignored, stop ignoring it
  47725. this._ignoredPaths.delete(path);
  47726. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  47727. // reset the cached userIgnored anymatch fn
  47728. // to make ignoredPaths changes effective
  47729. this._userIgnored = undefined;
  47730. return true;
  47731. });
  47732. if (this.options.useFsEvents && this._fsEventsHandler) {
  47733. if (!this._readyCount) this._readyCount = paths.length;
  47734. if (this.options.persistent) this._readyCount *= 2;
  47735. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  47736. } else {
  47737. if (!this._readyCount) this._readyCount = 0;
  47738. this._readyCount += paths.length;
  47739. Promise.all(
  47740. paths.map(async path => {
  47741. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  47742. if (res) this._emitReady();
  47743. return res;
  47744. })
  47745. ).then(results => {
  47746. if (this.closed) return;
  47747. results.filter(item => item).forEach(item => {
  47748. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  47749. });
  47750. });
  47751. }
  47752. return this;
  47753. }
  47754. /**
  47755. * Close watchers or start ignoring events from specified paths.
  47756. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  47757. * @returns {FSWatcher} for chaining
  47758. */
  47759. unwatch(paths_) {
  47760. if (this.closed) return this;
  47761. const paths = unifyPaths(paths_);
  47762. const {cwd} = this.options;
  47763. paths.forEach((path) => {
  47764. // convert to absolute path unless relative path already matches
  47765. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  47766. if (cwd) path = sysPath.join(cwd, path);
  47767. path = sysPath.resolve(path);
  47768. }
  47769. this._closePath(path);
  47770. this._ignoredPaths.add(path);
  47771. if (this._watched.has(path)) {
  47772. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  47773. }
  47774. // reset the cached userIgnored anymatch fn
  47775. // to make ignoredPaths changes effective
  47776. this._userIgnored = undefined;
  47777. });
  47778. return this;
  47779. }
  47780. /**
  47781. * Close watchers and remove all listeners from watched paths.
  47782. * @returns {Promise<void>}.
  47783. */
  47784. close() {
  47785. if (this.closed) return this._closePromise;
  47786. this.closed = true;
  47787. // Memory management.
  47788. this.removeAllListeners();
  47789. const closers = [];
  47790. this._closers.forEach(closerList => closerList.forEach(closer => {
  47791. const promise = closer();
  47792. if (promise instanceof Promise) closers.push(promise);
  47793. }));
  47794. this._streams.forEach(stream => stream.destroy());
  47795. this._userIgnored = undefined;
  47796. this._readyCount = 0;
  47797. this._readyEmitted = false;
  47798. this._watched.forEach(dirent => dirent.dispose());
  47799. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  47800. this[`_${key}`].clear();
  47801. });
  47802. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  47803. return this._closePromise;
  47804. }
  47805. /**
  47806. * Expose list of watched paths
  47807. * @returns {Object} for chaining
  47808. */
  47809. getWatched() {
  47810. const watchList = {};
  47811. this._watched.forEach((entry, dir) => {
  47812. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  47813. watchList[key || ONE_DOT] = entry.getChildren().sort();
  47814. });
  47815. return watchList;
  47816. }
  47817. emitWithAll(event, args) {
  47818. this.emit(...args);
  47819. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  47820. }
  47821. // Common helpers
  47822. // --------------
  47823. /**
  47824. * Normalize and emit events.
  47825. * Calling _emit DOES NOT MEAN emit() would be called!
  47826. * @param {EventName} event Type of event
  47827. * @param {Path} path File or directory path
  47828. * @param {*=} val1 arguments to be passed with event
  47829. * @param {*=} val2
  47830. * @param {*=} val3
  47831. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  47832. */
  47833. async _emit(event, path, val1, val2, val3) {
  47834. if (this.closed) return;
  47835. const opts = this.options;
  47836. if (isWindows$1) path = sysPath.normalize(path);
  47837. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  47838. /** @type Array<any> */
  47839. const args = [event, path];
  47840. if (val3 !== undefined) args.push(val1, val2, val3);
  47841. else if (val2 !== undefined) args.push(val1, val2);
  47842. else if (val1 !== undefined) args.push(val1);
  47843. const awf = opts.awaitWriteFinish;
  47844. let pw;
  47845. if (awf && (pw = this._pendingWrites.get(path))) {
  47846. pw.lastChange = new Date();
  47847. return this;
  47848. }
  47849. if (opts.atomic) {
  47850. if (event === EV_UNLINK) {
  47851. this._pendingUnlinks.set(path, args);
  47852. setTimeout(() => {
  47853. this._pendingUnlinks.forEach((entry, path) => {
  47854. this.emit(...entry);
  47855. this.emit(EV_ALL, ...entry);
  47856. this._pendingUnlinks.delete(path);
  47857. });
  47858. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  47859. return this;
  47860. }
  47861. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  47862. event = args[0] = EV_CHANGE;
  47863. this._pendingUnlinks.delete(path);
  47864. }
  47865. }
  47866. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  47867. const awfEmit = (err, stats) => {
  47868. if (err) {
  47869. event = args[0] = EV_ERROR;
  47870. args[1] = err;
  47871. this.emitWithAll(event, args);
  47872. } else if (stats) {
  47873. // if stats doesn't exist the file must have been deleted
  47874. if (args.length > 2) {
  47875. args[2] = stats;
  47876. } else {
  47877. args.push(stats);
  47878. }
  47879. this.emitWithAll(event, args);
  47880. }
  47881. };
  47882. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  47883. return this;
  47884. }
  47885. if (event === EV_CHANGE) {
  47886. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  47887. if (isThrottled) return this;
  47888. }
  47889. if (opts.alwaysStat && val1 === undefined &&
  47890. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  47891. ) {
  47892. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  47893. let stats;
  47894. try {
  47895. stats = await stat(fullPath);
  47896. } catch (err) {}
  47897. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  47898. if (!stats || this.closed) return;
  47899. args.push(stats);
  47900. }
  47901. this.emitWithAll(event, args);
  47902. return this;
  47903. }
  47904. /**
  47905. * Common handler for errors
  47906. * @param {Error} error
  47907. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  47908. */
  47909. _handleError(error) {
  47910. const code = error && error.code;
  47911. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  47912. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  47913. ) {
  47914. this.emit(EV_ERROR, error);
  47915. }
  47916. return error || this.closed;
  47917. }
  47918. /**
  47919. * Helper utility for throttling
  47920. * @param {ThrottleType} actionType type being throttled
  47921. * @param {Path} path being acted upon
  47922. * @param {Number} timeout duration of time to suppress duplicate actions
  47923. * @returns {Object|false} tracking object or false if action should be suppressed
  47924. */
  47925. _throttle(actionType, path, timeout) {
  47926. if (!this._throttled.has(actionType)) {
  47927. this._throttled.set(actionType, new Map());
  47928. }
  47929. /** @type {Map<Path, Object>} */
  47930. const action = this._throttled.get(actionType);
  47931. /** @type {Object} */
  47932. const actionPath = action.get(path);
  47933. if (actionPath) {
  47934. actionPath.count++;
  47935. return false;
  47936. }
  47937. let timeoutObject;
  47938. const clear = () => {
  47939. const item = action.get(path);
  47940. const count = item ? item.count : 0;
  47941. action.delete(path);
  47942. clearTimeout(timeoutObject);
  47943. if (item) clearTimeout(item.timeoutObject);
  47944. return count;
  47945. };
  47946. timeoutObject = setTimeout(clear, timeout);
  47947. const thr = {timeoutObject, clear, count: 0};
  47948. action.set(path, thr);
  47949. return thr;
  47950. }
  47951. _incrReadyCount() {
  47952. return this._readyCount++;
  47953. }
  47954. /**
  47955. * Awaits write operation to finish.
  47956. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  47957. * @param {Path} path being acted upon
  47958. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  47959. * @param {EventName} event
  47960. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  47961. */
  47962. _awaitWriteFinish(path, threshold, event, awfEmit) {
  47963. let timeoutHandler;
  47964. let fullPath = path;
  47965. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  47966. fullPath = sysPath.join(this.options.cwd, path);
  47967. }
  47968. const now = new Date();
  47969. const awaitWriteFinish = (prevStat) => {
  47970. fs$5.stat(fullPath, (err, curStat) => {
  47971. if (err || !this._pendingWrites.has(path)) {
  47972. if (err && err.code !== 'ENOENT') awfEmit(err);
  47973. return;
  47974. }
  47975. const now = Number(new Date());
  47976. if (prevStat && curStat.size !== prevStat.size) {
  47977. this._pendingWrites.get(path).lastChange = now;
  47978. }
  47979. const pw = this._pendingWrites.get(path);
  47980. const df = now - pw.lastChange;
  47981. if (df >= threshold) {
  47982. this._pendingWrites.delete(path);
  47983. awfEmit(undefined, curStat);
  47984. } else {
  47985. timeoutHandler = setTimeout(
  47986. awaitWriteFinish,
  47987. this.options.awaitWriteFinish.pollInterval,
  47988. curStat
  47989. );
  47990. }
  47991. });
  47992. };
  47993. if (!this._pendingWrites.has(path)) {
  47994. this._pendingWrites.set(path, {
  47995. lastChange: now,
  47996. cancelWait: () => {
  47997. this._pendingWrites.delete(path);
  47998. clearTimeout(timeoutHandler);
  47999. return event;
  48000. }
  48001. });
  48002. timeoutHandler = setTimeout(
  48003. awaitWriteFinish,
  48004. this.options.awaitWriteFinish.pollInterval
  48005. );
  48006. }
  48007. }
  48008. _getGlobIgnored() {
  48009. return [...this._ignoredPaths.values()];
  48010. }
  48011. /**
  48012. * Determines whether user has asked to ignore this path.
  48013. * @param {Path} path filepath or dir
  48014. * @param {fs.Stats=} stats result of fs.stat
  48015. * @returns {Boolean}
  48016. */
  48017. _isIgnored(path, stats) {
  48018. if (this.options.atomic && DOT_RE.test(path)) return true;
  48019. if (!this._userIgnored) {
  48020. const {cwd} = this.options;
  48021. const ign = this.options.ignored;
  48022. const ignored = ign && ign.map(normalizeIgnored(cwd));
  48023. const paths = arrify(ignored)
  48024. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  48025. .map((path) => path + SLASH_GLOBSTAR);
  48026. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  48027. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  48028. }
  48029. return this._userIgnored([path, stats]);
  48030. }
  48031. _isntIgnored(path, stat) {
  48032. return !this._isIgnored(path, stat);
  48033. }
  48034. /**
  48035. * Provides a set of common helpers and properties relating to symlink and glob handling.
  48036. * @param {Path} path file, directory, or glob pattern being watched
  48037. * @param {Number=} depth at any depth > 0, this isn't a glob
  48038. * @returns {WatchHelper} object containing helpers for this path
  48039. */
  48040. _getWatchHelpers(path, depth) {
  48041. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  48042. const follow = this.options.followSymlinks;
  48043. return new WatchHelper(path, watchPath, follow, this);
  48044. }
  48045. // Directory helpers
  48046. // -----------------
  48047. /**
  48048. * Provides directory tracking objects
  48049. * @param {String} directory path of the directory
  48050. * @returns {DirEntry} the directory's tracking object
  48051. */
  48052. _getWatchedDir(directory) {
  48053. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  48054. const dir = sysPath.resolve(directory);
  48055. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  48056. return this._watched.get(dir);
  48057. }
  48058. // File helpers
  48059. // ------------
  48060. /**
  48061. * Check for read permissions.
  48062. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  48063. * @param {fs.Stats} stats - object, result of fs_stat
  48064. * @returns {Boolean} indicates whether the file can be read
  48065. */
  48066. _hasReadPermissions(stats) {
  48067. if (this.options.ignorePermissionErrors) return true;
  48068. // stats.mode may be bigint
  48069. const md = stats && Number.parseInt(stats.mode, 10);
  48070. const st = md & 0o777;
  48071. const it = Number.parseInt(st.toString(8)[0], 10);
  48072. return Boolean(4 & it);
  48073. }
  48074. /**
  48075. * Handles emitting unlink events for
  48076. * files and directories, and via recursion, for
  48077. * files and directories within directories that are unlinked
  48078. * @param {String} directory within which the following item is located
  48079. * @param {String} item base path of item/directory
  48080. * @returns {void}
  48081. */
  48082. _remove(directory, item, isDirectory) {
  48083. // if what is being deleted is a directory, get that directory's paths
  48084. // for recursive deleting and cleaning of watched object
  48085. // if it is not a directory, nestedDirectoryChildren will be empty array
  48086. const path = sysPath.join(directory, item);
  48087. const fullPath = sysPath.resolve(path);
  48088. isDirectory = isDirectory != null
  48089. ? isDirectory
  48090. : this._watched.has(path) || this._watched.has(fullPath);
  48091. // prevent duplicate handling in case of arriving here nearly simultaneously
  48092. // via multiple paths (such as _handleFile and _handleDir)
  48093. if (!this._throttle('remove', path, 100)) return;
  48094. // if the only watched file is removed, watch for its return
  48095. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  48096. this.add(directory, item, true);
  48097. }
  48098. // This will create a new entry in the watched object in either case
  48099. // so we got to do the directory check beforehand
  48100. const wp = this._getWatchedDir(path);
  48101. const nestedDirectoryChildren = wp.getChildren();
  48102. // Recursively remove children directories / files.
  48103. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  48104. // Check if item was on the watched list and remove it
  48105. const parent = this._getWatchedDir(directory);
  48106. const wasTracked = parent.has(item);
  48107. parent.remove(item);
  48108. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  48109. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  48110. // but never removed from the map in case the path was deleted.
  48111. // This leads to an incorrect state if the path was recreated:
  48112. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  48113. if (this._symlinkPaths.has(fullPath)) {
  48114. this._symlinkPaths.delete(fullPath);
  48115. }
  48116. // If we wait for this file to be fully written, cancel the wait.
  48117. let relPath = path;
  48118. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  48119. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  48120. const event = this._pendingWrites.get(relPath).cancelWait();
  48121. if (event === EV_ADD) return;
  48122. }
  48123. // The Entry will either be a directory that just got removed
  48124. // or a bogus entry to a file, in either case we have to remove it
  48125. this._watched.delete(path);
  48126. this._watched.delete(fullPath);
  48127. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  48128. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  48129. // Avoid conflicts if we later create another file with the same name
  48130. if (!this.options.useFsEvents) {
  48131. this._closePath(path);
  48132. }
  48133. }
  48134. /**
  48135. * Closes all watchers for a path
  48136. * @param {Path} path
  48137. */
  48138. _closePath(path) {
  48139. this._closeFile(path);
  48140. const dir = sysPath.dirname(path);
  48141. this._getWatchedDir(dir).remove(sysPath.basename(path));
  48142. }
  48143. /**
  48144. * Closes only file-specific watchers
  48145. * @param {Path} path
  48146. */
  48147. _closeFile(path) {
  48148. const closers = this._closers.get(path);
  48149. if (!closers) return;
  48150. closers.forEach(closer => closer());
  48151. this._closers.delete(path);
  48152. }
  48153. /**
  48154. *
  48155. * @param {Path} path
  48156. * @param {Function} closer
  48157. */
  48158. _addPathCloser(path, closer) {
  48159. if (!closer) return;
  48160. let list = this._closers.get(path);
  48161. if (!list) {
  48162. list = [];
  48163. this._closers.set(path, list);
  48164. }
  48165. list.push(closer);
  48166. }
  48167. _readdirp(root, opts) {
  48168. if (this.closed) return;
  48169. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  48170. let stream = readdirp(root, options);
  48171. this._streams.add(stream);
  48172. stream.once(STR_CLOSE, () => {
  48173. stream = undefined;
  48174. });
  48175. stream.once(STR_END, () => {
  48176. if (stream) {
  48177. this._streams.delete(stream);
  48178. stream = undefined;
  48179. }
  48180. });
  48181. return stream;
  48182. }
  48183. }
  48184. // Export FSWatcher class
  48185. chokidar.FSWatcher = FSWatcher;
  48186. /**
  48187. * Instantiates watcher with paths to be tracked.
  48188. * @param {String|Array<String>} paths file/directory paths and/or globs
  48189. * @param {Object=} options chokidar opts
  48190. * @returns an instance of FSWatcher for chaining.
  48191. */
  48192. const watch = (paths, options) => {
  48193. const watcher = new FSWatcher(options);
  48194. watcher.add(paths);
  48195. return watcher;
  48196. };
  48197. chokidar.watch = watch;
  48198. var shellQuote$1 = {};
  48199. shellQuote$1.quote = function (xs) {
  48200. return xs.map(function (s) {
  48201. if (s && typeof s === 'object') {
  48202. return s.op.replace(/(.)/g, '\\$1');
  48203. }
  48204. else if (/["\s]/.test(s) && !/'/.test(s)) {
  48205. return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
  48206. }
  48207. else if (/["'\s]/.test(s)) {
  48208. return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"';
  48209. }
  48210. else {
  48211. return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2');
  48212. }
  48213. }).join(' ');
  48214. };
  48215. // '<(' is process substitution operator and
  48216. // can be parsed the same as control operator
  48217. var CONTROL = '(?:' + [
  48218. '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]'
  48219. ].join('|') + ')';
  48220. var META = '|&;()<> \\t';
  48221. var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+';
  48222. var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
  48223. var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
  48224. var TOKEN = '';
  48225. for (var i = 0; i < 4; i++) {
  48226. TOKEN += (Math.pow(16,8)*Math.random()).toString(16);
  48227. }
  48228. shellQuote$1.parse = function (s, env, opts) {
  48229. var mapped = parse$5(s, env, opts);
  48230. if (typeof env !== 'function') return mapped;
  48231. return mapped.reduce(function (acc, s) {
  48232. if (typeof s === 'object') return acc.concat(s);
  48233. var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
  48234. if (xs.length === 1) return acc.concat(xs[0]);
  48235. return acc.concat(xs.filter(Boolean).map(function (x) {
  48236. if (RegExp('^' + TOKEN).test(x)) {
  48237. return JSON.parse(x.split(TOKEN)[1]);
  48238. }
  48239. else return x;
  48240. }));
  48241. }, []);
  48242. };
  48243. function parse$5 (s, env, opts) {
  48244. var chunker = new RegExp([
  48245. '(' + CONTROL + ')', // control chars
  48246. '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'
  48247. ].join('|'), 'g');
  48248. var match = s.match(chunker).filter(Boolean);
  48249. var commented = false;
  48250. if (!match) return [];
  48251. if (!env) env = {};
  48252. if (!opts) opts = {};
  48253. return match.map(function (s, j) {
  48254. if (commented) {
  48255. return;
  48256. }
  48257. if (RegExp('^' + CONTROL + '$').test(s)) {
  48258. return { op: s };
  48259. }
  48260. // Hand-written scanner/parser for Bash quoting rules:
  48261. //
  48262. // 1. inside single quotes, all characters are printed literally.
  48263. // 2. inside double quotes, all characters are printed literally
  48264. // except variables prefixed by '$' and backslashes followed by
  48265. // either a double quote or another backslash.
  48266. // 3. outside of any quotes, backslashes are treated as escape
  48267. // characters and not printed (unless they are themselves escaped)
  48268. // 4. quote context can switch mid-token if there is no whitespace
  48269. // between the two quote contexts (e.g. all'one'"token" parses as
  48270. // "allonetoken")
  48271. var SQ = "'";
  48272. var DQ = '"';
  48273. var DS = '$';
  48274. var BS = opts.escape || '\\';
  48275. var quote = false;
  48276. var esc = false;
  48277. var out = '';
  48278. var isGlob = false;
  48279. for (var i = 0, len = s.length; i < len; i++) {
  48280. var c = s.charAt(i);
  48281. isGlob = isGlob || (!quote && (c === '*' || c === '?'));
  48282. if (esc) {
  48283. out += c;
  48284. esc = false;
  48285. }
  48286. else if (quote) {
  48287. if (c === quote) {
  48288. quote = false;
  48289. }
  48290. else if (quote == SQ) {
  48291. out += c;
  48292. }
  48293. else { // Double quote
  48294. if (c === BS) {
  48295. i += 1;
  48296. c = s.charAt(i);
  48297. if (c === DQ || c === BS || c === DS) {
  48298. out += c;
  48299. } else {
  48300. out += BS + c;
  48301. }
  48302. }
  48303. else if (c === DS) {
  48304. out += parseEnvVar();
  48305. }
  48306. else {
  48307. out += c;
  48308. }
  48309. }
  48310. }
  48311. else if (c === DQ || c === SQ) {
  48312. quote = c;
  48313. }
  48314. else if (RegExp('^' + CONTROL + '$').test(c)) {
  48315. return { op: s };
  48316. }
  48317. else if (RegExp('^#$').test(c)) {
  48318. commented = true;
  48319. if (out.length){
  48320. return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
  48321. }
  48322. return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
  48323. }
  48324. else if (c === BS) {
  48325. esc = true;
  48326. }
  48327. else if (c === DS) {
  48328. out += parseEnvVar();
  48329. }
  48330. else out += c;
  48331. }
  48332. if (isGlob) return {op: 'glob', pattern: out};
  48333. return out;
  48334. function parseEnvVar() {
  48335. i += 1;
  48336. var varend, varname;
  48337. //debugger
  48338. if (s.charAt(i) === '{') {
  48339. i += 1;
  48340. if (s.charAt(i) === '}') {
  48341. throw new Error("Bad substitution: " + s.substr(i - 2, 3));
  48342. }
  48343. varend = s.indexOf('}', i);
  48344. if (varend < 0) {
  48345. throw new Error("Bad substitution: " + s.substr(i));
  48346. }
  48347. varname = s.substr(i, varend - i);
  48348. i = varend;
  48349. }
  48350. else if (/[*@#?$!_\-]/.test(s.charAt(i))) {
  48351. varname = s.charAt(i);
  48352. i += 1;
  48353. }
  48354. else {
  48355. varend = s.substr(i).match(/[^\w\d_]/);
  48356. if (!varend) {
  48357. varname = s.substr(i);
  48358. i = s.length;
  48359. } else {
  48360. varname = s.substr(i, varend.index);
  48361. i += varend.index - 1;
  48362. }
  48363. }
  48364. return getVar(null, '', varname);
  48365. }
  48366. })
  48367. // finalize parsed aruments
  48368. .reduce(function(prev, arg){
  48369. if (arg === undefined){
  48370. return prev;
  48371. }
  48372. return prev.concat(arg);
  48373. },[]);
  48374. function getVar (_, pre, key) {
  48375. var r = typeof env === 'function' ? env(key) : env[key];
  48376. if (r === undefined && key != '')
  48377. r = '';
  48378. else if (r === undefined)
  48379. r = '$';
  48380. if (typeof r === 'object') {
  48381. return pre + TOKEN + JSON.stringify(r) + TOKEN;
  48382. }
  48383. else return pre + r;
  48384. }
  48385. }
  48386. var osx = {
  48387. '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
  48388. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
  48389. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
  48390. '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
  48391. '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
  48392. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  48393. '/Applications/Sublime Text.app/Contents/MacOS/sublime_text':
  48394. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  48395. '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
  48396. '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
  48397. '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':
  48398. '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',
  48399. '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
  48400. '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':
  48401. 'code-insiders',
  48402. '/Applications/VSCodium.app/Contents/MacOS/Electron': 'codium',
  48403. '/Applications/AppCode.app/Contents/MacOS/appcode':
  48404. '/Applications/AppCode.app/Contents/MacOS/appcode',
  48405. '/Applications/CLion.app/Contents/MacOS/clion':
  48406. '/Applications/CLion.app/Contents/MacOS/clion',
  48407. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':
  48408. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',
  48409. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':
  48410. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',
  48411. '/Applications/PyCharm.app/Contents/MacOS/pycharm':
  48412. '/Applications/PyCharm.app/Contents/MacOS/pycharm',
  48413. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':
  48414. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',
  48415. '/Applications/RubyMine.app/Contents/MacOS/rubymine':
  48416. '/Applications/RubyMine.app/Contents/MacOS/rubymine',
  48417. '/Applications/WebStorm.app/Contents/MacOS/webstorm':
  48418. '/Applications/WebStorm.app/Contents/MacOS/webstorm',
  48419. '/Applications/MacVim.app/Contents/MacOS/MacVim': 'mvim',
  48420. '/Applications/GoLand.app/Contents/MacOS/goland':
  48421. '/Applications/GoLand.app/Contents/MacOS/goland',
  48422. '/Applications/Rider.app/Contents/MacOS/rider':
  48423. '/Applications/Rider.app/Contents/MacOS/rider'
  48424. };
  48425. var linux = {
  48426. atom: 'atom',
  48427. Brackets: 'brackets',
  48428. code: 'code',
  48429. 'code-insiders': 'code-insiders',
  48430. codium: 'codium',
  48431. vscodium: 'vscodium',
  48432. emacs: 'emacs',
  48433. gvim: 'gvim',
  48434. 'idea.sh': 'idea',
  48435. 'phpstorm.sh': 'phpstorm',
  48436. 'pycharm.sh': 'pycharm',
  48437. 'rubymine.sh': 'rubymine',
  48438. sublime_text: 'subl',
  48439. vim: 'vim',
  48440. 'webstorm.sh': 'webstorm',
  48441. 'goland.sh': 'goland',
  48442. 'rider.sh': 'rider'
  48443. };
  48444. var windows$1 = [
  48445. 'Brackets.exe',
  48446. 'Code.exe',
  48447. 'Code - Insiders.exe',
  48448. 'VSCodium.exe',
  48449. 'atom.exe',
  48450. 'sublime_text.exe',
  48451. 'notepad++.exe',
  48452. 'clion.exe',
  48453. 'clion64.exe',
  48454. 'idea.exe',
  48455. 'idea64.exe',
  48456. 'phpstorm.exe',
  48457. 'phpstorm64.exe',
  48458. 'pycharm.exe',
  48459. 'pycharm64.exe',
  48460. 'rubymine.exe',
  48461. 'rubymine64.exe',
  48462. 'webstorm.exe',
  48463. 'webstorm64.exe',
  48464. 'goland.exe',
  48465. 'goland64.exe',
  48466. 'rider.exe',
  48467. 'rider64.exe'
  48468. ];
  48469. const path$7 = require$$0$4;
  48470. const shellQuote = shellQuote$1;
  48471. const childProcess$2 = require$$2$1;
  48472. // Map from full process name to binary that starts the process
  48473. // We can't just re-use full process name, because it will spawn a new instance
  48474. // of the app every time
  48475. const COMMON_EDITORS_OSX = osx;
  48476. const COMMON_EDITORS_LINUX = linux;
  48477. const COMMON_EDITORS_WIN = windows$1;
  48478. var guess = function guessEditor (specifiedEditor) {
  48479. if (specifiedEditor) {
  48480. return shellQuote.parse(specifiedEditor)
  48481. }
  48482. if (process.env.LAUNCH_EDITOR) {
  48483. return [process.env.LAUNCH_EDITOR]
  48484. }
  48485. if (process.versions.webcontainer) {
  48486. return [process.env.EDITOR || 'code']
  48487. }
  48488. // We can find out which editor is currently running by:
  48489. // `ps x` on macOS and Linux
  48490. // `Get-Process` on Windows
  48491. try {
  48492. if (process.platform === 'darwin') {
  48493. const output = childProcess$2
  48494. .execSync('ps x -o comm=', {
  48495. stdio: ['pipe', 'pipe', 'ignore']
  48496. })
  48497. .toString();
  48498. const processNames = Object.keys(COMMON_EDITORS_OSX);
  48499. const processList = output.split('\n');
  48500. for (let i = 0; i < processNames.length; i++) {
  48501. const processName = processNames[i];
  48502. // Find editor by exact match.
  48503. if (output.indexOf(processName) !== -1) {
  48504. return [COMMON_EDITORS_OSX[processName]]
  48505. }
  48506. const processNameWithoutApplications = processName.replace('/Applications', '');
  48507. // Find editor installation not in /Applications.
  48508. if (output.indexOf(processNameWithoutApplications) !== -1) {
  48509. // Use the CLI command if one is specified
  48510. if (processName !== COMMON_EDITORS_OSX[processName]) {
  48511. return [COMMON_EDITORS_OSX[processName]]
  48512. }
  48513. // Use a partial match to find the running process path. If one is found, use the
  48514. // existing path since it can be running from anywhere.
  48515. const runningProcess = processList.find((procName) => procName.endsWith(processNameWithoutApplications));
  48516. if (runningProcess !== undefined) {
  48517. return [runningProcess]
  48518. }
  48519. }
  48520. }
  48521. } else if (process.platform === 'win32') {
  48522. const output = childProcess$2
  48523. .execSync(
  48524. 'powershell -NoProfile -Command "Get-CimInstance -Query \\"select executablepath from win32_process where executablepath is not null\\" | % { $_.ExecutablePath }"',
  48525. {
  48526. stdio: ['pipe', 'pipe', 'ignore']
  48527. }
  48528. )
  48529. .toString();
  48530. const runningProcesses = output.split('\r\n');
  48531. for (let i = 0; i < runningProcesses.length; i++) {
  48532. const fullProcessPath = runningProcesses[i].trim();
  48533. const shortProcessName = path$7.basename(fullProcessPath);
  48534. if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
  48535. return [fullProcessPath]
  48536. }
  48537. }
  48538. } else if (process.platform === 'linux') {
  48539. // --no-heading No header line
  48540. // x List all processes owned by you
  48541. // -o comm Need only names column
  48542. const output = childProcess$2
  48543. .execSync('ps x --no-heading -o comm --sort=comm', {
  48544. stdio: ['pipe', 'pipe', 'ignore']
  48545. })
  48546. .toString();
  48547. const processNames = Object.keys(COMMON_EDITORS_LINUX);
  48548. for (let i = 0; i < processNames.length; i++) {
  48549. const processName = processNames[i];
  48550. if (output.indexOf(processName) !== -1) {
  48551. return [COMMON_EDITORS_LINUX[processName]]
  48552. }
  48553. }
  48554. }
  48555. } catch (error) {
  48556. // Ignore...
  48557. }
  48558. // Last resort, use old skool env vars
  48559. if (process.env.VISUAL) {
  48560. return [process.env.VISUAL]
  48561. } else if (process.env.EDITOR) {
  48562. return [process.env.EDITOR]
  48563. }
  48564. return [null]
  48565. };
  48566. const path$6 = require$$0$4;
  48567. // normalize file/line numbers into command line args for specific editors
  48568. var getArgs = function getArgumentsForPosition (
  48569. editor,
  48570. fileName,
  48571. lineNumber,
  48572. columnNumber = 1
  48573. ) {
  48574. const editorBasename = path$6.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');
  48575. switch (editorBasename) {
  48576. case 'atom':
  48577. case 'Atom':
  48578. case 'Atom Beta':
  48579. case 'subl':
  48580. case 'sublime':
  48581. case 'sublime_text':
  48582. case 'wstorm':
  48583. case 'charm':
  48584. return [`${fileName}:${lineNumber}:${columnNumber}`]
  48585. case 'notepad++':
  48586. return ['-n' + lineNumber, '-c' + columnNumber, fileName]
  48587. case 'vim':
  48588. case 'mvim':
  48589. return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName]
  48590. case 'joe':
  48591. case 'gvim':
  48592. return ['+' + `${lineNumber}`, fileName]
  48593. case 'emacs':
  48594. case 'emacsclient':
  48595. return [`+${lineNumber}:${columnNumber}`, fileName]
  48596. case 'rmate':
  48597. case 'mate':
  48598. case 'mine':
  48599. return ['--line', lineNumber, fileName]
  48600. case 'code':
  48601. case 'Code':
  48602. case 'code-insiders':
  48603. case 'Code - Insiders':
  48604. case 'codium':
  48605. case 'vscodium':
  48606. case 'VSCodium':
  48607. return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`]
  48608. case 'appcode':
  48609. case 'clion':
  48610. case 'clion64':
  48611. case 'idea':
  48612. case 'idea64':
  48613. case 'phpstorm':
  48614. case 'phpstorm64':
  48615. case 'pycharm':
  48616. case 'pycharm64':
  48617. case 'rubymine':
  48618. case 'rubymine64':
  48619. case 'webstorm':
  48620. case 'webstorm64':
  48621. case 'goland':
  48622. case 'goland64':
  48623. case 'rider':
  48624. case 'rider64':
  48625. return ['--line', lineNumber, '--column', columnNumber, fileName]
  48626. }
  48627. if (process.env.LAUNCH_EDITOR) {
  48628. return [fileName, lineNumber, columnNumber]
  48629. }
  48630. // For all others, drop the lineNumber until we have
  48631. // a mapping above, since providing the lineNumber incorrectly
  48632. // can result in errors or confusing behavior.
  48633. return [fileName]
  48634. };
  48635. /**
  48636. * Copyright (c) 2015-present, Facebook, Inc.
  48637. *
  48638. * This source code is licensed under the MIT license found in the
  48639. * LICENSE file at
  48640. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  48641. *
  48642. * Modified by Yuxi Evan You
  48643. */
  48644. const fs$4 = require$$0__default;
  48645. const os$1 = require$$2;
  48646. const path$5 = require$$0$4;
  48647. const colors = picocolorsExports;
  48648. const childProcess$1 = require$$2$1;
  48649. const guessEditor = guess;
  48650. const getArgumentsForPosition = getArgs;
  48651. function wrapErrorCallback (cb) {
  48652. return (fileName, errorMessage) => {
  48653. console.log();
  48654. console.log(
  48655. colors.red('Could not open ' + path$5.basename(fileName) + ' in the editor.')
  48656. );
  48657. if (errorMessage) {
  48658. if (errorMessage[errorMessage.length - 1] !== '.') {
  48659. errorMessage += '.';
  48660. }
  48661. console.log(
  48662. colors.red('The editor process exited with an error: ' + errorMessage)
  48663. );
  48664. }
  48665. console.log();
  48666. if (cb) cb(fileName, errorMessage);
  48667. }
  48668. }
  48669. function isTerminalEditor (editor) {
  48670. switch (editor) {
  48671. case 'vim':
  48672. case 'emacs':
  48673. case 'nano':
  48674. return true
  48675. }
  48676. return false
  48677. }
  48678. const positionRE = /:(\d+)(:(\d+))?$/;
  48679. function parseFile (file) {
  48680. const fileName = file.replace(positionRE, '');
  48681. const match = file.match(positionRE);
  48682. const lineNumber = match && match[1];
  48683. const columnNumber = match && match[3];
  48684. return {
  48685. fileName,
  48686. lineNumber,
  48687. columnNumber
  48688. }
  48689. }
  48690. let _childProcess = null;
  48691. function launchEditor (file, specifiedEditor, onErrorCallback) {
  48692. const parsed = parseFile(file);
  48693. let { fileName } = parsed;
  48694. const { lineNumber, columnNumber } = parsed;
  48695. if (!fs$4.existsSync(fileName)) {
  48696. return
  48697. }
  48698. if (typeof specifiedEditor === 'function') {
  48699. onErrorCallback = specifiedEditor;
  48700. specifiedEditor = undefined;
  48701. }
  48702. onErrorCallback = wrapErrorCallback(onErrorCallback);
  48703. const [editor, ...args] = guessEditor(specifiedEditor);
  48704. if (!editor) {
  48705. onErrorCallback(fileName, null);
  48706. return
  48707. }
  48708. if (
  48709. process.platform === 'linux' &&
  48710. fileName.startsWith('/mnt/') &&
  48711. /Microsoft/i.test(os$1.release())
  48712. ) {
  48713. // Assume WSL / "Bash on Ubuntu on Windows" is being used, and
  48714. // that the file exists on the Windows file system.
  48715. // `os.release()` is "4.4.0-43-Microsoft" in the current release
  48716. // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
  48717. // When a Windows editor is specified, interop functionality can
  48718. // handle the path translation, but only if a relative path is used.
  48719. fileName = path$5.relative('', fileName);
  48720. }
  48721. if (lineNumber) {
  48722. const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
  48723. args.push.apply(args, extraArgs);
  48724. } else {
  48725. args.push(fileName);
  48726. }
  48727. if (_childProcess && isTerminalEditor(editor)) {
  48728. // There's an existing editor process already and it's attached
  48729. // to the terminal, so go kill it. Otherwise two separate editor
  48730. // instances attach to the stdin/stdout which gets confusing.
  48731. _childProcess.kill('SIGKILL');
  48732. }
  48733. if (process.platform === 'win32') {
  48734. // On Windows, launch the editor in a shell because spawn can only
  48735. // launch .exe files.
  48736. _childProcess = childProcess$1.spawn(
  48737. 'cmd.exe',
  48738. ['/C', editor].concat(args),
  48739. { stdio: 'inherit' }
  48740. );
  48741. } else {
  48742. _childProcess = childProcess$1.spawn(editor, args, { stdio: 'inherit' });
  48743. }
  48744. _childProcess.on('exit', function (errorCode) {
  48745. _childProcess = null;
  48746. if (errorCode) {
  48747. onErrorCallback(fileName, '(code ' + errorCode + ')');
  48748. }
  48749. });
  48750. _childProcess.on('error', function (error) {
  48751. onErrorCallback(fileName, error.message);
  48752. });
  48753. }
  48754. var launchEditor_1 = launchEditor;
  48755. const url$2 = require$$0$9;
  48756. const path$4 = require$$0$4;
  48757. const launch = launchEditor_1;
  48758. var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => {
  48759. if (typeof specifiedEditor === 'function') {
  48760. onErrorCallback = specifiedEditor;
  48761. specifiedEditor = undefined;
  48762. }
  48763. if (typeof srcRoot === 'function') {
  48764. onErrorCallback = srcRoot;
  48765. srcRoot = undefined;
  48766. }
  48767. srcRoot = srcRoot || process.cwd();
  48768. return function launchEditorMiddleware (req, res, next) {
  48769. const { file } = url$2.parse(req.url, true).query || {};
  48770. if (!file) {
  48771. res.statusCode = 500;
  48772. res.end(`launch-editor-middleware: required query param "file" is missing.`);
  48773. } else {
  48774. launch(path$4.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
  48775. res.end();
  48776. }
  48777. }
  48778. };
  48779. var launchEditorMiddleware$1 = /*@__PURE__*/getDefaultExportFromCjs(launchEditorMiddleware);
  48780. async function resolveHttpServer({ proxy }, app, httpsOptions) {
  48781. if (!httpsOptions) {
  48782. const { createServer } = await import('node:http');
  48783. return createServer(app);
  48784. }
  48785. // #484 fallback to http1 when proxy is needed.
  48786. if (proxy) {
  48787. const { createServer } = await import('node:https');
  48788. return createServer(httpsOptions, app);
  48789. }
  48790. else {
  48791. const { createSecureServer } = await import('node:http2');
  48792. return createSecureServer({
  48793. // Manually increase the session memory to prevent 502 ENHANCE_YOUR_CALM
  48794. // errors on large numbers of requests
  48795. maxSessionMemory: 1000,
  48796. ...httpsOptions,
  48797. allowHTTP1: true,
  48798. },
  48799. // @ts-expect-error TODO: is this correct?
  48800. app);
  48801. }
  48802. }
  48803. async function resolveHttpsConfig(https) {
  48804. if (!https)
  48805. return undefined;
  48806. if (!isObject$2(https))
  48807. return {};
  48808. const [ca, cert, key, pfx] = await Promise.all([
  48809. readFileIfExists(https.ca),
  48810. readFileIfExists(https.cert),
  48811. readFileIfExists(https.key),
  48812. readFileIfExists(https.pfx),
  48813. ]);
  48814. return { ...https, ca, cert, key, pfx };
  48815. }
  48816. async function readFileIfExists(value) {
  48817. if (typeof value === 'string') {
  48818. return fsp.readFile(path$o.resolve(value)).catch(() => value);
  48819. }
  48820. return value;
  48821. }
  48822. async function httpServerStart(httpServer, serverOptions) {
  48823. let { port, strictPort, host, logger } = serverOptions;
  48824. return new Promise((resolve, reject) => {
  48825. const onError = (e) => {
  48826. if (e.code === 'EADDRINUSE') {
  48827. if (strictPort) {
  48828. httpServer.removeListener('error', onError);
  48829. reject(new Error(`Port ${port} is already in use`));
  48830. }
  48831. else {
  48832. logger.info(`Port ${port} is in use, trying another one...`);
  48833. httpServer.listen(++port, host);
  48834. }
  48835. }
  48836. else {
  48837. httpServer.removeListener('error', onError);
  48838. reject(e);
  48839. }
  48840. };
  48841. httpServer.on('error', onError);
  48842. httpServer.listen(port, host, () => {
  48843. httpServer.removeListener('error', onError);
  48844. resolve(port);
  48845. });
  48846. });
  48847. }
  48848. function setClientErrorHandler(server, logger) {
  48849. server.on('clientError', (err, socket) => {
  48850. let msg = '400 Bad Request';
  48851. if (err.code === 'HPE_HEADER_OVERFLOW') {
  48852. msg = '431 Request Header Fields Too Large';
  48853. logger.warn(colors$1.yellow('Server responded with status code 431. ' +
  48854. 'See https://vitejs.dev/guide/troubleshooting.html#_431-request-header-fields-too-large.'));
  48855. }
  48856. if (err.code === 'ECONNRESET' || !socket.writable) {
  48857. return;
  48858. }
  48859. socket.end(`HTTP/1.1 ${msg}\r\n\r\n`);
  48860. });
  48861. }
  48862. const ERR_LOAD_URL = 'ERR_LOAD_URL';
  48863. const ERR_LOAD_PUBLIC_URL = 'ERR_LOAD_PUBLIC_URL';
  48864. const debugLoad = createDebugger('vite:load');
  48865. const debugTransform = createDebugger('vite:transform');
  48866. const debugCache$1 = createDebugger('vite:cache');
  48867. function transformRequest(url, server, options = {}) {
  48868. const cacheKey = (options.ssr ? 'ssr:' : options.html ? 'html:' : '') + url;
  48869. // This module may get invalidated while we are processing it. For example
  48870. // when a full page reload is needed after the re-processing of pre-bundled
  48871. // dependencies when a missing dep is discovered. We save the current time
  48872. // to compare it to the last invalidation performed to know if we should
  48873. // cache the result of the transformation or we should discard it as stale.
  48874. //
  48875. // A module can be invalidated due to:
  48876. // 1. A full reload because of pre-bundling newly discovered deps
  48877. // 2. A full reload after a config change
  48878. // 3. The file that generated the module changed
  48879. // 4. Invalidation for a virtual module
  48880. //
  48881. // For 1 and 2, a new request for this module will be issued after
  48882. // the invalidation as part of the browser reloading the page. For 3 and 4
  48883. // there may not be a new request right away because of HMR handling.
  48884. // In all cases, the next time this module is requested, it should be
  48885. // re-processed.
  48886. //
  48887. // We save the timestamp when we start processing and compare it with the
  48888. // last time this module is invalidated
  48889. const timestamp = Date.now();
  48890. const pending = server._pendingRequests.get(cacheKey);
  48891. if (pending) {
  48892. return server.moduleGraph
  48893. .getModuleByUrl(removeTimestampQuery(url), options.ssr)
  48894. .then((module) => {
  48895. if (!module || pending.timestamp > module.lastInvalidationTimestamp) {
  48896. // The pending request is still valid, we can safely reuse its result
  48897. return pending.request;
  48898. }
  48899. else {
  48900. // Request 1 for module A (pending.timestamp)
  48901. // Invalidate module A (module.lastInvalidationTimestamp)
  48902. // Request 2 for module A (timestamp)
  48903. // First request has been invalidated, abort it to clear the cache,
  48904. // then perform a new doTransform.
  48905. pending.abort();
  48906. return transformRequest(url, server, options);
  48907. }
  48908. });
  48909. }
  48910. const request = doTransform(url, server, options, timestamp);
  48911. // Avoid clearing the cache of future requests if aborted
  48912. let cleared = false;
  48913. const clearCache = () => {
  48914. if (!cleared) {
  48915. server._pendingRequests.delete(cacheKey);
  48916. cleared = true;
  48917. }
  48918. };
  48919. // Cache the request and clear it once processing is done
  48920. server._pendingRequests.set(cacheKey, {
  48921. request,
  48922. timestamp,
  48923. abort: clearCache,
  48924. });
  48925. request.then(clearCache, clearCache);
  48926. return request;
  48927. }
  48928. async function doTransform(url, server, options, timestamp) {
  48929. url = removeTimestampQuery(url);
  48930. const { config, pluginContainer } = server;
  48931. const prettyUrl = debugCache$1 ? prettifyUrl(url, config.root) : '';
  48932. const ssr = !!options.ssr;
  48933. const module = await server.moduleGraph.getModuleByUrl(url, ssr);
  48934. // check if we have a fresh cache
  48935. const cached = module && (ssr ? module.ssrTransformResult : module.transformResult);
  48936. if (cached) {
  48937. // TODO: check if the module is "partially invalidated" - i.e. an import
  48938. // down the chain has been fully invalidated, but this current module's
  48939. // content has not changed.
  48940. // in this case, we can reuse its previous cached result and only update
  48941. // its import timestamps.
  48942. debugCache$1?.(`[memory] ${prettyUrl}`);
  48943. return cached;
  48944. }
  48945. // resolve
  48946. const id = module?.id ??
  48947. (await pluginContainer.resolveId(url, undefined, { ssr }))?.id ??
  48948. url;
  48949. const result = loadAndTransform(id, url, server, options, timestamp);
  48950. getDepsOptimizer(config, ssr)?.delayDepsOptimizerUntil(id, () => result);
  48951. return result;
  48952. }
  48953. async function loadAndTransform(id, url, server, options, timestamp) {
  48954. const { config, pluginContainer, moduleGraph, watcher } = server;
  48955. const { root, logger } = config;
  48956. const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : '';
  48957. const ssr = !!options.ssr;
  48958. const file = cleanUrl(id);
  48959. let code = null;
  48960. let map = null;
  48961. // load
  48962. const loadStart = debugLoad ? performance$1.now() : 0;
  48963. const loadResult = await pluginContainer.load(id, { ssr });
  48964. if (loadResult == null) {
  48965. // if this is an html request and there is no load result, skip ahead to
  48966. // SPA fallback.
  48967. if (options.html && !id.endsWith('.html')) {
  48968. return null;
  48969. }
  48970. // try fallback loading it from fs as string
  48971. // if the file is a binary, there should be a plugin that already loaded it
  48972. // as string
  48973. // only try the fallback if access is allowed, skip for out of root url
  48974. // like /service-worker.js or /api/users
  48975. if (options.ssr || isFileServingAllowed(file, server)) {
  48976. try {
  48977. code = await promises$2.readFile(file, 'utf-8');
  48978. debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
  48979. }
  48980. catch (e) {
  48981. if (e.code !== 'ENOENT') {
  48982. throw e;
  48983. }
  48984. }
  48985. }
  48986. if (code) {
  48987. try {
  48988. map = (convertSourceMap.fromSource(code) ||
  48989. (await convertSourceMap.fromMapFileSource(code, createConvertSourceMapReadMap(file))))?.toObject();
  48990. code = code.replace(convertSourceMap.mapFileCommentRegex, blankReplacer);
  48991. }
  48992. catch (e) {
  48993. logger.warn(`Failed to load source map for ${url}.`, {
  48994. timestamp: true,
  48995. });
  48996. }
  48997. }
  48998. }
  48999. else {
  49000. debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
  49001. if (isObject$2(loadResult)) {
  49002. code = loadResult.code;
  49003. map = loadResult.map;
  49004. }
  49005. else {
  49006. code = loadResult;
  49007. }
  49008. }
  49009. if (code == null) {
  49010. const isPublicFile = checkPublicFile(url, config);
  49011. const msg = isPublicFile
  49012. ? `This file is in /public and will be copied as-is during build without ` +
  49013. `going through the plugin transforms, and therefore should not be ` +
  49014. `imported from source code. It can only be referenced via HTML tags.`
  49015. : `Does the file exist?`;
  49016. const importerMod = server.moduleGraph.idToModuleMap
  49017. .get(id)
  49018. ?.importers.values()
  49019. .next().value;
  49020. const importer = importerMod?.file || importerMod?.url;
  49021. const err = new Error(`Failed to load url ${url} (resolved id: ${id})${importer ? ` in ${importer}` : ''}. ${msg}`);
  49022. err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
  49023. throw err;
  49024. }
  49025. // ensure module in graph after successful load
  49026. const mod = await moduleGraph.ensureEntryFromUrl(url, ssr);
  49027. ensureWatchedFile(watcher, mod.file, root);
  49028. // transform
  49029. const transformStart = debugTransform ? performance$1.now() : 0;
  49030. const transformResult = await pluginContainer.transform(code, id, {
  49031. inMap: map,
  49032. ssr,
  49033. });
  49034. const originalCode = code;
  49035. if (transformResult == null ||
  49036. (isObject$2(transformResult) && transformResult.code == null)) {
  49037. // no transform applied, keep code as-is
  49038. debugTransform?.(timeFrom(transformStart) + colors$1.dim(` [skipped] ${prettyUrl}`));
  49039. }
  49040. else {
  49041. debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`);
  49042. code = transformResult.code;
  49043. map = transformResult.map;
  49044. }
  49045. if (map && mod.file) {
  49046. map = (typeof map === 'string' ? JSON.parse(map) : map);
  49047. if (map.mappings && !map.sourcesContent) {
  49048. await injectSourcesContent(map, mod.file, logger);
  49049. }
  49050. const sourcemapPath = `${mod.file}.map`;
  49051. applySourcemapIgnoreList(map, sourcemapPath, config.server.sourcemapIgnoreList, logger);
  49052. if (path$o.isAbsolute(mod.file)) {
  49053. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  49054. const sourcePath = map.sources[sourcesIndex];
  49055. if (sourcePath) {
  49056. // Rewrite sources to relative paths to give debuggers the chance
  49057. // to resolve and display them in a meaningful way (rather than
  49058. // with absolute paths).
  49059. if (path$o.isAbsolute(sourcePath)) {
  49060. map.sources[sourcesIndex] = path$o.relative(path$o.dirname(mod.file), sourcePath);
  49061. }
  49062. }
  49063. }
  49064. }
  49065. }
  49066. const result = ssr && !server.config.experimental.skipSsrTransform
  49067. ? await server.ssrTransform(code, map, url, originalCode)
  49068. : {
  49069. code,
  49070. map,
  49071. etag: getEtag(code, { weak: true }),
  49072. };
  49073. // Only cache the result if the module wasn't invalidated while it was
  49074. // being processed, so it is re-processed next time if it is stale
  49075. if (timestamp > mod.lastInvalidationTimestamp) {
  49076. if (ssr)
  49077. mod.ssrTransformResult = result;
  49078. else
  49079. mod.transformResult = result;
  49080. }
  49081. return result;
  49082. }
  49083. function createConvertSourceMapReadMap(originalFileName) {
  49084. return (filename) => {
  49085. return promises$2.readFile(path$o.resolve(path$o.dirname(originalFileName), filename), 'utf-8');
  49086. };
  49087. }
  49088. /**
  49089. * @typedef { import('estree').Node} Node
  49090. * @typedef {{
  49091. * skip: () => void;
  49092. * remove: () => void;
  49093. * replace: (node: Node) => void;
  49094. * }} WalkerContext
  49095. */
  49096. class WalkerBase {
  49097. constructor() {
  49098. /** @type {boolean} */
  49099. this.should_skip = false;
  49100. /** @type {boolean} */
  49101. this.should_remove = false;
  49102. /** @type {Node | null} */
  49103. this.replacement = null;
  49104. /** @type {WalkerContext} */
  49105. this.context = {
  49106. skip: () => (this.should_skip = true),
  49107. remove: () => (this.should_remove = true),
  49108. replace: (node) => (this.replacement = node)
  49109. };
  49110. }
  49111. /**
  49112. * @template {Node} Parent
  49113. * @param {Parent | null | undefined} parent
  49114. * @param {keyof Parent | null | undefined} prop
  49115. * @param {number | null | undefined} index
  49116. * @param {Node} node
  49117. */
  49118. replace(parent, prop, index, node) {
  49119. if (parent && prop) {
  49120. if (index != null) {
  49121. /** @type {Array<Node>} */ (parent[prop])[index] = node;
  49122. } else {
  49123. /** @type {Node} */ (parent[prop]) = node;
  49124. }
  49125. }
  49126. }
  49127. /**
  49128. * @template {Node} Parent
  49129. * @param {Parent | null | undefined} parent
  49130. * @param {keyof Parent | null | undefined} prop
  49131. * @param {number | null | undefined} index
  49132. */
  49133. remove(parent, prop, index) {
  49134. if (parent && prop) {
  49135. if (index !== null && index !== undefined) {
  49136. /** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
  49137. } else {
  49138. delete parent[prop];
  49139. }
  49140. }
  49141. }
  49142. }
  49143. /**
  49144. * @typedef { import('estree').Node} Node
  49145. * @typedef { import('./walker.js').WalkerContext} WalkerContext
  49146. * @typedef {(
  49147. * this: WalkerContext,
  49148. * node: Node,
  49149. * parent: Node | null,
  49150. * key: string | number | symbol | null | undefined,
  49151. * index: number | null | undefined
  49152. * ) => void} SyncHandler
  49153. */
  49154. class SyncWalker extends WalkerBase {
  49155. /**
  49156. *
  49157. * @param {SyncHandler} [enter]
  49158. * @param {SyncHandler} [leave]
  49159. */
  49160. constructor(enter, leave) {
  49161. super();
  49162. /** @type {boolean} */
  49163. this.should_skip = false;
  49164. /** @type {boolean} */
  49165. this.should_remove = false;
  49166. /** @type {Node | null} */
  49167. this.replacement = null;
  49168. /** @type {WalkerContext} */
  49169. this.context = {
  49170. skip: () => (this.should_skip = true),
  49171. remove: () => (this.should_remove = true),
  49172. replace: (node) => (this.replacement = node)
  49173. };
  49174. /** @type {SyncHandler | undefined} */
  49175. this.enter = enter;
  49176. /** @type {SyncHandler | undefined} */
  49177. this.leave = leave;
  49178. }
  49179. /**
  49180. * @template {Node} Parent
  49181. * @param {Node} node
  49182. * @param {Parent | null} parent
  49183. * @param {keyof Parent} [prop]
  49184. * @param {number | null} [index]
  49185. * @returns {Node | null}
  49186. */
  49187. visit(node, parent, prop, index) {
  49188. if (node) {
  49189. if (this.enter) {
  49190. const _should_skip = this.should_skip;
  49191. const _should_remove = this.should_remove;
  49192. const _replacement = this.replacement;
  49193. this.should_skip = false;
  49194. this.should_remove = false;
  49195. this.replacement = null;
  49196. this.enter.call(this.context, node, parent, prop, index);
  49197. if (this.replacement) {
  49198. node = this.replacement;
  49199. this.replace(parent, prop, index, node);
  49200. }
  49201. if (this.should_remove) {
  49202. this.remove(parent, prop, index);
  49203. }
  49204. const skipped = this.should_skip;
  49205. const removed = this.should_remove;
  49206. this.should_skip = _should_skip;
  49207. this.should_remove = _should_remove;
  49208. this.replacement = _replacement;
  49209. if (skipped) return node;
  49210. if (removed) return null;
  49211. }
  49212. /** @type {keyof Node} */
  49213. let key;
  49214. for (key in node) {
  49215. /** @type {unknown} */
  49216. const value = node[key];
  49217. if (value && typeof value === 'object') {
  49218. if (Array.isArray(value)) {
  49219. const nodes = /** @type {Array<unknown>} */ (value);
  49220. for (let i = 0; i < nodes.length; i += 1) {
  49221. const item = nodes[i];
  49222. if (isNode(item)) {
  49223. if (!this.visit(item, node, key, i)) {
  49224. // removed
  49225. i--;
  49226. }
  49227. }
  49228. }
  49229. } else if (isNode(value)) {
  49230. this.visit(value, node, key, null);
  49231. }
  49232. }
  49233. }
  49234. if (this.leave) {
  49235. const _replacement = this.replacement;
  49236. const _should_remove = this.should_remove;
  49237. this.replacement = null;
  49238. this.should_remove = false;
  49239. this.leave.call(this.context, node, parent, prop, index);
  49240. if (this.replacement) {
  49241. node = this.replacement;
  49242. this.replace(parent, prop, index, node);
  49243. }
  49244. if (this.should_remove) {
  49245. this.remove(parent, prop, index);
  49246. }
  49247. const removed = this.should_remove;
  49248. this.replacement = _replacement;
  49249. this.should_remove = _should_remove;
  49250. if (removed) return null;
  49251. }
  49252. }
  49253. return node;
  49254. }
  49255. }
  49256. /**
  49257. * Ducktype a node.
  49258. *
  49259. * @param {unknown} value
  49260. * @returns {value is Node}
  49261. */
  49262. function isNode(value) {
  49263. return (
  49264. value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
  49265. );
  49266. }
  49267. /**
  49268. * @typedef {import('estree').Node} Node
  49269. * @typedef {import('./sync.js').SyncHandler} SyncHandler
  49270. * @typedef {import('./async.js').AsyncHandler} AsyncHandler
  49271. */
  49272. /**
  49273. * @param {Node} ast
  49274. * @param {{
  49275. * enter?: SyncHandler
  49276. * leave?: SyncHandler
  49277. * }} walker
  49278. * @returns {Node | null}
  49279. */
  49280. function walk$1(ast, { enter, leave }) {
  49281. const instance = new SyncWalker(enter, leave);
  49282. return instance.visit(ast, null);
  49283. }
  49284. /**
  49285. * @param {import('estree').Node} param
  49286. * @returns {string[]}
  49287. */
  49288. function extract_names(param) {
  49289. return extract_identifiers(param).map(node => node.name);
  49290. }
  49291. /**
  49292. * @param {import('estree').Node} param
  49293. * @param {import('estree').Identifier[]} nodes
  49294. * @returns {import('estree').Identifier[]}
  49295. */
  49296. function extract_identifiers(param, nodes = []) {
  49297. switch (param.type) {
  49298. case 'Identifier':
  49299. nodes.push(param);
  49300. break;
  49301. case 'MemberExpression':
  49302. let object = param;
  49303. while (object.type === 'MemberExpression') {
  49304. object = /** @type {any} */ (object.object);
  49305. }
  49306. nodes.push(/** @type {any} */ (object));
  49307. break;
  49308. case 'ObjectPattern':
  49309. /** @param {import('estree').Property | import('estree').RestElement} prop */
  49310. const handle_prop = (prop) => {
  49311. if (prop.type === 'RestElement') {
  49312. extract_identifiers(prop.argument, nodes);
  49313. } else {
  49314. extract_identifiers(prop.value, nodes);
  49315. }
  49316. };
  49317. param.properties.forEach(handle_prop);
  49318. break;
  49319. case 'ArrayPattern':
  49320. /** @param {import('estree').Node} element */
  49321. const handle_element = (element) => {
  49322. if (element) extract_identifiers(element, nodes);
  49323. };
  49324. param.elements.forEach((element) => {
  49325. if (element) {
  49326. handle_element(element);
  49327. }
  49328. });
  49329. break;
  49330. case 'RestElement':
  49331. extract_identifiers(param.argument, nodes);
  49332. break;
  49333. case 'AssignmentPattern':
  49334. extract_identifiers(param.left, nodes);
  49335. break;
  49336. }
  49337. return nodes;
  49338. }
  49339. const ssrModuleExportsKey = `__vite_ssr_exports__`;
  49340. const ssrImportKey = `__vite_ssr_import__`;
  49341. const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
  49342. const ssrExportAllKey = `__vite_ssr_exportAll__`;
  49343. const ssrImportMetaKey = `__vite_ssr_import_meta__`;
  49344. const hashbangRE = /^#!.*\n/;
  49345. async function ssrTransform(code, inMap, url, originalCode, options) {
  49346. if (options?.json?.stringify && isJSONRequest(url)) {
  49347. return ssrTransformJSON(code, inMap);
  49348. }
  49349. return ssrTransformScript(code, inMap, url, originalCode);
  49350. }
  49351. async function ssrTransformJSON(code, inMap) {
  49352. return {
  49353. code: code.replace('export default', `${ssrModuleExportsKey}.default =`),
  49354. map: inMap,
  49355. deps: [],
  49356. dynamicDeps: [],
  49357. };
  49358. }
  49359. async function ssrTransformScript(code, inMap, url, originalCode) {
  49360. const s = new MagicString(code);
  49361. let ast;
  49362. try {
  49363. ast = parser.parse(code, {
  49364. sourceType: 'module',
  49365. ecmaVersion: 'latest',
  49366. locations: true,
  49367. allowHashBang: true,
  49368. });
  49369. }
  49370. catch (err) {
  49371. if (!err.loc || !err.loc.line)
  49372. throw err;
  49373. const line = err.loc.line;
  49374. throw new Error(`Parse failure: ${err.message}\nAt file: ${url}\nContents of line ${line}: ${code.split('\n')[line - 1]}`);
  49375. }
  49376. let uid = 0;
  49377. const deps = new Set();
  49378. const dynamicDeps = new Set();
  49379. const idToImportMap = new Map();
  49380. const declaredConst = new Set();
  49381. // hoist at the start of the file, after the hashbang
  49382. const hoistIndex = code.match(hashbangRE)?.[0].length ?? 0;
  49383. function defineImport(source) {
  49384. deps.add(source);
  49385. const importId = `__vite_ssr_import_${uid++}__`;
  49386. // There will be an error if the module is called before it is imported,
  49387. // so the module import statement is hoisted to the top
  49388. s.appendLeft(hoistIndex, `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n`);
  49389. return importId;
  49390. }
  49391. function defineExport(position, name, local = name) {
  49392. s.appendLeft(position, `\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` +
  49393. `{ enumerable: true, configurable: true, get(){ return ${local} }});`);
  49394. }
  49395. // 1. check all import statements and record id -> importName map
  49396. for (const node of ast.body) {
  49397. // import foo from 'foo' --> foo -> __import_foo__.default
  49398. // import { baz } from 'foo' --> baz -> __import_foo__.baz
  49399. // import * as ok from 'foo' --> ok -> __import_foo__
  49400. if (node.type === 'ImportDeclaration') {
  49401. const importId = defineImport(node.source.value);
  49402. s.remove(node.start, node.end);
  49403. for (const spec of node.specifiers) {
  49404. if (spec.type === 'ImportSpecifier') {
  49405. idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
  49406. }
  49407. else if (spec.type === 'ImportDefaultSpecifier') {
  49408. idToImportMap.set(spec.local.name, `${importId}.default`);
  49409. }
  49410. else {
  49411. // namespace specifier
  49412. idToImportMap.set(spec.local.name, importId);
  49413. }
  49414. }
  49415. }
  49416. }
  49417. // 2. check all export statements and define exports
  49418. for (const node of ast.body) {
  49419. // named exports
  49420. if (node.type === 'ExportNamedDeclaration') {
  49421. if (node.declaration) {
  49422. if (node.declaration.type === 'FunctionDeclaration' ||
  49423. node.declaration.type === 'ClassDeclaration') {
  49424. // export function foo() {}
  49425. defineExport(node.end, node.declaration.id.name);
  49426. }
  49427. else {
  49428. // export const foo = 1, bar = 2
  49429. for (const declaration of node.declaration.declarations) {
  49430. const names = extract_names(declaration.id);
  49431. for (const name of names) {
  49432. defineExport(node.end, name);
  49433. }
  49434. }
  49435. }
  49436. s.remove(node.start, node.declaration.start);
  49437. }
  49438. else {
  49439. s.remove(node.start, node.end);
  49440. if (node.source) {
  49441. // export { foo, bar } from './foo'
  49442. const importId = defineImport(node.source.value);
  49443. // hoist re-exports near the defined import so they are immediately exported
  49444. for (const spec of node.specifiers) {
  49445. defineExport(hoistIndex, spec.exported.name, `${importId}.${spec.local.name}`);
  49446. }
  49447. }
  49448. else {
  49449. // export { foo, bar }
  49450. for (const spec of node.specifiers) {
  49451. const local = spec.local.name;
  49452. const binding = idToImportMap.get(local);
  49453. defineExport(node.end, spec.exported.name, binding || local);
  49454. }
  49455. }
  49456. }
  49457. }
  49458. // default export
  49459. if (node.type === 'ExportDefaultDeclaration') {
  49460. const expressionTypes = ['FunctionExpression', 'ClassExpression'];
  49461. if ('id' in node.declaration &&
  49462. node.declaration.id &&
  49463. !expressionTypes.includes(node.declaration.type)) {
  49464. // named hoistable/class exports
  49465. // export default function foo() {}
  49466. // export default class A {}
  49467. const { name } = node.declaration.id;
  49468. s.remove(node.start, node.start + 15 /* 'export default '.length */);
  49469. s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` +
  49470. `{ enumerable: true, configurable: true, value: ${name} });`);
  49471. }
  49472. else {
  49473. // anonymous default exports
  49474. s.update(node.start, node.start + 14 /* 'export default'.length */, `${ssrModuleExportsKey}.default =`);
  49475. }
  49476. }
  49477. // export * from './foo'
  49478. if (node.type === 'ExportAllDeclaration') {
  49479. s.remove(node.start, node.end);
  49480. const importId = defineImport(node.source.value);
  49481. // hoist re-exports near the defined import so they are immediately exported
  49482. if (node.exported) {
  49483. defineExport(hoistIndex, node.exported.name, `${importId}`);
  49484. }
  49485. else {
  49486. s.appendLeft(hoistIndex, `${ssrExportAllKey}(${importId});\n`);
  49487. }
  49488. }
  49489. }
  49490. // 3. convert references to import bindings & import.meta references
  49491. walk(ast, {
  49492. onIdentifier(id, parent, parentStack) {
  49493. const grandparent = parentStack[1];
  49494. const binding = idToImportMap.get(id.name);
  49495. if (!binding) {
  49496. return;
  49497. }
  49498. if (isStaticProperty(parent) && parent.shorthand) {
  49499. // let binding used in a property shorthand
  49500. // { foo } -> { foo: __import_x__.foo }
  49501. // skip for destructuring patterns
  49502. if (!isNodeInPattern(parent) ||
  49503. isInDestructuringAssignment(parent, parentStack)) {
  49504. s.appendLeft(id.end, `: ${binding}`);
  49505. }
  49506. }
  49507. else if ((parent.type === 'PropertyDefinition' &&
  49508. grandparent?.type === 'ClassBody') ||
  49509. (parent.type === 'ClassDeclaration' && id === parent.superClass)) {
  49510. if (!declaredConst.has(id.name)) {
  49511. declaredConst.add(id.name);
  49512. // locate the top-most node containing the class declaration
  49513. const topNode = parentStack[parentStack.length - 2];
  49514. s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
  49515. }
  49516. }
  49517. else {
  49518. s.update(id.start, id.end, binding);
  49519. }
  49520. },
  49521. onImportMeta(node) {
  49522. s.update(node.start, node.end, ssrImportMetaKey);
  49523. },
  49524. onDynamicImport(node) {
  49525. s.update(node.start, node.start + 6, ssrDynamicImportKey);
  49526. if (node.type === 'ImportExpression' && node.source.type === 'Literal') {
  49527. dynamicDeps.add(node.source.value);
  49528. }
  49529. },
  49530. });
  49531. let map = s.generateMap({ hires: true });
  49532. if (inMap && inMap.mappings && inMap.sources.length > 0) {
  49533. map = combineSourcemaps(url, [
  49534. {
  49535. ...map,
  49536. sources: inMap.sources,
  49537. sourcesContent: inMap.sourcesContent,
  49538. },
  49539. inMap,
  49540. ], false);
  49541. }
  49542. else {
  49543. map.sources = [url];
  49544. // needs to use originalCode instead of code
  49545. // because code might be already transformed even if map is null
  49546. map.sourcesContent = [originalCode];
  49547. }
  49548. return {
  49549. code: s.toString(),
  49550. map,
  49551. deps: [...deps],
  49552. dynamicDeps: [...dynamicDeps],
  49553. };
  49554. }
  49555. const isNodeInPatternWeakSet = new WeakSet();
  49556. const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node);
  49557. const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node);
  49558. /**
  49559. * Same logic from \@vue/compiler-core & \@vue/compiler-sfc
  49560. * Except this is using acorn AST
  49561. */
  49562. function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
  49563. const parentStack = [];
  49564. const varKindStack = [];
  49565. const scopeMap = new WeakMap();
  49566. const identifiers = [];
  49567. const setScope = (node, name) => {
  49568. let scopeIds = scopeMap.get(node);
  49569. if (scopeIds && scopeIds.has(name)) {
  49570. return;
  49571. }
  49572. if (!scopeIds) {
  49573. scopeIds = new Set();
  49574. scopeMap.set(node, scopeIds);
  49575. }
  49576. scopeIds.add(name);
  49577. };
  49578. function isInScope(name, parents) {
  49579. return parents.some((node) => node && scopeMap.get(node)?.has(name));
  49580. }
  49581. function handlePattern(p, parentScope) {
  49582. if (p.type === 'Identifier') {
  49583. setScope(parentScope, p.name);
  49584. }
  49585. else if (p.type === 'RestElement') {
  49586. handlePattern(p.argument, parentScope);
  49587. }
  49588. else if (p.type === 'ObjectPattern') {
  49589. p.properties.forEach((property) => {
  49590. if (property.type === 'RestElement') {
  49591. setScope(parentScope, property.argument.name);
  49592. }
  49593. else {
  49594. handlePattern(property.value, parentScope);
  49595. }
  49596. });
  49597. }
  49598. else if (p.type === 'ArrayPattern') {
  49599. p.elements.forEach((element) => {
  49600. if (element) {
  49601. handlePattern(element, parentScope);
  49602. }
  49603. });
  49604. }
  49605. else if (p.type === 'AssignmentPattern') {
  49606. handlePattern(p.left, parentScope);
  49607. }
  49608. else {
  49609. setScope(parentScope, p.name);
  49610. }
  49611. }
  49612. walk$1(root, {
  49613. enter(node, parent) {
  49614. if (node.type === 'ImportDeclaration') {
  49615. return this.skip();
  49616. }
  49617. // track parent stack, skip for "else-if"/"else" branches as acorn nests
  49618. // the ast within "if" nodes instead of flattening them
  49619. if (parent &&
  49620. !(parent.type === 'IfStatement' && node === parent.alternate)) {
  49621. parentStack.unshift(parent);
  49622. }
  49623. // track variable declaration kind stack used by VariableDeclarator
  49624. if (node.type === 'VariableDeclaration') {
  49625. varKindStack.unshift(node.kind);
  49626. }
  49627. if (node.type === 'MetaProperty' && node.meta.name === 'import') {
  49628. onImportMeta(node);
  49629. }
  49630. else if (node.type === 'ImportExpression') {
  49631. onDynamicImport(node);
  49632. }
  49633. if (node.type === 'Identifier') {
  49634. if (!isInScope(node.name, parentStack) &&
  49635. isRefIdentifier(node, parent, parentStack)) {
  49636. // record the identifier, for DFS -> BFS
  49637. identifiers.push([node, parentStack.slice(0)]);
  49638. }
  49639. }
  49640. else if (isFunction(node)) {
  49641. // If it is a function declaration, it could be shadowing an import
  49642. // Add its name to the scope so it won't get replaced
  49643. if (node.type === 'FunctionDeclaration') {
  49644. const parentScope = findParentScope(parentStack);
  49645. if (parentScope) {
  49646. setScope(parentScope, node.id.name);
  49647. }
  49648. }
  49649. // walk function expressions and add its arguments to known identifiers
  49650. // so that we don't prefix them
  49651. node.params.forEach((p) => {
  49652. if (p.type === 'ObjectPattern' || p.type === 'ArrayPattern') {
  49653. handlePattern(p, node);
  49654. return;
  49655. }
  49656. walk$1(p.type === 'AssignmentPattern' ? p.left : p, {
  49657. enter(child, parent) {
  49658. // skip params default value of destructure
  49659. if (parent?.type === 'AssignmentPattern' &&
  49660. parent?.right === child) {
  49661. return this.skip();
  49662. }
  49663. if (child.type !== 'Identifier')
  49664. return;
  49665. // do not record as scope variable if is a destructuring keyword
  49666. if (isStaticPropertyKey(child, parent))
  49667. return;
  49668. // do not record if this is a default value
  49669. // assignment of a destructuring variable
  49670. if ((parent?.type === 'TemplateLiteral' &&
  49671. parent?.expressions.includes(child)) ||
  49672. (parent?.type === 'CallExpression' && parent?.callee === child)) {
  49673. return;
  49674. }
  49675. setScope(node, child.name);
  49676. },
  49677. });
  49678. });
  49679. }
  49680. else if (node.type === 'Property' && parent.type === 'ObjectPattern') {
  49681. // mark property in destructuring pattern
  49682. setIsNodeInPattern(node);
  49683. }
  49684. else if (node.type === 'VariableDeclarator') {
  49685. const parentFunction = findParentScope(parentStack, varKindStack[0] === 'var');
  49686. if (parentFunction) {
  49687. handlePattern(node.id, parentFunction);
  49688. }
  49689. }
  49690. else if (node.type === 'CatchClause' && node.param) {
  49691. handlePattern(node.param, node);
  49692. }
  49693. },
  49694. leave(node, parent) {
  49695. // untrack parent stack from above
  49696. if (parent &&
  49697. !(parent.type === 'IfStatement' && node === parent.alternate)) {
  49698. parentStack.shift();
  49699. }
  49700. if (node.type === 'VariableDeclaration') {
  49701. varKindStack.shift();
  49702. }
  49703. },
  49704. });
  49705. // emit the identifier events in BFS so the hoisted declarations
  49706. // can be captured correctly
  49707. identifiers.forEach(([node, stack]) => {
  49708. if (!isInScope(node.name, stack))
  49709. onIdentifier(node, stack[0], stack);
  49710. });
  49711. }
  49712. function isRefIdentifier(id, parent, parentStack) {
  49713. // declaration id
  49714. if (parent.type === 'CatchClause' ||
  49715. ((parent.type === 'VariableDeclarator' ||
  49716. parent.type === 'ClassDeclaration') &&
  49717. parent.id === id)) {
  49718. return false;
  49719. }
  49720. if (isFunction(parent)) {
  49721. // function declaration/expression id
  49722. if (parent.id === id) {
  49723. return false;
  49724. }
  49725. // params list
  49726. if (parent.params.includes(id)) {
  49727. return false;
  49728. }
  49729. }
  49730. // class method name
  49731. if (parent.type === 'MethodDefinition' && !parent.computed) {
  49732. return false;
  49733. }
  49734. // property key
  49735. if (isStaticPropertyKey(id, parent)) {
  49736. return false;
  49737. }
  49738. // object destructuring pattern
  49739. if (isNodeInPattern(parent) && parent.value === id) {
  49740. return false;
  49741. }
  49742. // non-assignment array destructuring pattern
  49743. if (parent.type === 'ArrayPattern' &&
  49744. !isInDestructuringAssignment(parent, parentStack)) {
  49745. return false;
  49746. }
  49747. // member expression property
  49748. if (parent.type === 'MemberExpression' &&
  49749. parent.property === id &&
  49750. !parent.computed) {
  49751. return false;
  49752. }
  49753. if (parent.type === 'ExportSpecifier') {
  49754. return false;
  49755. }
  49756. // is a special keyword but parsed as identifier
  49757. if (id.name === 'arguments') {
  49758. return false;
  49759. }
  49760. return true;
  49761. }
  49762. const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed;
  49763. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  49764. const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
  49765. function isFunction(node) {
  49766. return functionNodeTypeRE.test(node.type);
  49767. }
  49768. const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
  49769. function isBlock(node) {
  49770. return blockNodeTypeRE.test(node.type);
  49771. }
  49772. function findParentScope(parentStack, isVar = false) {
  49773. return parentStack.find(isVar ? isFunction : isBlock);
  49774. }
  49775. function isInDestructuringAssignment(parent, parentStack) {
  49776. if (parent &&
  49777. (parent.type === 'Property' || parent.type === 'ArrayPattern')) {
  49778. return parentStack.some((i) => i.type === 'AssignmentExpression');
  49779. }
  49780. return false;
  49781. }
  49782. let offset;
  49783. try {
  49784. new Function('throw new Error(1)')();
  49785. }
  49786. catch (e) {
  49787. // in Node 12, stack traces account for the function wrapper.
  49788. // in Node 13 and later, the function wrapper adds two lines,
  49789. // which must be subtracted to generate a valid mapping
  49790. const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]);
  49791. offset = match ? +match[1] - 1 : 0;
  49792. }
  49793. function ssrRewriteStacktrace(stack, moduleGraph) {
  49794. return stack
  49795. .split('\n')
  49796. .map((line) => {
  49797. return line.replace(/^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varName, url, line, column) => {
  49798. if (!url)
  49799. return input;
  49800. const mod = moduleGraph.urlToModuleMap.get(url);
  49801. const rawSourceMap = mod?.ssrTransformResult?.map;
  49802. if (!rawSourceMap) {
  49803. return input;
  49804. }
  49805. const traced = new TraceMap(rawSourceMap);
  49806. const pos = originalPositionFor$1(traced, {
  49807. line: Number(line) - offset,
  49808. column: Number(column),
  49809. });
  49810. if (!pos.source || pos.line == null || pos.column == null) {
  49811. return input;
  49812. }
  49813. const trimmedVarName = varName.trim();
  49814. const source = `${pos.source}:${pos.line}:${pos.column}`;
  49815. if (!trimmedVarName || trimmedVarName === 'eval') {
  49816. return ` at ${source}`;
  49817. }
  49818. else {
  49819. return ` at ${trimmedVarName} (${source})`;
  49820. }
  49821. });
  49822. })
  49823. .join('\n');
  49824. }
  49825. function rebindErrorStacktrace(e, stacktrace) {
  49826. const { configurable, writable } = Object.getOwnPropertyDescriptor(e, 'stack');
  49827. if (configurable) {
  49828. Object.defineProperty(e, 'stack', {
  49829. value: stacktrace,
  49830. enumerable: true,
  49831. configurable: true,
  49832. writable: true,
  49833. });
  49834. }
  49835. else if (writable) {
  49836. e.stack = stacktrace;
  49837. }
  49838. }
  49839. const rewroteStacktraces = new WeakSet();
  49840. function ssrFixStacktrace(e, moduleGraph) {
  49841. if (!e.stack)
  49842. return;
  49843. // stacktrace shouldn't be rewritten more than once
  49844. if (rewroteStacktraces.has(e))
  49845. return;
  49846. const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph);
  49847. rebindErrorStacktrace(e, stacktrace);
  49848. rewroteStacktraces.add(e);
  49849. }
  49850. // eslint-disable-next-line @typescript-eslint/no-empty-function
  49851. const AsyncFunction = async function () { }.constructor;
  49852. let fnDeclarationLineCount = 0;
  49853. {
  49854. const body = '/*code*/';
  49855. const source = new AsyncFunction('a', 'b', body).toString();
  49856. fnDeclarationLineCount =
  49857. source.slice(0, source.indexOf(body)).split('\n').length - 1;
  49858. }
  49859. const pendingModules = new Map();
  49860. const pendingImports = new Map();
  49861. const importErrors = new WeakMap();
  49862. async function ssrLoadModule(url, server, context = { global }, urlStack = [], fixStacktrace) {
  49863. url = unwrapId(url);
  49864. // when we instantiate multiple dependency modules in parallel, they may
  49865. // point to shared modules. We need to avoid duplicate instantiation attempts
  49866. // by register every module as pending synchronously so that all subsequent
  49867. // request to that module are simply waiting on the same promise.
  49868. const pending = pendingModules.get(url);
  49869. if (pending) {
  49870. return pending;
  49871. }
  49872. const modulePromise = instantiateModule(url, server, context, urlStack, fixStacktrace);
  49873. pendingModules.set(url, modulePromise);
  49874. modulePromise
  49875. .catch(() => {
  49876. pendingImports.delete(url);
  49877. })
  49878. .finally(() => {
  49879. pendingModules.delete(url);
  49880. });
  49881. return modulePromise;
  49882. }
  49883. async function instantiateModule(url, server, context = { global }, urlStack = [], fixStacktrace) {
  49884. const { moduleGraph } = server;
  49885. const mod = await moduleGraph.ensureEntryFromUrl(url, true);
  49886. if (mod.ssrError) {
  49887. throw mod.ssrError;
  49888. }
  49889. if (mod.ssrModule) {
  49890. return mod.ssrModule;
  49891. }
  49892. const result = mod.ssrTransformResult ||
  49893. (await transformRequest(url, server, { ssr: true }));
  49894. if (!result) {
  49895. // TODO more info? is this even necessary?
  49896. throw new Error(`failed to load module for ssr: ${url}`);
  49897. }
  49898. const ssrModule = {
  49899. [Symbol.toStringTag]: 'Module',
  49900. };
  49901. Object.defineProperty(ssrModule, '__esModule', { value: true });
  49902. // Tolerate circular imports by ensuring the module can be
  49903. // referenced before it's been instantiated.
  49904. mod.ssrModule = ssrModule;
  49905. const ssrImportMeta = {
  49906. // The filesystem URL, matching native Node.js modules
  49907. url: pathToFileURL(mod.file).toString(),
  49908. };
  49909. urlStack = urlStack.concat(url);
  49910. const isCircular = (url) => urlStack.includes(url);
  49911. const { isProduction, resolve: { dedupe, preserveSymlinks }, root, } = server.config;
  49912. const resolveOptions = {
  49913. mainFields: ['main'],
  49914. browserField: true,
  49915. conditions: [],
  49916. overrideConditions: ['production', 'development'],
  49917. extensions: ['.js', '.cjs', '.json'],
  49918. dedupe,
  49919. preserveSymlinks,
  49920. isBuild: false,
  49921. isProduction,
  49922. root,
  49923. };
  49924. // Since dynamic imports can happen in parallel, we need to
  49925. // account for multiple pending deps and duplicate imports.
  49926. const pendingDeps = [];
  49927. const ssrImport = async (dep) => {
  49928. try {
  49929. if (dep[0] !== '.' && dep[0] !== '/') {
  49930. return await nodeImport(dep, mod.file, resolveOptions);
  49931. }
  49932. // convert to rollup URL because `pendingImports`, `moduleGraph.urlToModuleMap` requires that
  49933. dep = unwrapId(dep);
  49934. if (!isCircular(dep) && !pendingImports.get(dep)?.some(isCircular)) {
  49935. pendingDeps.push(dep);
  49936. if (pendingDeps.length === 1) {
  49937. pendingImports.set(url, pendingDeps);
  49938. }
  49939. const mod = await ssrLoadModule(dep, server, context, urlStack, fixStacktrace);
  49940. if (pendingDeps.length === 1) {
  49941. pendingImports.delete(url);
  49942. }
  49943. else {
  49944. pendingDeps.splice(pendingDeps.indexOf(dep), 1);
  49945. }
  49946. // return local module to avoid race condition #5470
  49947. return mod;
  49948. }
  49949. return moduleGraph.urlToModuleMap.get(dep)?.ssrModule;
  49950. }
  49951. catch (err) {
  49952. // tell external error handler which mod was imported with error
  49953. importErrors.set(err, { importee: dep });
  49954. throw err;
  49955. }
  49956. };
  49957. const ssrDynamicImport = (dep) => {
  49958. // #3087 dynamic import vars is ignored at rewrite import path,
  49959. // so here need process relative path
  49960. if (dep[0] === '.') {
  49961. dep = path$o.posix.resolve(path$o.dirname(url), dep);
  49962. }
  49963. return ssrImport(dep);
  49964. };
  49965. function ssrExportAll(sourceModule) {
  49966. for (const key in sourceModule) {
  49967. if (key !== 'default' && key !== '__esModule') {
  49968. Object.defineProperty(ssrModule, key, {
  49969. enumerable: true,
  49970. configurable: true,
  49971. get() {
  49972. return sourceModule[key];
  49973. },
  49974. });
  49975. }
  49976. }
  49977. }
  49978. let sourceMapSuffix = '';
  49979. if (result.map) {
  49980. const moduleSourceMap = Object.assign({}, result.map, {
  49981. // currently we need to offset the line
  49982. // https://github.com/nodejs/node/issues/43047#issuecomment-1180632750
  49983. mappings: ';'.repeat(fnDeclarationLineCount) + result.map.mappings,
  49984. });
  49985. sourceMapSuffix =
  49986. '\n//# sourceMappingURL=' + genSourceMapUrl(moduleSourceMap);
  49987. }
  49988. try {
  49989. const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, '"use strict";' +
  49990. result.code +
  49991. `\n//# sourceURL=${mod.url}${sourceMapSuffix}`);
  49992. await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll);
  49993. }
  49994. catch (e) {
  49995. mod.ssrError = e;
  49996. const errorData = importErrors.get(e);
  49997. if (e.stack && fixStacktrace) {
  49998. ssrFixStacktrace(e, moduleGraph);
  49999. }
  50000. server.config.logger.error(colors$1.red(`Error when evaluating SSR module ${url}:` +
  50001. (errorData?.importee
  50002. ? ` failed to import "${errorData.importee}"`
  50003. : '') +
  50004. `\n|- ${e.stack}\n`), {
  50005. timestamp: true,
  50006. clear: server.config.clearScreen,
  50007. error: e,
  50008. });
  50009. throw e;
  50010. }
  50011. return Object.freeze(ssrModule);
  50012. }
  50013. // In node@12+ we can use dynamic import to load CJS and ESM
  50014. async function nodeImport(id, importer, resolveOptions) {
  50015. let url;
  50016. if (id.startsWith('node:') || id.startsWith('data:') || isBuiltin(id)) {
  50017. url = id;
  50018. }
  50019. else {
  50020. const resolved = tryNodeResolve(id, importer,
  50021. // Non-external modules can import ESM-only modules, but only outside
  50022. // of test runs, because we use Node `require` in Jest to avoid segfault.
  50023. // @ts-expect-error jest only exists when running Jest
  50024. typeof jest === 'undefined'
  50025. ? { ...resolveOptions, tryEsmOnly: true }
  50026. : resolveOptions, false);
  50027. if (!resolved) {
  50028. const err = new Error(`Cannot find module '${id}' imported from '${importer}'`);
  50029. err.code = 'ERR_MODULE_NOT_FOUND';
  50030. throw err;
  50031. }
  50032. url = resolved.id;
  50033. if (usingDynamicImport) {
  50034. url = pathToFileURL(url).toString();
  50035. }
  50036. }
  50037. const mod = await dynamicImport(url);
  50038. return proxyESM(mod);
  50039. }
  50040. // rollup-style default import interop for cjs
  50041. function proxyESM(mod) {
  50042. // This is the only sensible option when the exports object is a primitive
  50043. if (isPrimitive(mod))
  50044. return { default: mod };
  50045. let defaultExport = 'default' in mod ? mod.default : mod;
  50046. if (!isPrimitive(defaultExport) && '__esModule' in defaultExport) {
  50047. mod = defaultExport;
  50048. if ('default' in defaultExport) {
  50049. defaultExport = defaultExport.default;
  50050. }
  50051. }
  50052. return new Proxy(mod, {
  50053. get(mod, prop) {
  50054. if (prop === 'default')
  50055. return defaultExport;
  50056. return mod[prop] ?? defaultExport?.[prop];
  50057. },
  50058. });
  50059. }
  50060. function isPrimitive(value) {
  50061. return !value || (typeof value !== 'object' && typeof value !== 'function');
  50062. }
  50063. function bindShortcuts(server, opts) {
  50064. if (!server.httpServer || !process.stdin.isTTY || process.env.CI) {
  50065. return;
  50066. }
  50067. server._shortcutsOptions = opts;
  50068. if (opts.print) {
  50069. server.config.logger.info(colors$1.dim(colors$1.green(' ➜')) +
  50070. colors$1.dim(' press ') +
  50071. colors$1.bold('h') +
  50072. colors$1.dim(' to show help'));
  50073. }
  50074. const shortcuts = (opts.customShortcuts ?? [])
  50075. .filter(isDefined)
  50076. .concat(BASE_SHORTCUTS);
  50077. let actionRunning = false;
  50078. const onInput = async (input) => {
  50079. // ctrl+c or ctrl+d
  50080. if (input === '\x03' || input === '\x04') {
  50081. await server.close().finally(() => process.exit(1));
  50082. return;
  50083. }
  50084. if (actionRunning)
  50085. return;
  50086. if (input === 'h') {
  50087. server.config.logger.info([
  50088. '',
  50089. colors$1.bold(' Shortcuts'),
  50090. ...shortcuts.map((shortcut) => colors$1.dim(' press ') +
  50091. colors$1.bold(shortcut.key) +
  50092. colors$1.dim(` to ${shortcut.description}`)),
  50093. ].join('\n'));
  50094. }
  50095. const shortcut = shortcuts.find((shortcut) => shortcut.key === input);
  50096. if (!shortcut)
  50097. return;
  50098. actionRunning = true;
  50099. await shortcut.action(server);
  50100. actionRunning = false;
  50101. };
  50102. process.stdin.setRawMode(true);
  50103. process.stdin.on('data', onInput).setEncoding('utf8').resume();
  50104. server.httpServer.on('close', () => {
  50105. process.stdin.off('data', onInput).pause();
  50106. });
  50107. }
  50108. const BASE_SHORTCUTS = [
  50109. {
  50110. key: 'r',
  50111. description: 'restart the server',
  50112. async action(server) {
  50113. await server.restart();
  50114. },
  50115. },
  50116. {
  50117. key: 'u',
  50118. description: 'show server url',
  50119. action(server) {
  50120. server.config.logger.info('');
  50121. server.printUrls();
  50122. },
  50123. },
  50124. {
  50125. key: 'o',
  50126. description: 'open in browser',
  50127. action(server) {
  50128. server.openBrowser();
  50129. },
  50130. },
  50131. {
  50132. key: 'c',
  50133. description: 'clear console',
  50134. action(server) {
  50135. server.config.logger.clearScreen('error');
  50136. },
  50137. },
  50138. {
  50139. key: 'q',
  50140. description: 'quit',
  50141. async action(server) {
  50142. await server.close().finally(() => process.exit());
  50143. },
  50144. },
  50145. ];
  50146. var bufferUtil$1 = {exports: {}};
  50147. var constants = {
  50148. BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
  50149. EMPTY_BUFFER: Buffer.alloc(0),
  50150. GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
  50151. kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
  50152. kListener: Symbol('kListener'),
  50153. kStatusCode: Symbol('status-code'),
  50154. kWebSocket: Symbol('websocket'),
  50155. NOOP: () => {}
  50156. };
  50157. const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
  50158. const FastBuffer$2 = Buffer[Symbol.species];
  50159. /**
  50160. * Merges an array of buffers into a new buffer.
  50161. *
  50162. * @param {Buffer[]} list The array of buffers to concat
  50163. * @param {Number} totalLength The total length of buffers in the list
  50164. * @return {Buffer} The resulting buffer
  50165. * @public
  50166. */
  50167. function concat$1(list, totalLength) {
  50168. if (list.length === 0) return EMPTY_BUFFER$3;
  50169. if (list.length === 1) return list[0];
  50170. const target = Buffer.allocUnsafe(totalLength);
  50171. let offset = 0;
  50172. for (let i = 0; i < list.length; i++) {
  50173. const buf = list[i];
  50174. target.set(buf, offset);
  50175. offset += buf.length;
  50176. }
  50177. if (offset < totalLength) {
  50178. return new FastBuffer$2(target.buffer, target.byteOffset, offset);
  50179. }
  50180. return target;
  50181. }
  50182. /**
  50183. * Masks a buffer using the given mask.
  50184. *
  50185. * @param {Buffer} source The buffer to mask
  50186. * @param {Buffer} mask The mask to use
  50187. * @param {Buffer} output The buffer where to store the result
  50188. * @param {Number} offset The offset at which to start writing
  50189. * @param {Number} length The number of bytes to mask.
  50190. * @public
  50191. */
  50192. function _mask(source, mask, output, offset, length) {
  50193. for (let i = 0; i < length; i++) {
  50194. output[offset + i] = source[i] ^ mask[i & 3];
  50195. }
  50196. }
  50197. /**
  50198. * Unmasks a buffer using the given mask.
  50199. *
  50200. * @param {Buffer} buffer The buffer to unmask
  50201. * @param {Buffer} mask The mask to use
  50202. * @public
  50203. */
  50204. function _unmask(buffer, mask) {
  50205. for (let i = 0; i < buffer.length; i++) {
  50206. buffer[i] ^= mask[i & 3];
  50207. }
  50208. }
  50209. /**
  50210. * Converts a buffer to an `ArrayBuffer`.
  50211. *
  50212. * @param {Buffer} buf The buffer to convert
  50213. * @return {ArrayBuffer} Converted buffer
  50214. * @public
  50215. */
  50216. function toArrayBuffer$1(buf) {
  50217. if (buf.length === buf.buffer.byteLength) {
  50218. return buf.buffer;
  50219. }
  50220. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
  50221. }
  50222. /**
  50223. * Converts `data` to a `Buffer`.
  50224. *
  50225. * @param {*} data The data to convert
  50226. * @return {Buffer} The buffer
  50227. * @throws {TypeError}
  50228. * @public
  50229. */
  50230. function toBuffer$2(data) {
  50231. toBuffer$2.readOnly = true;
  50232. if (Buffer.isBuffer(data)) return data;
  50233. let buf;
  50234. if (data instanceof ArrayBuffer) {
  50235. buf = new FastBuffer$2(data);
  50236. } else if (ArrayBuffer.isView(data)) {
  50237. buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength);
  50238. } else {
  50239. buf = Buffer.from(data);
  50240. toBuffer$2.readOnly = false;
  50241. }
  50242. return buf;
  50243. }
  50244. bufferUtil$1.exports = {
  50245. concat: concat$1,
  50246. mask: _mask,
  50247. toArrayBuffer: toArrayBuffer$1,
  50248. toBuffer: toBuffer$2,
  50249. unmask: _unmask
  50250. };
  50251. /* istanbul ignore else */
  50252. if (!process.env.WS_NO_BUFFER_UTIL) {
  50253. try {
  50254. const bufferUtil = require('bufferutil');
  50255. bufferUtil$1.exports.mask = function (source, mask, output, offset, length) {
  50256. if (length < 48) _mask(source, mask, output, offset, length);
  50257. else bufferUtil.mask(source, mask, output, offset, length);
  50258. };
  50259. bufferUtil$1.exports.unmask = function (buffer, mask) {
  50260. if (buffer.length < 32) _unmask(buffer, mask);
  50261. else bufferUtil.unmask(buffer, mask);
  50262. };
  50263. } catch (e) {
  50264. // Continue regardless of the error.
  50265. }
  50266. }
  50267. var bufferUtilExports = bufferUtil$1.exports;
  50268. const kDone = Symbol('kDone');
  50269. const kRun = Symbol('kRun');
  50270. /**
  50271. * A very simple job queue with adjustable concurrency. Adapted from
  50272. * https://github.com/STRML/async-limiter
  50273. */
  50274. let Limiter$1 = class Limiter {
  50275. /**
  50276. * Creates a new `Limiter`.
  50277. *
  50278. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  50279. * to run concurrently
  50280. */
  50281. constructor(concurrency) {
  50282. this[kDone] = () => {
  50283. this.pending--;
  50284. this[kRun]();
  50285. };
  50286. this.concurrency = concurrency || Infinity;
  50287. this.jobs = [];
  50288. this.pending = 0;
  50289. }
  50290. /**
  50291. * Adds a job to the queue.
  50292. *
  50293. * @param {Function} job The job to run
  50294. * @public
  50295. */
  50296. add(job) {
  50297. this.jobs.push(job);
  50298. this[kRun]();
  50299. }
  50300. /**
  50301. * Removes a job from the queue and runs it if possible.
  50302. *
  50303. * @private
  50304. */
  50305. [kRun]() {
  50306. if (this.pending === this.concurrency) return;
  50307. if (this.jobs.length) {
  50308. const job = this.jobs.shift();
  50309. this.pending++;
  50310. job(this[kDone]);
  50311. }
  50312. }
  50313. };
  50314. var limiter = Limiter$1;
  50315. const zlib = require$$0$a;
  50316. const bufferUtil = bufferUtilExports;
  50317. const Limiter = limiter;
  50318. const { kStatusCode: kStatusCode$2 } = constants;
  50319. const FastBuffer$1 = Buffer[Symbol.species];
  50320. const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
  50321. const kPerMessageDeflate = Symbol('permessage-deflate');
  50322. const kTotalLength = Symbol('total-length');
  50323. const kCallback = Symbol('callback');
  50324. const kBuffers = Symbol('buffers');
  50325. const kError$1 = Symbol('error');
  50326. //
  50327. // We limit zlib concurrency, which prevents severe memory fragmentation
  50328. // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
  50329. // and https://github.com/websockets/ws/issues/1202
  50330. //
  50331. // Intentionally global; it's the global thread pool that's an issue.
  50332. //
  50333. let zlibLimiter;
  50334. /**
  50335. * permessage-deflate implementation.
  50336. */
  50337. let PerMessageDeflate$4 = class PerMessageDeflate {
  50338. /**
  50339. * Creates a PerMessageDeflate instance.
  50340. *
  50341. * @param {Object} [options] Configuration options
  50342. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  50343. * for, or request, a custom client window size
  50344. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  50345. * acknowledge disabling of client context takeover
  50346. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  50347. * calls to zlib
  50348. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  50349. * use of a custom server window size
  50350. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  50351. * disabling of server context takeover
  50352. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  50353. * messages should not be compressed if context takeover is disabled
  50354. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  50355. * deflate
  50356. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  50357. * inflate
  50358. * @param {Boolean} [isServer=false] Create the instance in either server or
  50359. * client mode
  50360. * @param {Number} [maxPayload=0] The maximum allowed message length
  50361. */
  50362. constructor(options, isServer, maxPayload) {
  50363. this._maxPayload = maxPayload | 0;
  50364. this._options = options || {};
  50365. this._threshold =
  50366. this._options.threshold !== undefined ? this._options.threshold : 1024;
  50367. this._isServer = !!isServer;
  50368. this._deflate = null;
  50369. this._inflate = null;
  50370. this.params = null;
  50371. if (!zlibLimiter) {
  50372. const concurrency =
  50373. this._options.concurrencyLimit !== undefined
  50374. ? this._options.concurrencyLimit
  50375. : 10;
  50376. zlibLimiter = new Limiter(concurrency);
  50377. }
  50378. }
  50379. /**
  50380. * @type {String}
  50381. */
  50382. static get extensionName() {
  50383. return 'permessage-deflate';
  50384. }
  50385. /**
  50386. * Create an extension negotiation offer.
  50387. *
  50388. * @return {Object} Extension parameters
  50389. * @public
  50390. */
  50391. offer() {
  50392. const params = {};
  50393. if (this._options.serverNoContextTakeover) {
  50394. params.server_no_context_takeover = true;
  50395. }
  50396. if (this._options.clientNoContextTakeover) {
  50397. params.client_no_context_takeover = true;
  50398. }
  50399. if (this._options.serverMaxWindowBits) {
  50400. params.server_max_window_bits = this._options.serverMaxWindowBits;
  50401. }
  50402. if (this._options.clientMaxWindowBits) {
  50403. params.client_max_window_bits = this._options.clientMaxWindowBits;
  50404. } else if (this._options.clientMaxWindowBits == null) {
  50405. params.client_max_window_bits = true;
  50406. }
  50407. return params;
  50408. }
  50409. /**
  50410. * Accept an extension negotiation offer/response.
  50411. *
  50412. * @param {Array} configurations The extension negotiation offers/reponse
  50413. * @return {Object} Accepted configuration
  50414. * @public
  50415. */
  50416. accept(configurations) {
  50417. configurations = this.normalizeParams(configurations);
  50418. this.params = this._isServer
  50419. ? this.acceptAsServer(configurations)
  50420. : this.acceptAsClient(configurations);
  50421. return this.params;
  50422. }
  50423. /**
  50424. * Releases all resources used by the extension.
  50425. *
  50426. * @public
  50427. */
  50428. cleanup() {
  50429. if (this._inflate) {
  50430. this._inflate.close();
  50431. this._inflate = null;
  50432. }
  50433. if (this._deflate) {
  50434. const callback = this._deflate[kCallback];
  50435. this._deflate.close();
  50436. this._deflate = null;
  50437. if (callback) {
  50438. callback(
  50439. new Error(
  50440. 'The deflate stream was closed while data was being processed'
  50441. )
  50442. );
  50443. }
  50444. }
  50445. }
  50446. /**
  50447. * Accept an extension negotiation offer.
  50448. *
  50449. * @param {Array} offers The extension negotiation offers
  50450. * @return {Object} Accepted configuration
  50451. * @private
  50452. */
  50453. acceptAsServer(offers) {
  50454. const opts = this._options;
  50455. const accepted = offers.find((params) => {
  50456. if (
  50457. (opts.serverNoContextTakeover === false &&
  50458. params.server_no_context_takeover) ||
  50459. (params.server_max_window_bits &&
  50460. (opts.serverMaxWindowBits === false ||
  50461. (typeof opts.serverMaxWindowBits === 'number' &&
  50462. opts.serverMaxWindowBits > params.server_max_window_bits))) ||
  50463. (typeof opts.clientMaxWindowBits === 'number' &&
  50464. !params.client_max_window_bits)
  50465. ) {
  50466. return false;
  50467. }
  50468. return true;
  50469. });
  50470. if (!accepted) {
  50471. throw new Error('None of the extension offers can be accepted');
  50472. }
  50473. if (opts.serverNoContextTakeover) {
  50474. accepted.server_no_context_takeover = true;
  50475. }
  50476. if (opts.clientNoContextTakeover) {
  50477. accepted.client_no_context_takeover = true;
  50478. }
  50479. if (typeof opts.serverMaxWindowBits === 'number') {
  50480. accepted.server_max_window_bits = opts.serverMaxWindowBits;
  50481. }
  50482. if (typeof opts.clientMaxWindowBits === 'number') {
  50483. accepted.client_max_window_bits = opts.clientMaxWindowBits;
  50484. } else if (
  50485. accepted.client_max_window_bits === true ||
  50486. opts.clientMaxWindowBits === false
  50487. ) {
  50488. delete accepted.client_max_window_bits;
  50489. }
  50490. return accepted;
  50491. }
  50492. /**
  50493. * Accept the extension negotiation response.
  50494. *
  50495. * @param {Array} response The extension negotiation response
  50496. * @return {Object} Accepted configuration
  50497. * @private
  50498. */
  50499. acceptAsClient(response) {
  50500. const params = response[0];
  50501. if (
  50502. this._options.clientNoContextTakeover === false &&
  50503. params.client_no_context_takeover
  50504. ) {
  50505. throw new Error('Unexpected parameter "client_no_context_takeover"');
  50506. }
  50507. if (!params.client_max_window_bits) {
  50508. if (typeof this._options.clientMaxWindowBits === 'number') {
  50509. params.client_max_window_bits = this._options.clientMaxWindowBits;
  50510. }
  50511. } else if (
  50512. this._options.clientMaxWindowBits === false ||
  50513. (typeof this._options.clientMaxWindowBits === 'number' &&
  50514. params.client_max_window_bits > this._options.clientMaxWindowBits)
  50515. ) {
  50516. throw new Error(
  50517. 'Unexpected or invalid parameter "client_max_window_bits"'
  50518. );
  50519. }
  50520. return params;
  50521. }
  50522. /**
  50523. * Normalize parameters.
  50524. *
  50525. * @param {Array} configurations The extension negotiation offers/reponse
  50526. * @return {Array} The offers/response with normalized parameters
  50527. * @private
  50528. */
  50529. normalizeParams(configurations) {
  50530. configurations.forEach((params) => {
  50531. Object.keys(params).forEach((key) => {
  50532. let value = params[key];
  50533. if (value.length > 1) {
  50534. throw new Error(`Parameter "${key}" must have only a single value`);
  50535. }
  50536. value = value[0];
  50537. if (key === 'client_max_window_bits') {
  50538. if (value !== true) {
  50539. const num = +value;
  50540. if (!Number.isInteger(num) || num < 8 || num > 15) {
  50541. throw new TypeError(
  50542. `Invalid value for parameter "${key}": ${value}`
  50543. );
  50544. }
  50545. value = num;
  50546. } else if (!this._isServer) {
  50547. throw new TypeError(
  50548. `Invalid value for parameter "${key}": ${value}`
  50549. );
  50550. }
  50551. } else if (key === 'server_max_window_bits') {
  50552. const num = +value;
  50553. if (!Number.isInteger(num) || num < 8 || num > 15) {
  50554. throw new TypeError(
  50555. `Invalid value for parameter "${key}": ${value}`
  50556. );
  50557. }
  50558. value = num;
  50559. } else if (
  50560. key === 'client_no_context_takeover' ||
  50561. key === 'server_no_context_takeover'
  50562. ) {
  50563. if (value !== true) {
  50564. throw new TypeError(
  50565. `Invalid value for parameter "${key}": ${value}`
  50566. );
  50567. }
  50568. } else {
  50569. throw new Error(`Unknown parameter "${key}"`);
  50570. }
  50571. params[key] = value;
  50572. });
  50573. });
  50574. return configurations;
  50575. }
  50576. /**
  50577. * Decompress data. Concurrency limited.
  50578. *
  50579. * @param {Buffer} data Compressed data
  50580. * @param {Boolean} fin Specifies whether or not this is the last fragment
  50581. * @param {Function} callback Callback
  50582. * @public
  50583. */
  50584. decompress(data, fin, callback) {
  50585. zlibLimiter.add((done) => {
  50586. this._decompress(data, fin, (err, result) => {
  50587. done();
  50588. callback(err, result);
  50589. });
  50590. });
  50591. }
  50592. /**
  50593. * Compress data. Concurrency limited.
  50594. *
  50595. * @param {(Buffer|String)} data Data to compress
  50596. * @param {Boolean} fin Specifies whether or not this is the last fragment
  50597. * @param {Function} callback Callback
  50598. * @public
  50599. */
  50600. compress(data, fin, callback) {
  50601. zlibLimiter.add((done) => {
  50602. this._compress(data, fin, (err, result) => {
  50603. done();
  50604. callback(err, result);
  50605. });
  50606. });
  50607. }
  50608. /**
  50609. * Decompress data.
  50610. *
  50611. * @param {Buffer} data Compressed data
  50612. * @param {Boolean} fin Specifies whether or not this is the last fragment
  50613. * @param {Function} callback Callback
  50614. * @private
  50615. */
  50616. _decompress(data, fin, callback) {
  50617. const endpoint = this._isServer ? 'client' : 'server';
  50618. if (!this._inflate) {
  50619. const key = `${endpoint}_max_window_bits`;
  50620. const windowBits =
  50621. typeof this.params[key] !== 'number'
  50622. ? zlib.Z_DEFAULT_WINDOWBITS
  50623. : this.params[key];
  50624. this._inflate = zlib.createInflateRaw({
  50625. ...this._options.zlibInflateOptions,
  50626. windowBits
  50627. });
  50628. this._inflate[kPerMessageDeflate] = this;
  50629. this._inflate[kTotalLength] = 0;
  50630. this._inflate[kBuffers] = [];
  50631. this._inflate.on('error', inflateOnError);
  50632. this._inflate.on('data', inflateOnData);
  50633. }
  50634. this._inflate[kCallback] = callback;
  50635. this._inflate.write(data);
  50636. if (fin) this._inflate.write(TRAILER);
  50637. this._inflate.flush(() => {
  50638. const err = this._inflate[kError$1];
  50639. if (err) {
  50640. this._inflate.close();
  50641. this._inflate = null;
  50642. callback(err);
  50643. return;
  50644. }
  50645. const data = bufferUtil.concat(
  50646. this._inflate[kBuffers],
  50647. this._inflate[kTotalLength]
  50648. );
  50649. if (this._inflate._readableState.endEmitted) {
  50650. this._inflate.close();
  50651. this._inflate = null;
  50652. } else {
  50653. this._inflate[kTotalLength] = 0;
  50654. this._inflate[kBuffers] = [];
  50655. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  50656. this._inflate.reset();
  50657. }
  50658. }
  50659. callback(null, data);
  50660. });
  50661. }
  50662. /**
  50663. * Compress data.
  50664. *
  50665. * @param {(Buffer|String)} data Data to compress
  50666. * @param {Boolean} fin Specifies whether or not this is the last fragment
  50667. * @param {Function} callback Callback
  50668. * @private
  50669. */
  50670. _compress(data, fin, callback) {
  50671. const endpoint = this._isServer ? 'server' : 'client';
  50672. if (!this._deflate) {
  50673. const key = `${endpoint}_max_window_bits`;
  50674. const windowBits =
  50675. typeof this.params[key] !== 'number'
  50676. ? zlib.Z_DEFAULT_WINDOWBITS
  50677. : this.params[key];
  50678. this._deflate = zlib.createDeflateRaw({
  50679. ...this._options.zlibDeflateOptions,
  50680. windowBits
  50681. });
  50682. this._deflate[kTotalLength] = 0;
  50683. this._deflate[kBuffers] = [];
  50684. this._deflate.on('data', deflateOnData);
  50685. }
  50686. this._deflate[kCallback] = callback;
  50687. this._deflate.write(data);
  50688. this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
  50689. if (!this._deflate) {
  50690. //
  50691. // The deflate stream was closed while data was being processed.
  50692. //
  50693. return;
  50694. }
  50695. let data = bufferUtil.concat(
  50696. this._deflate[kBuffers],
  50697. this._deflate[kTotalLength]
  50698. );
  50699. if (fin) {
  50700. data = new FastBuffer$1(data.buffer, data.byteOffset, data.length - 4);
  50701. }
  50702. //
  50703. // Ensure that the callback will not be called again in
  50704. // `PerMessageDeflate#cleanup()`.
  50705. //
  50706. this._deflate[kCallback] = null;
  50707. this._deflate[kTotalLength] = 0;
  50708. this._deflate[kBuffers] = [];
  50709. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  50710. this._deflate.reset();
  50711. }
  50712. callback(null, data);
  50713. });
  50714. }
  50715. };
  50716. var permessageDeflate = PerMessageDeflate$4;
  50717. /**
  50718. * The listener of the `zlib.DeflateRaw` stream `'data'` event.
  50719. *
  50720. * @param {Buffer} chunk A chunk of data
  50721. * @private
  50722. */
  50723. function deflateOnData(chunk) {
  50724. this[kBuffers].push(chunk);
  50725. this[kTotalLength] += chunk.length;
  50726. }
  50727. /**
  50728. * The listener of the `zlib.InflateRaw` stream `'data'` event.
  50729. *
  50730. * @param {Buffer} chunk A chunk of data
  50731. * @private
  50732. */
  50733. function inflateOnData(chunk) {
  50734. this[kTotalLength] += chunk.length;
  50735. if (
  50736. this[kPerMessageDeflate]._maxPayload < 1 ||
  50737. this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
  50738. ) {
  50739. this[kBuffers].push(chunk);
  50740. return;
  50741. }
  50742. this[kError$1] = new RangeError('Max payload size exceeded');
  50743. this[kError$1].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
  50744. this[kError$1][kStatusCode$2] = 1009;
  50745. this.removeListener('data', inflateOnData);
  50746. this.reset();
  50747. }
  50748. /**
  50749. * The listener of the `zlib.InflateRaw` stream `'error'` event.
  50750. *
  50751. * @param {Error} err The emitted error
  50752. * @private
  50753. */
  50754. function inflateOnError(err) {
  50755. //
  50756. // There is no need to call `Zlib#close()` as the handle is automatically
  50757. // closed when an error is emitted.
  50758. //
  50759. this[kPerMessageDeflate]._inflate = null;
  50760. err[kStatusCode$2] = 1007;
  50761. this[kCallback](err);
  50762. }
  50763. var validation = {exports: {}};
  50764. const { isUtf8 } = require$$0$b;
  50765. //
  50766. // Allowed token characters:
  50767. //
  50768. // '!', '#', '$', '%', '&', ''', '*', '+', '-',
  50769. // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
  50770. //
  50771. // tokenChars[32] === 0 // ' '
  50772. // tokenChars[33] === 1 // '!'
  50773. // tokenChars[34] === 0 // '"'
  50774. // ...
  50775. //
  50776. // prettier-ignore
  50777. const tokenChars$2 = [
  50778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
  50779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
  50780. 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
  50781. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
  50782. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
  50783. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
  50784. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
  50785. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
  50786. ];
  50787. /**
  50788. * Checks if a status code is allowed in a close frame.
  50789. *
  50790. * @param {Number} code The status code
  50791. * @return {Boolean} `true` if the status code is valid, else `false`
  50792. * @public
  50793. */
  50794. function isValidStatusCode$2(code) {
  50795. return (
  50796. (code >= 1000 &&
  50797. code <= 1014 &&
  50798. code !== 1004 &&
  50799. code !== 1005 &&
  50800. code !== 1006) ||
  50801. (code >= 3000 && code <= 4999)
  50802. );
  50803. }
  50804. /**
  50805. * Checks if a given buffer contains only correct UTF-8.
  50806. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
  50807. * Markus Kuhn.
  50808. *
  50809. * @param {Buffer} buf The buffer to check
  50810. * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
  50811. * @public
  50812. */
  50813. function _isValidUTF8(buf) {
  50814. const len = buf.length;
  50815. let i = 0;
  50816. while (i < len) {
  50817. if ((buf[i] & 0x80) === 0) {
  50818. // 0xxxxxxx
  50819. i++;
  50820. } else if ((buf[i] & 0xe0) === 0xc0) {
  50821. // 110xxxxx 10xxxxxx
  50822. if (
  50823. i + 1 === len ||
  50824. (buf[i + 1] & 0xc0) !== 0x80 ||
  50825. (buf[i] & 0xfe) === 0xc0 // Overlong
  50826. ) {
  50827. return false;
  50828. }
  50829. i += 2;
  50830. } else if ((buf[i] & 0xf0) === 0xe0) {
  50831. // 1110xxxx 10xxxxxx 10xxxxxx
  50832. if (
  50833. i + 2 >= len ||
  50834. (buf[i + 1] & 0xc0) !== 0x80 ||
  50835. (buf[i + 2] & 0xc0) !== 0x80 ||
  50836. (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
  50837. (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
  50838. ) {
  50839. return false;
  50840. }
  50841. i += 3;
  50842. } else if ((buf[i] & 0xf8) === 0xf0) {
  50843. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  50844. if (
  50845. i + 3 >= len ||
  50846. (buf[i + 1] & 0xc0) !== 0x80 ||
  50847. (buf[i + 2] & 0xc0) !== 0x80 ||
  50848. (buf[i + 3] & 0xc0) !== 0x80 ||
  50849. (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
  50850. (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
  50851. buf[i] > 0xf4 // > U+10FFFF
  50852. ) {
  50853. return false;
  50854. }
  50855. i += 4;
  50856. } else {
  50857. return false;
  50858. }
  50859. }
  50860. return true;
  50861. }
  50862. validation.exports = {
  50863. isValidStatusCode: isValidStatusCode$2,
  50864. isValidUTF8: _isValidUTF8,
  50865. tokenChars: tokenChars$2
  50866. };
  50867. if (isUtf8) {
  50868. validation.exports.isValidUTF8 = function (buf) {
  50869. return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
  50870. };
  50871. } /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {
  50872. try {
  50873. const isValidUTF8 = require('utf-8-validate');
  50874. validation.exports.isValidUTF8 = function (buf) {
  50875. return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
  50876. };
  50877. } catch (e) {
  50878. // Continue regardless of the error.
  50879. }
  50880. }
  50881. var validationExports = validation.exports;
  50882. const { Writable: Writable$1 } = require$$0$7;
  50883. const PerMessageDeflate$3 = permessageDeflate;
  50884. const {
  50885. BINARY_TYPES: BINARY_TYPES$1,
  50886. EMPTY_BUFFER: EMPTY_BUFFER$2,
  50887. kStatusCode: kStatusCode$1,
  50888. kWebSocket: kWebSocket$2
  50889. } = constants;
  50890. const { concat, toArrayBuffer, unmask } = bufferUtilExports;
  50891. const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports;
  50892. const FastBuffer = Buffer[Symbol.species];
  50893. const GET_INFO = 0;
  50894. const GET_PAYLOAD_LENGTH_16 = 1;
  50895. const GET_PAYLOAD_LENGTH_64 = 2;
  50896. const GET_MASK = 3;
  50897. const GET_DATA = 4;
  50898. const INFLATING = 5;
  50899. /**
  50900. * HyBi Receiver implementation.
  50901. *
  50902. * @extends Writable
  50903. */
  50904. let Receiver$1 = class Receiver extends Writable$1 {
  50905. /**
  50906. * Creates a Receiver instance.
  50907. *
  50908. * @param {Object} [options] Options object
  50909. * @param {String} [options.binaryType=nodebuffer] The type for binary data
  50910. * @param {Object} [options.extensions] An object containing the negotiated
  50911. * extensions
  50912. * @param {Boolean} [options.isServer=false] Specifies whether to operate in
  50913. * client or server mode
  50914. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  50915. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  50916. * not to skip UTF-8 validation for text and close messages
  50917. */
  50918. constructor(options = {}) {
  50919. super();
  50920. this._binaryType = options.binaryType || BINARY_TYPES$1[0];
  50921. this._extensions = options.extensions || {};
  50922. this._isServer = !!options.isServer;
  50923. this._maxPayload = options.maxPayload | 0;
  50924. this._skipUTF8Validation = !!options.skipUTF8Validation;
  50925. this[kWebSocket$2] = undefined;
  50926. this._bufferedBytes = 0;
  50927. this._buffers = [];
  50928. this._compressed = false;
  50929. this._payloadLength = 0;
  50930. this._mask = undefined;
  50931. this._fragmented = 0;
  50932. this._masked = false;
  50933. this._fin = false;
  50934. this._opcode = 0;
  50935. this._totalPayloadLength = 0;
  50936. this._messageLength = 0;
  50937. this._fragments = [];
  50938. this._state = GET_INFO;
  50939. this._loop = false;
  50940. }
  50941. /**
  50942. * Implements `Writable.prototype._write()`.
  50943. *
  50944. * @param {Buffer} chunk The chunk of data to write
  50945. * @param {String} encoding The character encoding of `chunk`
  50946. * @param {Function} cb Callback
  50947. * @private
  50948. */
  50949. _write(chunk, encoding, cb) {
  50950. if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
  50951. this._bufferedBytes += chunk.length;
  50952. this._buffers.push(chunk);
  50953. this.startLoop(cb);
  50954. }
  50955. /**
  50956. * Consumes `n` bytes from the buffered data.
  50957. *
  50958. * @param {Number} n The number of bytes to consume
  50959. * @return {Buffer} The consumed bytes
  50960. * @private
  50961. */
  50962. consume(n) {
  50963. this._bufferedBytes -= n;
  50964. if (n === this._buffers[0].length) return this._buffers.shift();
  50965. if (n < this._buffers[0].length) {
  50966. const buf = this._buffers[0];
  50967. this._buffers[0] = new FastBuffer(
  50968. buf.buffer,
  50969. buf.byteOffset + n,
  50970. buf.length - n
  50971. );
  50972. return new FastBuffer(buf.buffer, buf.byteOffset, n);
  50973. }
  50974. const dst = Buffer.allocUnsafe(n);
  50975. do {
  50976. const buf = this._buffers[0];
  50977. const offset = dst.length - n;
  50978. if (n >= buf.length) {
  50979. dst.set(this._buffers.shift(), offset);
  50980. } else {
  50981. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
  50982. this._buffers[0] = new FastBuffer(
  50983. buf.buffer,
  50984. buf.byteOffset + n,
  50985. buf.length - n
  50986. );
  50987. }
  50988. n -= buf.length;
  50989. } while (n > 0);
  50990. return dst;
  50991. }
  50992. /**
  50993. * Starts the parsing loop.
  50994. *
  50995. * @param {Function} cb Callback
  50996. * @private
  50997. */
  50998. startLoop(cb) {
  50999. let err;
  51000. this._loop = true;
  51001. do {
  51002. switch (this._state) {
  51003. case GET_INFO:
  51004. err = this.getInfo();
  51005. break;
  51006. case GET_PAYLOAD_LENGTH_16:
  51007. err = this.getPayloadLength16();
  51008. break;
  51009. case GET_PAYLOAD_LENGTH_64:
  51010. err = this.getPayloadLength64();
  51011. break;
  51012. case GET_MASK:
  51013. this.getMask();
  51014. break;
  51015. case GET_DATA:
  51016. err = this.getData(cb);
  51017. break;
  51018. default:
  51019. // `INFLATING`
  51020. this._loop = false;
  51021. return;
  51022. }
  51023. } while (this._loop);
  51024. cb(err);
  51025. }
  51026. /**
  51027. * Reads the first two bytes of a frame.
  51028. *
  51029. * @return {(RangeError|undefined)} A possible error
  51030. * @private
  51031. */
  51032. getInfo() {
  51033. if (this._bufferedBytes < 2) {
  51034. this._loop = false;
  51035. return;
  51036. }
  51037. const buf = this.consume(2);
  51038. if ((buf[0] & 0x30) !== 0x00) {
  51039. this._loop = false;
  51040. return error(
  51041. RangeError,
  51042. 'RSV2 and RSV3 must be clear',
  51043. true,
  51044. 1002,
  51045. 'WS_ERR_UNEXPECTED_RSV_2_3'
  51046. );
  51047. }
  51048. const compressed = (buf[0] & 0x40) === 0x40;
  51049. if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
  51050. this._loop = false;
  51051. return error(
  51052. RangeError,
  51053. 'RSV1 must be clear',
  51054. true,
  51055. 1002,
  51056. 'WS_ERR_UNEXPECTED_RSV_1'
  51057. );
  51058. }
  51059. this._fin = (buf[0] & 0x80) === 0x80;
  51060. this._opcode = buf[0] & 0x0f;
  51061. this._payloadLength = buf[1] & 0x7f;
  51062. if (this._opcode === 0x00) {
  51063. if (compressed) {
  51064. this._loop = false;
  51065. return error(
  51066. RangeError,
  51067. 'RSV1 must be clear',
  51068. true,
  51069. 1002,
  51070. 'WS_ERR_UNEXPECTED_RSV_1'
  51071. );
  51072. }
  51073. if (!this._fragmented) {
  51074. this._loop = false;
  51075. return error(
  51076. RangeError,
  51077. 'invalid opcode 0',
  51078. true,
  51079. 1002,
  51080. 'WS_ERR_INVALID_OPCODE'
  51081. );
  51082. }
  51083. this._opcode = this._fragmented;
  51084. } else if (this._opcode === 0x01 || this._opcode === 0x02) {
  51085. if (this._fragmented) {
  51086. this._loop = false;
  51087. return error(
  51088. RangeError,
  51089. `invalid opcode ${this._opcode}`,
  51090. true,
  51091. 1002,
  51092. 'WS_ERR_INVALID_OPCODE'
  51093. );
  51094. }
  51095. this._compressed = compressed;
  51096. } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
  51097. if (!this._fin) {
  51098. this._loop = false;
  51099. return error(
  51100. RangeError,
  51101. 'FIN must be set',
  51102. true,
  51103. 1002,
  51104. 'WS_ERR_EXPECTED_FIN'
  51105. );
  51106. }
  51107. if (compressed) {
  51108. this._loop = false;
  51109. return error(
  51110. RangeError,
  51111. 'RSV1 must be clear',
  51112. true,
  51113. 1002,
  51114. 'WS_ERR_UNEXPECTED_RSV_1'
  51115. );
  51116. }
  51117. if (
  51118. this._payloadLength > 0x7d ||
  51119. (this._opcode === 0x08 && this._payloadLength === 1)
  51120. ) {
  51121. this._loop = false;
  51122. return error(
  51123. RangeError,
  51124. `invalid payload length ${this._payloadLength}`,
  51125. true,
  51126. 1002,
  51127. 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
  51128. );
  51129. }
  51130. } else {
  51131. this._loop = false;
  51132. return error(
  51133. RangeError,
  51134. `invalid opcode ${this._opcode}`,
  51135. true,
  51136. 1002,
  51137. 'WS_ERR_INVALID_OPCODE'
  51138. );
  51139. }
  51140. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  51141. this._masked = (buf[1] & 0x80) === 0x80;
  51142. if (this._isServer) {
  51143. if (!this._masked) {
  51144. this._loop = false;
  51145. return error(
  51146. RangeError,
  51147. 'MASK must be set',
  51148. true,
  51149. 1002,
  51150. 'WS_ERR_EXPECTED_MASK'
  51151. );
  51152. }
  51153. } else if (this._masked) {
  51154. this._loop = false;
  51155. return error(
  51156. RangeError,
  51157. 'MASK must be clear',
  51158. true,
  51159. 1002,
  51160. 'WS_ERR_UNEXPECTED_MASK'
  51161. );
  51162. }
  51163. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  51164. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  51165. else return this.haveLength();
  51166. }
  51167. /**
  51168. * Gets extended payload length (7+16).
  51169. *
  51170. * @return {(RangeError|undefined)} A possible error
  51171. * @private
  51172. */
  51173. getPayloadLength16() {
  51174. if (this._bufferedBytes < 2) {
  51175. this._loop = false;
  51176. return;
  51177. }
  51178. this._payloadLength = this.consume(2).readUInt16BE(0);
  51179. return this.haveLength();
  51180. }
  51181. /**
  51182. * Gets extended payload length (7+64).
  51183. *
  51184. * @return {(RangeError|undefined)} A possible error
  51185. * @private
  51186. */
  51187. getPayloadLength64() {
  51188. if (this._bufferedBytes < 8) {
  51189. this._loop = false;
  51190. return;
  51191. }
  51192. const buf = this.consume(8);
  51193. const num = buf.readUInt32BE(0);
  51194. //
  51195. // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
  51196. // if payload length is greater than this number.
  51197. //
  51198. if (num > Math.pow(2, 53 - 32) - 1) {
  51199. this._loop = false;
  51200. return error(
  51201. RangeError,
  51202. 'Unsupported WebSocket frame: payload length > 2^53 - 1',
  51203. false,
  51204. 1009,
  51205. 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
  51206. );
  51207. }
  51208. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  51209. return this.haveLength();
  51210. }
  51211. /**
  51212. * Payload length has been read.
  51213. *
  51214. * @return {(RangeError|undefined)} A possible error
  51215. * @private
  51216. */
  51217. haveLength() {
  51218. if (this._payloadLength && this._opcode < 0x08) {
  51219. this._totalPayloadLength += this._payloadLength;
  51220. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  51221. this._loop = false;
  51222. return error(
  51223. RangeError,
  51224. 'Max payload size exceeded',
  51225. false,
  51226. 1009,
  51227. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  51228. );
  51229. }
  51230. }
  51231. if (this._masked) this._state = GET_MASK;
  51232. else this._state = GET_DATA;
  51233. }
  51234. /**
  51235. * Reads mask bytes.
  51236. *
  51237. * @private
  51238. */
  51239. getMask() {
  51240. if (this._bufferedBytes < 4) {
  51241. this._loop = false;
  51242. return;
  51243. }
  51244. this._mask = this.consume(4);
  51245. this._state = GET_DATA;
  51246. }
  51247. /**
  51248. * Reads data bytes.
  51249. *
  51250. * @param {Function} cb Callback
  51251. * @return {(Error|RangeError|undefined)} A possible error
  51252. * @private
  51253. */
  51254. getData(cb) {
  51255. let data = EMPTY_BUFFER$2;
  51256. if (this._payloadLength) {
  51257. if (this._bufferedBytes < this._payloadLength) {
  51258. this._loop = false;
  51259. return;
  51260. }
  51261. data = this.consume(this._payloadLength);
  51262. if (
  51263. this._masked &&
  51264. (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
  51265. ) {
  51266. unmask(data, this._mask);
  51267. }
  51268. }
  51269. if (this._opcode > 0x07) return this.controlMessage(data);
  51270. if (this._compressed) {
  51271. this._state = INFLATING;
  51272. this.decompress(data, cb);
  51273. return;
  51274. }
  51275. if (data.length) {
  51276. //
  51277. // This message is not compressed so its length is the sum of the payload
  51278. // length of all fragments.
  51279. //
  51280. this._messageLength = this._totalPayloadLength;
  51281. this._fragments.push(data);
  51282. }
  51283. return this.dataMessage();
  51284. }
  51285. /**
  51286. * Decompresses data.
  51287. *
  51288. * @param {Buffer} data Compressed data
  51289. * @param {Function} cb Callback
  51290. * @private
  51291. */
  51292. decompress(data, cb) {
  51293. const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName];
  51294. perMessageDeflate.decompress(data, this._fin, (err, buf) => {
  51295. if (err) return cb(err);
  51296. if (buf.length) {
  51297. this._messageLength += buf.length;
  51298. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  51299. return cb(
  51300. error(
  51301. RangeError,
  51302. 'Max payload size exceeded',
  51303. false,
  51304. 1009,
  51305. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  51306. )
  51307. );
  51308. }
  51309. this._fragments.push(buf);
  51310. }
  51311. const er = this.dataMessage();
  51312. if (er) return cb(er);
  51313. this.startLoop(cb);
  51314. });
  51315. }
  51316. /**
  51317. * Handles a data message.
  51318. *
  51319. * @return {(Error|undefined)} A possible error
  51320. * @private
  51321. */
  51322. dataMessage() {
  51323. if (this._fin) {
  51324. const messageLength = this._messageLength;
  51325. const fragments = this._fragments;
  51326. this._totalPayloadLength = 0;
  51327. this._messageLength = 0;
  51328. this._fragmented = 0;
  51329. this._fragments = [];
  51330. if (this._opcode === 2) {
  51331. let data;
  51332. if (this._binaryType === 'nodebuffer') {
  51333. data = concat(fragments, messageLength);
  51334. } else if (this._binaryType === 'arraybuffer') {
  51335. data = toArrayBuffer(concat(fragments, messageLength));
  51336. } else {
  51337. data = fragments;
  51338. }
  51339. this.emit('message', data, true);
  51340. } else {
  51341. const buf = concat(fragments, messageLength);
  51342. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  51343. this._loop = false;
  51344. return error(
  51345. Error,
  51346. 'invalid UTF-8 sequence',
  51347. true,
  51348. 1007,
  51349. 'WS_ERR_INVALID_UTF8'
  51350. );
  51351. }
  51352. this.emit('message', buf, false);
  51353. }
  51354. }
  51355. this._state = GET_INFO;
  51356. }
  51357. /**
  51358. * Handles a control message.
  51359. *
  51360. * @param {Buffer} data Data to handle
  51361. * @return {(Error|RangeError|undefined)} A possible error
  51362. * @private
  51363. */
  51364. controlMessage(data) {
  51365. if (this._opcode === 0x08) {
  51366. this._loop = false;
  51367. if (data.length === 0) {
  51368. this.emit('conclude', 1005, EMPTY_BUFFER$2);
  51369. this.end();
  51370. } else {
  51371. const code = data.readUInt16BE(0);
  51372. if (!isValidStatusCode$1(code)) {
  51373. return error(
  51374. RangeError,
  51375. `invalid status code ${code}`,
  51376. true,
  51377. 1002,
  51378. 'WS_ERR_INVALID_CLOSE_CODE'
  51379. );
  51380. }
  51381. const buf = new FastBuffer(
  51382. data.buffer,
  51383. data.byteOffset + 2,
  51384. data.length - 2
  51385. );
  51386. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  51387. return error(
  51388. Error,
  51389. 'invalid UTF-8 sequence',
  51390. true,
  51391. 1007,
  51392. 'WS_ERR_INVALID_UTF8'
  51393. );
  51394. }
  51395. this.emit('conclude', code, buf);
  51396. this.end();
  51397. }
  51398. } else if (this._opcode === 0x09) {
  51399. this.emit('ping', data);
  51400. } else {
  51401. this.emit('pong', data);
  51402. }
  51403. this._state = GET_INFO;
  51404. }
  51405. };
  51406. var receiver = Receiver$1;
  51407. /**
  51408. * Builds an error object.
  51409. *
  51410. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  51411. * @param {String} message The error message
  51412. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  51413. * `message`
  51414. * @param {Number} statusCode The status code
  51415. * @param {String} errorCode The exposed error code
  51416. * @return {(Error|RangeError)} The error
  51417. * @private
  51418. */
  51419. function error(ErrorCtor, message, prefix, statusCode, errorCode) {
  51420. const err = new ErrorCtor(
  51421. prefix ? `Invalid WebSocket frame: ${message}` : message
  51422. );
  51423. Error.captureStackTrace(err, error);
  51424. err.code = errorCode;
  51425. err[kStatusCode$1] = statusCode;
  51426. return err;
  51427. }
  51428. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */
  51429. const { randomFillSync } = require$$5$1;
  51430. const PerMessageDeflate$2 = permessageDeflate;
  51431. const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants;
  51432. const { isValidStatusCode } = validationExports;
  51433. const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports;
  51434. const kByteLength = Symbol('kByteLength');
  51435. const maskBuffer = Buffer.alloc(4);
  51436. /**
  51437. * HyBi Sender implementation.
  51438. */
  51439. let Sender$1 = class Sender {
  51440. /**
  51441. * Creates a Sender instance.
  51442. *
  51443. * @param {(net.Socket|tls.Socket)} socket The connection socket
  51444. * @param {Object} [extensions] An object containing the negotiated extensions
  51445. * @param {Function} [generateMask] The function used to generate the masking
  51446. * key
  51447. */
  51448. constructor(socket, extensions, generateMask) {
  51449. this._extensions = extensions || {};
  51450. if (generateMask) {
  51451. this._generateMask = generateMask;
  51452. this._maskBuffer = Buffer.alloc(4);
  51453. }
  51454. this._socket = socket;
  51455. this._firstFragment = true;
  51456. this._compress = false;
  51457. this._bufferedBytes = 0;
  51458. this._deflating = false;
  51459. this._queue = [];
  51460. }
  51461. /**
  51462. * Frames a piece of data according to the HyBi WebSocket protocol.
  51463. *
  51464. * @param {(Buffer|String)} data The data to frame
  51465. * @param {Object} options Options object
  51466. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  51467. * FIN bit
  51468. * @param {Function} [options.generateMask] The function used to generate the
  51469. * masking key
  51470. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  51471. * `data`
  51472. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  51473. * key
  51474. * @param {Number} options.opcode The opcode
  51475. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  51476. * modified
  51477. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  51478. * RSV1 bit
  51479. * @return {(Buffer|String)[]} The framed data
  51480. * @public
  51481. */
  51482. static frame(data, options) {
  51483. let mask;
  51484. let merge = false;
  51485. let offset = 2;
  51486. let skipMasking = false;
  51487. if (options.mask) {
  51488. mask = options.maskBuffer || maskBuffer;
  51489. if (options.generateMask) {
  51490. options.generateMask(mask);
  51491. } else {
  51492. randomFillSync(mask, 0, 4);
  51493. }
  51494. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  51495. offset = 6;
  51496. }
  51497. let dataLength;
  51498. if (typeof data === 'string') {
  51499. if (
  51500. (!options.mask || skipMasking) &&
  51501. options[kByteLength] !== undefined
  51502. ) {
  51503. dataLength = options[kByteLength];
  51504. } else {
  51505. data = Buffer.from(data);
  51506. dataLength = data.length;
  51507. }
  51508. } else {
  51509. dataLength = data.length;
  51510. merge = options.mask && options.readOnly && !skipMasking;
  51511. }
  51512. let payloadLength = dataLength;
  51513. if (dataLength >= 65536) {
  51514. offset += 8;
  51515. payloadLength = 127;
  51516. } else if (dataLength > 125) {
  51517. offset += 2;
  51518. payloadLength = 126;
  51519. }
  51520. const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
  51521. target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
  51522. if (options.rsv1) target[0] |= 0x40;
  51523. target[1] = payloadLength;
  51524. if (payloadLength === 126) {
  51525. target.writeUInt16BE(dataLength, 2);
  51526. } else if (payloadLength === 127) {
  51527. target[2] = target[3] = 0;
  51528. target.writeUIntBE(dataLength, 4, 6);
  51529. }
  51530. if (!options.mask) return [target, data];
  51531. target[1] |= 0x80;
  51532. target[offset - 4] = mask[0];
  51533. target[offset - 3] = mask[1];
  51534. target[offset - 2] = mask[2];
  51535. target[offset - 1] = mask[3];
  51536. if (skipMasking) return [target, data];
  51537. if (merge) {
  51538. applyMask(data, mask, target, offset, dataLength);
  51539. return [target];
  51540. }
  51541. applyMask(data, mask, data, 0, dataLength);
  51542. return [target, data];
  51543. }
  51544. /**
  51545. * Sends a close message to the other peer.
  51546. *
  51547. * @param {Number} [code] The status code component of the body
  51548. * @param {(String|Buffer)} [data] The message component of the body
  51549. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  51550. * @param {Function} [cb] Callback
  51551. * @public
  51552. */
  51553. close(code, data, mask, cb) {
  51554. let buf;
  51555. if (code === undefined) {
  51556. buf = EMPTY_BUFFER$1;
  51557. } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
  51558. throw new TypeError('First argument must be a valid error code number');
  51559. } else if (data === undefined || !data.length) {
  51560. buf = Buffer.allocUnsafe(2);
  51561. buf.writeUInt16BE(code, 0);
  51562. } else {
  51563. const length = Buffer.byteLength(data);
  51564. if (length > 123) {
  51565. throw new RangeError('The message must not be greater than 123 bytes');
  51566. }
  51567. buf = Buffer.allocUnsafe(2 + length);
  51568. buf.writeUInt16BE(code, 0);
  51569. if (typeof data === 'string') {
  51570. buf.write(data, 2);
  51571. } else {
  51572. buf.set(data, 2);
  51573. }
  51574. }
  51575. const options = {
  51576. [kByteLength]: buf.length,
  51577. fin: true,
  51578. generateMask: this._generateMask,
  51579. mask,
  51580. maskBuffer: this._maskBuffer,
  51581. opcode: 0x08,
  51582. readOnly: false,
  51583. rsv1: false
  51584. };
  51585. if (this._deflating) {
  51586. this.enqueue([this.dispatch, buf, false, options, cb]);
  51587. } else {
  51588. this.sendFrame(Sender.frame(buf, options), cb);
  51589. }
  51590. }
  51591. /**
  51592. * Sends a ping message to the other peer.
  51593. *
  51594. * @param {*} data The message to send
  51595. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  51596. * @param {Function} [cb] Callback
  51597. * @public
  51598. */
  51599. ping(data, mask, cb) {
  51600. let byteLength;
  51601. let readOnly;
  51602. if (typeof data === 'string') {
  51603. byteLength = Buffer.byteLength(data);
  51604. readOnly = false;
  51605. } else {
  51606. data = toBuffer$1(data);
  51607. byteLength = data.length;
  51608. readOnly = toBuffer$1.readOnly;
  51609. }
  51610. if (byteLength > 125) {
  51611. throw new RangeError('The data size must not be greater than 125 bytes');
  51612. }
  51613. const options = {
  51614. [kByteLength]: byteLength,
  51615. fin: true,
  51616. generateMask: this._generateMask,
  51617. mask,
  51618. maskBuffer: this._maskBuffer,
  51619. opcode: 0x09,
  51620. readOnly,
  51621. rsv1: false
  51622. };
  51623. if (this._deflating) {
  51624. this.enqueue([this.dispatch, data, false, options, cb]);
  51625. } else {
  51626. this.sendFrame(Sender.frame(data, options), cb);
  51627. }
  51628. }
  51629. /**
  51630. * Sends a pong message to the other peer.
  51631. *
  51632. * @param {*} data The message to send
  51633. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  51634. * @param {Function} [cb] Callback
  51635. * @public
  51636. */
  51637. pong(data, mask, cb) {
  51638. let byteLength;
  51639. let readOnly;
  51640. if (typeof data === 'string') {
  51641. byteLength = Buffer.byteLength(data);
  51642. readOnly = false;
  51643. } else {
  51644. data = toBuffer$1(data);
  51645. byteLength = data.length;
  51646. readOnly = toBuffer$1.readOnly;
  51647. }
  51648. if (byteLength > 125) {
  51649. throw new RangeError('The data size must not be greater than 125 bytes');
  51650. }
  51651. const options = {
  51652. [kByteLength]: byteLength,
  51653. fin: true,
  51654. generateMask: this._generateMask,
  51655. mask,
  51656. maskBuffer: this._maskBuffer,
  51657. opcode: 0x0a,
  51658. readOnly,
  51659. rsv1: false
  51660. };
  51661. if (this._deflating) {
  51662. this.enqueue([this.dispatch, data, false, options, cb]);
  51663. } else {
  51664. this.sendFrame(Sender.frame(data, options), cb);
  51665. }
  51666. }
  51667. /**
  51668. * Sends a data message to the other peer.
  51669. *
  51670. * @param {*} data The message to send
  51671. * @param {Object} options Options object
  51672. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  51673. * or text
  51674. * @param {Boolean} [options.compress=false] Specifies whether or not to
  51675. * compress `data`
  51676. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  51677. * last one
  51678. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  51679. * `data`
  51680. * @param {Function} [cb] Callback
  51681. * @public
  51682. */
  51683. send(data, options, cb) {
  51684. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  51685. let opcode = options.binary ? 2 : 1;
  51686. let rsv1 = options.compress;
  51687. let byteLength;
  51688. let readOnly;
  51689. if (typeof data === 'string') {
  51690. byteLength = Buffer.byteLength(data);
  51691. readOnly = false;
  51692. } else {
  51693. data = toBuffer$1(data);
  51694. byteLength = data.length;
  51695. readOnly = toBuffer$1.readOnly;
  51696. }
  51697. if (this._firstFragment) {
  51698. this._firstFragment = false;
  51699. if (
  51700. rsv1 &&
  51701. perMessageDeflate &&
  51702. perMessageDeflate.params[
  51703. perMessageDeflate._isServer
  51704. ? 'server_no_context_takeover'
  51705. : 'client_no_context_takeover'
  51706. ]
  51707. ) {
  51708. rsv1 = byteLength >= perMessageDeflate._threshold;
  51709. }
  51710. this._compress = rsv1;
  51711. } else {
  51712. rsv1 = false;
  51713. opcode = 0;
  51714. }
  51715. if (options.fin) this._firstFragment = true;
  51716. if (perMessageDeflate) {
  51717. const opts = {
  51718. [kByteLength]: byteLength,
  51719. fin: options.fin,
  51720. generateMask: this._generateMask,
  51721. mask: options.mask,
  51722. maskBuffer: this._maskBuffer,
  51723. opcode,
  51724. readOnly,
  51725. rsv1
  51726. };
  51727. if (this._deflating) {
  51728. this.enqueue([this.dispatch, data, this._compress, opts, cb]);
  51729. } else {
  51730. this.dispatch(data, this._compress, opts, cb);
  51731. }
  51732. } else {
  51733. this.sendFrame(
  51734. Sender.frame(data, {
  51735. [kByteLength]: byteLength,
  51736. fin: options.fin,
  51737. generateMask: this._generateMask,
  51738. mask: options.mask,
  51739. maskBuffer: this._maskBuffer,
  51740. opcode,
  51741. readOnly,
  51742. rsv1: false
  51743. }),
  51744. cb
  51745. );
  51746. }
  51747. }
  51748. /**
  51749. * Dispatches a message.
  51750. *
  51751. * @param {(Buffer|String)} data The message to send
  51752. * @param {Boolean} [compress=false] Specifies whether or not to compress
  51753. * `data`
  51754. * @param {Object} options Options object
  51755. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  51756. * FIN bit
  51757. * @param {Function} [options.generateMask] The function used to generate the
  51758. * masking key
  51759. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  51760. * `data`
  51761. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  51762. * key
  51763. * @param {Number} options.opcode The opcode
  51764. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  51765. * modified
  51766. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  51767. * RSV1 bit
  51768. * @param {Function} [cb] Callback
  51769. * @private
  51770. */
  51771. dispatch(data, compress, options, cb) {
  51772. if (!compress) {
  51773. this.sendFrame(Sender.frame(data, options), cb);
  51774. return;
  51775. }
  51776. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  51777. this._bufferedBytes += options[kByteLength];
  51778. this._deflating = true;
  51779. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  51780. if (this._socket.destroyed) {
  51781. const err = new Error(
  51782. 'The socket was closed while data was being compressed'
  51783. );
  51784. if (typeof cb === 'function') cb(err);
  51785. for (let i = 0; i < this._queue.length; i++) {
  51786. const params = this._queue[i];
  51787. const callback = params[params.length - 1];
  51788. if (typeof callback === 'function') callback(err);
  51789. }
  51790. return;
  51791. }
  51792. this._bufferedBytes -= options[kByteLength];
  51793. this._deflating = false;
  51794. options.readOnly = false;
  51795. this.sendFrame(Sender.frame(buf, options), cb);
  51796. this.dequeue();
  51797. });
  51798. }
  51799. /**
  51800. * Executes queued send operations.
  51801. *
  51802. * @private
  51803. */
  51804. dequeue() {
  51805. while (!this._deflating && this._queue.length) {
  51806. const params = this._queue.shift();
  51807. this._bufferedBytes -= params[3][kByteLength];
  51808. Reflect.apply(params[0], this, params.slice(1));
  51809. }
  51810. }
  51811. /**
  51812. * Enqueues a send operation.
  51813. *
  51814. * @param {Array} params Send operation parameters.
  51815. * @private
  51816. */
  51817. enqueue(params) {
  51818. this._bufferedBytes += params[3][kByteLength];
  51819. this._queue.push(params);
  51820. }
  51821. /**
  51822. * Sends a frame.
  51823. *
  51824. * @param {Buffer[]} list The frame to send
  51825. * @param {Function} [cb] Callback
  51826. * @private
  51827. */
  51828. sendFrame(list, cb) {
  51829. if (list.length === 2) {
  51830. this._socket.cork();
  51831. this._socket.write(list[0]);
  51832. this._socket.write(list[1], cb);
  51833. this._socket.uncork();
  51834. } else {
  51835. this._socket.write(list[0], cb);
  51836. }
  51837. }
  51838. };
  51839. var sender = Sender$1;
  51840. const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants;
  51841. const kCode = Symbol('kCode');
  51842. const kData = Symbol('kData');
  51843. const kError = Symbol('kError');
  51844. const kMessage = Symbol('kMessage');
  51845. const kReason = Symbol('kReason');
  51846. const kTarget = Symbol('kTarget');
  51847. const kType = Symbol('kType');
  51848. const kWasClean = Symbol('kWasClean');
  51849. /**
  51850. * Class representing an event.
  51851. */
  51852. class Event {
  51853. /**
  51854. * Create a new `Event`.
  51855. *
  51856. * @param {String} type The name of the event
  51857. * @throws {TypeError} If the `type` argument is not specified
  51858. */
  51859. constructor(type) {
  51860. this[kTarget] = null;
  51861. this[kType] = type;
  51862. }
  51863. /**
  51864. * @type {*}
  51865. */
  51866. get target() {
  51867. return this[kTarget];
  51868. }
  51869. /**
  51870. * @type {String}
  51871. */
  51872. get type() {
  51873. return this[kType];
  51874. }
  51875. }
  51876. Object.defineProperty(Event.prototype, 'target', { enumerable: true });
  51877. Object.defineProperty(Event.prototype, 'type', { enumerable: true });
  51878. /**
  51879. * Class representing a close event.
  51880. *
  51881. * @extends Event
  51882. */
  51883. class CloseEvent extends Event {
  51884. /**
  51885. * Create a new `CloseEvent`.
  51886. *
  51887. * @param {String} type The name of the event
  51888. * @param {Object} [options] A dictionary object that allows for setting
  51889. * attributes via object members of the same name
  51890. * @param {Number} [options.code=0] The status code explaining why the
  51891. * connection was closed
  51892. * @param {String} [options.reason=''] A human-readable string explaining why
  51893. * the connection was closed
  51894. * @param {Boolean} [options.wasClean=false] Indicates whether or not the
  51895. * connection was cleanly closed
  51896. */
  51897. constructor(type, options = {}) {
  51898. super(type);
  51899. this[kCode] = options.code === undefined ? 0 : options.code;
  51900. this[kReason] = options.reason === undefined ? '' : options.reason;
  51901. this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
  51902. }
  51903. /**
  51904. * @type {Number}
  51905. */
  51906. get code() {
  51907. return this[kCode];
  51908. }
  51909. /**
  51910. * @type {String}
  51911. */
  51912. get reason() {
  51913. return this[kReason];
  51914. }
  51915. /**
  51916. * @type {Boolean}
  51917. */
  51918. get wasClean() {
  51919. return this[kWasClean];
  51920. }
  51921. }
  51922. Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
  51923. Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
  51924. Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
  51925. /**
  51926. * Class representing an error event.
  51927. *
  51928. * @extends Event
  51929. */
  51930. class ErrorEvent extends Event {
  51931. /**
  51932. * Create a new `ErrorEvent`.
  51933. *
  51934. * @param {String} type The name of the event
  51935. * @param {Object} [options] A dictionary object that allows for setting
  51936. * attributes via object members of the same name
  51937. * @param {*} [options.error=null] The error that generated this event
  51938. * @param {String} [options.message=''] The error message
  51939. */
  51940. constructor(type, options = {}) {
  51941. super(type);
  51942. this[kError] = options.error === undefined ? null : options.error;
  51943. this[kMessage] = options.message === undefined ? '' : options.message;
  51944. }
  51945. /**
  51946. * @type {*}
  51947. */
  51948. get error() {
  51949. return this[kError];
  51950. }
  51951. /**
  51952. * @type {String}
  51953. */
  51954. get message() {
  51955. return this[kMessage];
  51956. }
  51957. }
  51958. Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
  51959. Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
  51960. /**
  51961. * Class representing a message event.
  51962. *
  51963. * @extends Event
  51964. */
  51965. class MessageEvent extends Event {
  51966. /**
  51967. * Create a new `MessageEvent`.
  51968. *
  51969. * @param {String} type The name of the event
  51970. * @param {Object} [options] A dictionary object that allows for setting
  51971. * attributes via object members of the same name
  51972. * @param {*} [options.data=null] The message content
  51973. */
  51974. constructor(type, options = {}) {
  51975. super(type);
  51976. this[kData] = options.data === undefined ? null : options.data;
  51977. }
  51978. /**
  51979. * @type {*}
  51980. */
  51981. get data() {
  51982. return this[kData];
  51983. }
  51984. }
  51985. Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
  51986. /**
  51987. * This provides methods for emulating the `EventTarget` interface. It's not
  51988. * meant to be used directly.
  51989. *
  51990. * @mixin
  51991. */
  51992. const EventTarget = {
  51993. /**
  51994. * Register an event listener.
  51995. *
  51996. * @param {String} type A string representing the event type to listen for
  51997. * @param {(Function|Object)} handler The listener to add
  51998. * @param {Object} [options] An options object specifies characteristics about
  51999. * the event listener
  52000. * @param {Boolean} [options.once=false] A `Boolean` indicating that the
  52001. * listener should be invoked at most once after being added. If `true`,
  52002. * the listener would be automatically removed when invoked.
  52003. * @public
  52004. */
  52005. addEventListener(type, handler, options = {}) {
  52006. for (const listener of this.listeners(type)) {
  52007. if (
  52008. !options[kForOnEventAttribute$1] &&
  52009. listener[kListener$1] === handler &&
  52010. !listener[kForOnEventAttribute$1]
  52011. ) {
  52012. return;
  52013. }
  52014. }
  52015. let wrapper;
  52016. if (type === 'message') {
  52017. wrapper = function onMessage(data, isBinary) {
  52018. const event = new MessageEvent('message', {
  52019. data: isBinary ? data : data.toString()
  52020. });
  52021. event[kTarget] = this;
  52022. callListener(handler, this, event);
  52023. };
  52024. } else if (type === 'close') {
  52025. wrapper = function onClose(code, message) {
  52026. const event = new CloseEvent('close', {
  52027. code,
  52028. reason: message.toString(),
  52029. wasClean: this._closeFrameReceived && this._closeFrameSent
  52030. });
  52031. event[kTarget] = this;
  52032. callListener(handler, this, event);
  52033. };
  52034. } else if (type === 'error') {
  52035. wrapper = function onError(error) {
  52036. const event = new ErrorEvent('error', {
  52037. error,
  52038. message: error.message
  52039. });
  52040. event[kTarget] = this;
  52041. callListener(handler, this, event);
  52042. };
  52043. } else if (type === 'open') {
  52044. wrapper = function onOpen() {
  52045. const event = new Event('open');
  52046. event[kTarget] = this;
  52047. callListener(handler, this, event);
  52048. };
  52049. } else {
  52050. return;
  52051. }
  52052. wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
  52053. wrapper[kListener$1] = handler;
  52054. if (options.once) {
  52055. this.once(type, wrapper);
  52056. } else {
  52057. this.on(type, wrapper);
  52058. }
  52059. },
  52060. /**
  52061. * Remove an event listener.
  52062. *
  52063. * @param {String} type A string representing the event type to remove
  52064. * @param {(Function|Object)} handler The listener to remove
  52065. * @public
  52066. */
  52067. removeEventListener(type, handler) {
  52068. for (const listener of this.listeners(type)) {
  52069. if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) {
  52070. this.removeListener(type, listener);
  52071. break;
  52072. }
  52073. }
  52074. }
  52075. };
  52076. var eventTarget = {
  52077. CloseEvent,
  52078. ErrorEvent,
  52079. Event,
  52080. EventTarget,
  52081. MessageEvent
  52082. };
  52083. /**
  52084. * Call an event listener
  52085. *
  52086. * @param {(Function|Object)} listener The listener to call
  52087. * @param {*} thisArg The value to use as `this`` when calling the listener
  52088. * @param {Event} event The event to pass to the listener
  52089. * @private
  52090. */
  52091. function callListener(listener, thisArg, event) {
  52092. if (typeof listener === 'object' && listener.handleEvent) {
  52093. listener.handleEvent.call(listener, event);
  52094. } else {
  52095. listener.call(thisArg, event);
  52096. }
  52097. }
  52098. const { tokenChars: tokenChars$1 } = validationExports;
  52099. /**
  52100. * Adds an offer to the map of extension offers or a parameter to the map of
  52101. * parameters.
  52102. *
  52103. * @param {Object} dest The map of extension offers or parameters
  52104. * @param {String} name The extension or parameter name
  52105. * @param {(Object|Boolean|String)} elem The extension parameters or the
  52106. * parameter value
  52107. * @private
  52108. */
  52109. function push(dest, name, elem) {
  52110. if (dest[name] === undefined) dest[name] = [elem];
  52111. else dest[name].push(elem);
  52112. }
  52113. /**
  52114. * Parses the `Sec-WebSocket-Extensions` header into an object.
  52115. *
  52116. * @param {String} header The field value of the header
  52117. * @return {Object} The parsed object
  52118. * @public
  52119. */
  52120. function parse$4(header) {
  52121. const offers = Object.create(null);
  52122. let params = Object.create(null);
  52123. let mustUnescape = false;
  52124. let isEscaping = false;
  52125. let inQuotes = false;
  52126. let extensionName;
  52127. let paramName;
  52128. let start = -1;
  52129. let code = -1;
  52130. let end = -1;
  52131. let i = 0;
  52132. for (; i < header.length; i++) {
  52133. code = header.charCodeAt(i);
  52134. if (extensionName === undefined) {
  52135. if (end === -1 && tokenChars$1[code] === 1) {
  52136. if (start === -1) start = i;
  52137. } else if (
  52138. i !== 0 &&
  52139. (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
  52140. ) {
  52141. if (end === -1 && start !== -1) end = i;
  52142. } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
  52143. if (start === -1) {
  52144. throw new SyntaxError(`Unexpected character at index ${i}`);
  52145. }
  52146. if (end === -1) end = i;
  52147. const name = header.slice(start, end);
  52148. if (code === 0x2c) {
  52149. push(offers, name, params);
  52150. params = Object.create(null);
  52151. } else {
  52152. extensionName = name;
  52153. }
  52154. start = end = -1;
  52155. } else {
  52156. throw new SyntaxError(`Unexpected character at index ${i}`);
  52157. }
  52158. } else if (paramName === undefined) {
  52159. if (end === -1 && tokenChars$1[code] === 1) {
  52160. if (start === -1) start = i;
  52161. } else if (code === 0x20 || code === 0x09) {
  52162. if (end === -1 && start !== -1) end = i;
  52163. } else if (code === 0x3b || code === 0x2c) {
  52164. if (start === -1) {
  52165. throw new SyntaxError(`Unexpected character at index ${i}`);
  52166. }
  52167. if (end === -1) end = i;
  52168. push(params, header.slice(start, end), true);
  52169. if (code === 0x2c) {
  52170. push(offers, extensionName, params);
  52171. params = Object.create(null);
  52172. extensionName = undefined;
  52173. }
  52174. start = end = -1;
  52175. } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
  52176. paramName = header.slice(start, i);
  52177. start = end = -1;
  52178. } else {
  52179. throw new SyntaxError(`Unexpected character at index ${i}`);
  52180. }
  52181. } else {
  52182. //
  52183. // The value of a quoted-string after unescaping must conform to the
  52184. // token ABNF, so only token characters are valid.
  52185. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
  52186. //
  52187. if (isEscaping) {
  52188. if (tokenChars$1[code] !== 1) {
  52189. throw new SyntaxError(`Unexpected character at index ${i}`);
  52190. }
  52191. if (start === -1) start = i;
  52192. else if (!mustUnescape) mustUnescape = true;
  52193. isEscaping = false;
  52194. } else if (inQuotes) {
  52195. if (tokenChars$1[code] === 1) {
  52196. if (start === -1) start = i;
  52197. } else if (code === 0x22 /* '"' */ && start !== -1) {
  52198. inQuotes = false;
  52199. end = i;
  52200. } else if (code === 0x5c /* '\' */) {
  52201. isEscaping = true;
  52202. } else {
  52203. throw new SyntaxError(`Unexpected character at index ${i}`);
  52204. }
  52205. } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
  52206. inQuotes = true;
  52207. } else if (end === -1 && tokenChars$1[code] === 1) {
  52208. if (start === -1) start = i;
  52209. } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
  52210. if (end === -1) end = i;
  52211. } else if (code === 0x3b || code === 0x2c) {
  52212. if (start === -1) {
  52213. throw new SyntaxError(`Unexpected character at index ${i}`);
  52214. }
  52215. if (end === -1) end = i;
  52216. let value = header.slice(start, end);
  52217. if (mustUnescape) {
  52218. value = value.replace(/\\/g, '');
  52219. mustUnescape = false;
  52220. }
  52221. push(params, paramName, value);
  52222. if (code === 0x2c) {
  52223. push(offers, extensionName, params);
  52224. params = Object.create(null);
  52225. extensionName = undefined;
  52226. }
  52227. paramName = undefined;
  52228. start = end = -1;
  52229. } else {
  52230. throw new SyntaxError(`Unexpected character at index ${i}`);
  52231. }
  52232. }
  52233. }
  52234. if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
  52235. throw new SyntaxError('Unexpected end of input');
  52236. }
  52237. if (end === -1) end = i;
  52238. const token = header.slice(start, end);
  52239. if (extensionName === undefined) {
  52240. push(offers, token, params);
  52241. } else {
  52242. if (paramName === undefined) {
  52243. push(params, token, true);
  52244. } else if (mustUnescape) {
  52245. push(params, paramName, token.replace(/\\/g, ''));
  52246. } else {
  52247. push(params, paramName, token);
  52248. }
  52249. push(offers, extensionName, params);
  52250. }
  52251. return offers;
  52252. }
  52253. /**
  52254. * Builds the `Sec-WebSocket-Extensions` header field value.
  52255. *
  52256. * @param {Object} extensions The map of extensions and parameters to format
  52257. * @return {String} A string representing the given object
  52258. * @public
  52259. */
  52260. function format$1(extensions) {
  52261. return Object.keys(extensions)
  52262. .map((extension) => {
  52263. let configurations = extensions[extension];
  52264. if (!Array.isArray(configurations)) configurations = [configurations];
  52265. return configurations
  52266. .map((params) => {
  52267. return [extension]
  52268. .concat(
  52269. Object.keys(params).map((k) => {
  52270. let values = params[k];
  52271. if (!Array.isArray(values)) values = [values];
  52272. return values
  52273. .map((v) => (v === true ? k : `${k}=${v}`))
  52274. .join('; ');
  52275. })
  52276. )
  52277. .join('; ');
  52278. })
  52279. .join(', ');
  52280. })
  52281. .join(', ');
  52282. }
  52283. var extension$1 = { format: format$1, parse: parse$4 };
  52284. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */
  52285. const EventEmitter$1 = require$$0$5;
  52286. const https$2 = require$$1$2;
  52287. const http$3 = require$$1$1;
  52288. const net = require$$3$2;
  52289. const tls = require$$4;
  52290. const { randomBytes, createHash: createHash$1 } = require$$5$1;
  52291. const { URL: URL$2 } = require$$0$9;
  52292. const PerMessageDeflate$1 = permessageDeflate;
  52293. const Receiver = receiver;
  52294. const Sender = sender;
  52295. const {
  52296. BINARY_TYPES,
  52297. EMPTY_BUFFER,
  52298. GUID: GUID$1,
  52299. kForOnEventAttribute,
  52300. kListener,
  52301. kStatusCode,
  52302. kWebSocket: kWebSocket$1,
  52303. NOOP
  52304. } = constants;
  52305. const {
  52306. EventTarget: { addEventListener, removeEventListener }
  52307. } = eventTarget;
  52308. const { format, parse: parse$3 } = extension$1;
  52309. const { toBuffer } = bufferUtilExports;
  52310. const closeTimeout = 30 * 1000;
  52311. const kAborted = Symbol('kAborted');
  52312. const protocolVersions = [8, 13];
  52313. const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
  52314. const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
  52315. /**
  52316. * Class representing a WebSocket.
  52317. *
  52318. * @extends EventEmitter
  52319. */
  52320. let WebSocket$1 = class WebSocket extends EventEmitter$1 {
  52321. /**
  52322. * Create a new `WebSocket`.
  52323. *
  52324. * @param {(String|URL)} address The URL to which to connect
  52325. * @param {(String|String[])} [protocols] The subprotocols
  52326. * @param {Object} [options] Connection options
  52327. */
  52328. constructor(address, protocols, options) {
  52329. super();
  52330. this._binaryType = BINARY_TYPES[0];
  52331. this._closeCode = 1006;
  52332. this._closeFrameReceived = false;
  52333. this._closeFrameSent = false;
  52334. this._closeMessage = EMPTY_BUFFER;
  52335. this._closeTimer = null;
  52336. this._extensions = {};
  52337. this._paused = false;
  52338. this._protocol = '';
  52339. this._readyState = WebSocket.CONNECTING;
  52340. this._receiver = null;
  52341. this._sender = null;
  52342. this._socket = null;
  52343. if (address !== null) {
  52344. this._bufferedAmount = 0;
  52345. this._isServer = false;
  52346. this._redirects = 0;
  52347. if (protocols === undefined) {
  52348. protocols = [];
  52349. } else if (!Array.isArray(protocols)) {
  52350. if (typeof protocols === 'object' && protocols !== null) {
  52351. options = protocols;
  52352. protocols = [];
  52353. } else {
  52354. protocols = [protocols];
  52355. }
  52356. }
  52357. initAsClient(this, address, protocols, options);
  52358. } else {
  52359. this._isServer = true;
  52360. }
  52361. }
  52362. /**
  52363. * This deviates from the WHATWG interface since ws doesn't support the
  52364. * required default "blob" type (instead we define a custom "nodebuffer"
  52365. * type).
  52366. *
  52367. * @type {String}
  52368. */
  52369. get binaryType() {
  52370. return this._binaryType;
  52371. }
  52372. set binaryType(type) {
  52373. if (!BINARY_TYPES.includes(type)) return;
  52374. this._binaryType = type;
  52375. //
  52376. // Allow to change `binaryType` on the fly.
  52377. //
  52378. if (this._receiver) this._receiver._binaryType = type;
  52379. }
  52380. /**
  52381. * @type {Number}
  52382. */
  52383. get bufferedAmount() {
  52384. if (!this._socket) return this._bufferedAmount;
  52385. return this._socket._writableState.length + this._sender._bufferedBytes;
  52386. }
  52387. /**
  52388. * @type {String}
  52389. */
  52390. get extensions() {
  52391. return Object.keys(this._extensions).join();
  52392. }
  52393. /**
  52394. * @type {Boolean}
  52395. */
  52396. get isPaused() {
  52397. return this._paused;
  52398. }
  52399. /**
  52400. * @type {Function}
  52401. */
  52402. /* istanbul ignore next */
  52403. get onclose() {
  52404. return null;
  52405. }
  52406. /**
  52407. * @type {Function}
  52408. */
  52409. /* istanbul ignore next */
  52410. get onerror() {
  52411. return null;
  52412. }
  52413. /**
  52414. * @type {Function}
  52415. */
  52416. /* istanbul ignore next */
  52417. get onopen() {
  52418. return null;
  52419. }
  52420. /**
  52421. * @type {Function}
  52422. */
  52423. /* istanbul ignore next */
  52424. get onmessage() {
  52425. return null;
  52426. }
  52427. /**
  52428. * @type {String}
  52429. */
  52430. get protocol() {
  52431. return this._protocol;
  52432. }
  52433. /**
  52434. * @type {Number}
  52435. */
  52436. get readyState() {
  52437. return this._readyState;
  52438. }
  52439. /**
  52440. * @type {String}
  52441. */
  52442. get url() {
  52443. return this._url;
  52444. }
  52445. /**
  52446. * Set up the socket and the internal resources.
  52447. *
  52448. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  52449. * server and client
  52450. * @param {Buffer} head The first packet of the upgraded stream
  52451. * @param {Object} options Options object
  52452. * @param {Function} [options.generateMask] The function used to generate the
  52453. * masking key
  52454. * @param {Number} [options.maxPayload=0] The maximum allowed message size
  52455. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  52456. * not to skip UTF-8 validation for text and close messages
  52457. * @private
  52458. */
  52459. setSocket(socket, head, options) {
  52460. const receiver = new Receiver({
  52461. binaryType: this.binaryType,
  52462. extensions: this._extensions,
  52463. isServer: this._isServer,
  52464. maxPayload: options.maxPayload,
  52465. skipUTF8Validation: options.skipUTF8Validation
  52466. });
  52467. this._sender = new Sender(socket, this._extensions, options.generateMask);
  52468. this._receiver = receiver;
  52469. this._socket = socket;
  52470. receiver[kWebSocket$1] = this;
  52471. socket[kWebSocket$1] = this;
  52472. receiver.on('conclude', receiverOnConclude);
  52473. receiver.on('drain', receiverOnDrain);
  52474. receiver.on('error', receiverOnError);
  52475. receiver.on('message', receiverOnMessage);
  52476. receiver.on('ping', receiverOnPing);
  52477. receiver.on('pong', receiverOnPong);
  52478. socket.setTimeout(0);
  52479. socket.setNoDelay();
  52480. if (head.length > 0) socket.unshift(head);
  52481. socket.on('close', socketOnClose);
  52482. socket.on('data', socketOnData);
  52483. socket.on('end', socketOnEnd);
  52484. socket.on('error', socketOnError$1);
  52485. this._readyState = WebSocket.OPEN;
  52486. this.emit('open');
  52487. }
  52488. /**
  52489. * Emit the `'close'` event.
  52490. *
  52491. * @private
  52492. */
  52493. emitClose() {
  52494. if (!this._socket) {
  52495. this._readyState = WebSocket.CLOSED;
  52496. this.emit('close', this._closeCode, this._closeMessage);
  52497. return;
  52498. }
  52499. if (this._extensions[PerMessageDeflate$1.extensionName]) {
  52500. this._extensions[PerMessageDeflate$1.extensionName].cleanup();
  52501. }
  52502. this._receiver.removeAllListeners();
  52503. this._readyState = WebSocket.CLOSED;
  52504. this.emit('close', this._closeCode, this._closeMessage);
  52505. }
  52506. /**
  52507. * Start a closing handshake.
  52508. *
  52509. * +----------+ +-----------+ +----------+
  52510. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  52511. * | +----------+ +-----------+ +----------+ |
  52512. * +----------+ +-----------+ |
  52513. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  52514. * +----------+ +-----------+ |
  52515. * | | | +---+ |
  52516. * +------------------------+-->|fin| - - - -
  52517. * | +---+ | +---+
  52518. * - - - - -|fin|<---------------------+
  52519. * +---+
  52520. *
  52521. * @param {Number} [code] Status code explaining why the connection is closing
  52522. * @param {(String|Buffer)} [data] The reason why the connection is
  52523. * closing
  52524. * @public
  52525. */
  52526. close(code, data) {
  52527. if (this.readyState === WebSocket.CLOSED) return;
  52528. if (this.readyState === WebSocket.CONNECTING) {
  52529. const msg = 'WebSocket was closed before the connection was established';
  52530. abortHandshake$1(this, this._req, msg);
  52531. return;
  52532. }
  52533. if (this.readyState === WebSocket.CLOSING) {
  52534. if (
  52535. this._closeFrameSent &&
  52536. (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
  52537. ) {
  52538. this._socket.end();
  52539. }
  52540. return;
  52541. }
  52542. this._readyState = WebSocket.CLOSING;
  52543. this._sender.close(code, data, !this._isServer, (err) => {
  52544. //
  52545. // This error is handled by the `'error'` listener on the socket. We only
  52546. // want to know if the close frame has been sent here.
  52547. //
  52548. if (err) return;
  52549. this._closeFrameSent = true;
  52550. if (
  52551. this._closeFrameReceived ||
  52552. this._receiver._writableState.errorEmitted
  52553. ) {
  52554. this._socket.end();
  52555. }
  52556. });
  52557. //
  52558. // Specify a timeout for the closing handshake to complete.
  52559. //
  52560. this._closeTimer = setTimeout(
  52561. this._socket.destroy.bind(this._socket),
  52562. closeTimeout
  52563. );
  52564. }
  52565. /**
  52566. * Pause the socket.
  52567. *
  52568. * @public
  52569. */
  52570. pause() {
  52571. if (
  52572. this.readyState === WebSocket.CONNECTING ||
  52573. this.readyState === WebSocket.CLOSED
  52574. ) {
  52575. return;
  52576. }
  52577. this._paused = true;
  52578. this._socket.pause();
  52579. }
  52580. /**
  52581. * Send a ping.
  52582. *
  52583. * @param {*} [data] The data to send
  52584. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  52585. * @param {Function} [cb] Callback which is executed when the ping is sent
  52586. * @public
  52587. */
  52588. ping(data, mask, cb) {
  52589. if (this.readyState === WebSocket.CONNECTING) {
  52590. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  52591. }
  52592. if (typeof data === 'function') {
  52593. cb = data;
  52594. data = mask = undefined;
  52595. } else if (typeof mask === 'function') {
  52596. cb = mask;
  52597. mask = undefined;
  52598. }
  52599. if (typeof data === 'number') data = data.toString();
  52600. if (this.readyState !== WebSocket.OPEN) {
  52601. sendAfterClose(this, data, cb);
  52602. return;
  52603. }
  52604. if (mask === undefined) mask = !this._isServer;
  52605. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  52606. }
  52607. /**
  52608. * Send a pong.
  52609. *
  52610. * @param {*} [data] The data to send
  52611. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  52612. * @param {Function} [cb] Callback which is executed when the pong is sent
  52613. * @public
  52614. */
  52615. pong(data, mask, cb) {
  52616. if (this.readyState === WebSocket.CONNECTING) {
  52617. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  52618. }
  52619. if (typeof data === 'function') {
  52620. cb = data;
  52621. data = mask = undefined;
  52622. } else if (typeof mask === 'function') {
  52623. cb = mask;
  52624. mask = undefined;
  52625. }
  52626. if (typeof data === 'number') data = data.toString();
  52627. if (this.readyState !== WebSocket.OPEN) {
  52628. sendAfterClose(this, data, cb);
  52629. return;
  52630. }
  52631. if (mask === undefined) mask = !this._isServer;
  52632. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  52633. }
  52634. /**
  52635. * Resume the socket.
  52636. *
  52637. * @public
  52638. */
  52639. resume() {
  52640. if (
  52641. this.readyState === WebSocket.CONNECTING ||
  52642. this.readyState === WebSocket.CLOSED
  52643. ) {
  52644. return;
  52645. }
  52646. this._paused = false;
  52647. if (!this._receiver._writableState.needDrain) this._socket.resume();
  52648. }
  52649. /**
  52650. * Send a data message.
  52651. *
  52652. * @param {*} data The message to send
  52653. * @param {Object} [options] Options object
  52654. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  52655. * text
  52656. * @param {Boolean} [options.compress] Specifies whether or not to compress
  52657. * `data`
  52658. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  52659. * last one
  52660. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  52661. * @param {Function} [cb] Callback which is executed when data is written out
  52662. * @public
  52663. */
  52664. send(data, options, cb) {
  52665. if (this.readyState === WebSocket.CONNECTING) {
  52666. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  52667. }
  52668. if (typeof options === 'function') {
  52669. cb = options;
  52670. options = {};
  52671. }
  52672. if (typeof data === 'number') data = data.toString();
  52673. if (this.readyState !== WebSocket.OPEN) {
  52674. sendAfterClose(this, data, cb);
  52675. return;
  52676. }
  52677. const opts = {
  52678. binary: typeof data !== 'string',
  52679. mask: !this._isServer,
  52680. compress: true,
  52681. fin: true,
  52682. ...options
  52683. };
  52684. if (!this._extensions[PerMessageDeflate$1.extensionName]) {
  52685. opts.compress = false;
  52686. }
  52687. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  52688. }
  52689. /**
  52690. * Forcibly close the connection.
  52691. *
  52692. * @public
  52693. */
  52694. terminate() {
  52695. if (this.readyState === WebSocket.CLOSED) return;
  52696. if (this.readyState === WebSocket.CONNECTING) {
  52697. const msg = 'WebSocket was closed before the connection was established';
  52698. abortHandshake$1(this, this._req, msg);
  52699. return;
  52700. }
  52701. if (this._socket) {
  52702. this._readyState = WebSocket.CLOSING;
  52703. this._socket.destroy();
  52704. }
  52705. }
  52706. };
  52707. /**
  52708. * @constant {Number} CONNECTING
  52709. * @memberof WebSocket
  52710. */
  52711. Object.defineProperty(WebSocket$1, 'CONNECTING', {
  52712. enumerable: true,
  52713. value: readyStates.indexOf('CONNECTING')
  52714. });
  52715. /**
  52716. * @constant {Number} CONNECTING
  52717. * @memberof WebSocket.prototype
  52718. */
  52719. Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', {
  52720. enumerable: true,
  52721. value: readyStates.indexOf('CONNECTING')
  52722. });
  52723. /**
  52724. * @constant {Number} OPEN
  52725. * @memberof WebSocket
  52726. */
  52727. Object.defineProperty(WebSocket$1, 'OPEN', {
  52728. enumerable: true,
  52729. value: readyStates.indexOf('OPEN')
  52730. });
  52731. /**
  52732. * @constant {Number} OPEN
  52733. * @memberof WebSocket.prototype
  52734. */
  52735. Object.defineProperty(WebSocket$1.prototype, 'OPEN', {
  52736. enumerable: true,
  52737. value: readyStates.indexOf('OPEN')
  52738. });
  52739. /**
  52740. * @constant {Number} CLOSING
  52741. * @memberof WebSocket
  52742. */
  52743. Object.defineProperty(WebSocket$1, 'CLOSING', {
  52744. enumerable: true,
  52745. value: readyStates.indexOf('CLOSING')
  52746. });
  52747. /**
  52748. * @constant {Number} CLOSING
  52749. * @memberof WebSocket.prototype
  52750. */
  52751. Object.defineProperty(WebSocket$1.prototype, 'CLOSING', {
  52752. enumerable: true,
  52753. value: readyStates.indexOf('CLOSING')
  52754. });
  52755. /**
  52756. * @constant {Number} CLOSED
  52757. * @memberof WebSocket
  52758. */
  52759. Object.defineProperty(WebSocket$1, 'CLOSED', {
  52760. enumerable: true,
  52761. value: readyStates.indexOf('CLOSED')
  52762. });
  52763. /**
  52764. * @constant {Number} CLOSED
  52765. * @memberof WebSocket.prototype
  52766. */
  52767. Object.defineProperty(WebSocket$1.prototype, 'CLOSED', {
  52768. enumerable: true,
  52769. value: readyStates.indexOf('CLOSED')
  52770. });
  52771. [
  52772. 'binaryType',
  52773. 'bufferedAmount',
  52774. 'extensions',
  52775. 'isPaused',
  52776. 'protocol',
  52777. 'readyState',
  52778. 'url'
  52779. ].forEach((property) => {
  52780. Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true });
  52781. });
  52782. //
  52783. // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
  52784. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
  52785. //
  52786. ['open', 'error', 'close', 'message'].forEach((method) => {
  52787. Object.defineProperty(WebSocket$1.prototype, `on${method}`, {
  52788. enumerable: true,
  52789. get() {
  52790. for (const listener of this.listeners(method)) {
  52791. if (listener[kForOnEventAttribute]) return listener[kListener];
  52792. }
  52793. return null;
  52794. },
  52795. set(handler) {
  52796. for (const listener of this.listeners(method)) {
  52797. if (listener[kForOnEventAttribute]) {
  52798. this.removeListener(method, listener);
  52799. break;
  52800. }
  52801. }
  52802. if (typeof handler !== 'function') return;
  52803. this.addEventListener(method, handler, {
  52804. [kForOnEventAttribute]: true
  52805. });
  52806. }
  52807. });
  52808. });
  52809. WebSocket$1.prototype.addEventListener = addEventListener;
  52810. WebSocket$1.prototype.removeEventListener = removeEventListener;
  52811. var websocket = WebSocket$1;
  52812. /**
  52813. * Initialize a WebSocket client.
  52814. *
  52815. * @param {WebSocket} websocket The client to initialize
  52816. * @param {(String|URL)} address The URL to which to connect
  52817. * @param {Array} protocols The subprotocols
  52818. * @param {Object} [options] Connection options
  52819. * @param {Boolean} [options.followRedirects=false] Whether or not to follow
  52820. * redirects
  52821. * @param {Function} [options.generateMask] The function used to generate the
  52822. * masking key
  52823. * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
  52824. * handshake request
  52825. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  52826. * size
  52827. * @param {Number} [options.maxRedirects=10] The maximum number of redirects
  52828. * allowed
  52829. * @param {String} [options.origin] Value of the `Origin` or
  52830. * `Sec-WebSocket-Origin` header
  52831. * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
  52832. * permessage-deflate
  52833. * @param {Number} [options.protocolVersion=13] Value of the
  52834. * `Sec-WebSocket-Version` header
  52835. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  52836. * not to skip UTF-8 validation for text and close messages
  52837. * @private
  52838. */
  52839. function initAsClient(websocket, address, protocols, options) {
  52840. const opts = {
  52841. protocolVersion: protocolVersions[1],
  52842. maxPayload: 100 * 1024 * 1024,
  52843. skipUTF8Validation: false,
  52844. perMessageDeflate: true,
  52845. followRedirects: false,
  52846. maxRedirects: 10,
  52847. ...options,
  52848. createConnection: undefined,
  52849. socketPath: undefined,
  52850. hostname: undefined,
  52851. protocol: undefined,
  52852. timeout: undefined,
  52853. method: 'GET',
  52854. host: undefined,
  52855. path: undefined,
  52856. port: undefined
  52857. };
  52858. if (!protocolVersions.includes(opts.protocolVersion)) {
  52859. throw new RangeError(
  52860. `Unsupported protocol version: ${opts.protocolVersion} ` +
  52861. `(supported versions: ${protocolVersions.join(', ')})`
  52862. );
  52863. }
  52864. let parsedUrl;
  52865. if (address instanceof URL$2) {
  52866. parsedUrl = address;
  52867. websocket._url = address.href;
  52868. } else {
  52869. try {
  52870. parsedUrl = new URL$2(address);
  52871. } catch (e) {
  52872. throw new SyntaxError(`Invalid URL: ${address}`);
  52873. }
  52874. websocket._url = address;
  52875. }
  52876. const isSecure = parsedUrl.protocol === 'wss:';
  52877. const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
  52878. let invalidUrlMessage;
  52879. if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
  52880. invalidUrlMessage =
  52881. 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"';
  52882. } else if (isIpcUrl && !parsedUrl.pathname) {
  52883. invalidUrlMessage = "The URL's pathname is empty";
  52884. } else if (parsedUrl.hash) {
  52885. invalidUrlMessage = 'The URL contains a fragment identifier';
  52886. }
  52887. if (invalidUrlMessage) {
  52888. const err = new SyntaxError(invalidUrlMessage);
  52889. if (websocket._redirects === 0) {
  52890. throw err;
  52891. } else {
  52892. emitErrorAndClose(websocket, err);
  52893. return;
  52894. }
  52895. }
  52896. const defaultPort = isSecure ? 443 : 80;
  52897. const key = randomBytes(16).toString('base64');
  52898. const request = isSecure ? https$2.request : http$3.request;
  52899. const protocolSet = new Set();
  52900. let perMessageDeflate;
  52901. opts.createConnection = isSecure ? tlsConnect : netConnect;
  52902. opts.defaultPort = opts.defaultPort || defaultPort;
  52903. opts.port = parsedUrl.port || defaultPort;
  52904. opts.host = parsedUrl.hostname.startsWith('[')
  52905. ? parsedUrl.hostname.slice(1, -1)
  52906. : parsedUrl.hostname;
  52907. opts.headers = {
  52908. ...opts.headers,
  52909. 'Sec-WebSocket-Version': opts.protocolVersion,
  52910. 'Sec-WebSocket-Key': key,
  52911. Connection: 'Upgrade',
  52912. Upgrade: 'websocket'
  52913. };
  52914. opts.path = parsedUrl.pathname + parsedUrl.search;
  52915. opts.timeout = opts.handshakeTimeout;
  52916. if (opts.perMessageDeflate) {
  52917. perMessageDeflate = new PerMessageDeflate$1(
  52918. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  52919. false,
  52920. opts.maxPayload
  52921. );
  52922. opts.headers['Sec-WebSocket-Extensions'] = format({
  52923. [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
  52924. });
  52925. }
  52926. if (protocols.length) {
  52927. for (const protocol of protocols) {
  52928. if (
  52929. typeof protocol !== 'string' ||
  52930. !subprotocolRegex.test(protocol) ||
  52931. protocolSet.has(protocol)
  52932. ) {
  52933. throw new SyntaxError(
  52934. 'An invalid or duplicated subprotocol was specified'
  52935. );
  52936. }
  52937. protocolSet.add(protocol);
  52938. }
  52939. opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
  52940. }
  52941. if (opts.origin) {
  52942. if (opts.protocolVersion < 13) {
  52943. opts.headers['Sec-WebSocket-Origin'] = opts.origin;
  52944. } else {
  52945. opts.headers.Origin = opts.origin;
  52946. }
  52947. }
  52948. if (parsedUrl.username || parsedUrl.password) {
  52949. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  52950. }
  52951. if (isIpcUrl) {
  52952. const parts = opts.path.split(':');
  52953. opts.socketPath = parts[0];
  52954. opts.path = parts[1];
  52955. }
  52956. let req;
  52957. if (opts.followRedirects) {
  52958. if (websocket._redirects === 0) {
  52959. websocket._originalIpc = isIpcUrl;
  52960. websocket._originalSecure = isSecure;
  52961. websocket._originalHostOrSocketPath = isIpcUrl
  52962. ? opts.socketPath
  52963. : parsedUrl.host;
  52964. const headers = options && options.headers;
  52965. //
  52966. // Shallow copy the user provided options so that headers can be changed
  52967. // without mutating the original object.
  52968. //
  52969. options = { ...options, headers: {} };
  52970. if (headers) {
  52971. for (const [key, value] of Object.entries(headers)) {
  52972. options.headers[key.toLowerCase()] = value;
  52973. }
  52974. }
  52975. } else if (websocket.listenerCount('redirect') === 0) {
  52976. const isSameHost = isIpcUrl
  52977. ? websocket._originalIpc
  52978. ? opts.socketPath === websocket._originalHostOrSocketPath
  52979. : false
  52980. : websocket._originalIpc
  52981. ? false
  52982. : parsedUrl.host === websocket._originalHostOrSocketPath;
  52983. if (!isSameHost || (websocket._originalSecure && !isSecure)) {
  52984. //
  52985. // Match curl 7.77.0 behavior and drop the following headers. These
  52986. // headers are also dropped when following a redirect to a subdomain.
  52987. //
  52988. delete opts.headers.authorization;
  52989. delete opts.headers.cookie;
  52990. if (!isSameHost) delete opts.headers.host;
  52991. opts.auth = undefined;
  52992. }
  52993. }
  52994. //
  52995. // Match curl 7.77.0 behavior and make the first `Authorization` header win.
  52996. // If the `Authorization` header is set, then there is nothing to do as it
  52997. // will take precedence.
  52998. //
  52999. if (opts.auth && !options.headers.authorization) {
  53000. options.headers.authorization =
  53001. 'Basic ' + Buffer.from(opts.auth).toString('base64');
  53002. }
  53003. req = websocket._req = request(opts);
  53004. if (websocket._redirects) {
  53005. //
  53006. // Unlike what is done for the `'upgrade'` event, no early exit is
  53007. // triggered here if the user calls `websocket.close()` or
  53008. // `websocket.terminate()` from a listener of the `'redirect'` event. This
  53009. // is because the user can also call `request.destroy()` with an error
  53010. // before calling `websocket.close()` or `websocket.terminate()` and this
  53011. // would result in an error being emitted on the `request` object with no
  53012. // `'error'` event listeners attached.
  53013. //
  53014. websocket.emit('redirect', websocket.url, req);
  53015. }
  53016. } else {
  53017. req = websocket._req = request(opts);
  53018. }
  53019. if (opts.timeout) {
  53020. req.on('timeout', () => {
  53021. abortHandshake$1(websocket, req, 'Opening handshake has timed out');
  53022. });
  53023. }
  53024. req.on('error', (err) => {
  53025. if (req === null || req[kAborted]) return;
  53026. req = websocket._req = null;
  53027. emitErrorAndClose(websocket, err);
  53028. });
  53029. req.on('response', (res) => {
  53030. const location = res.headers.location;
  53031. const statusCode = res.statusCode;
  53032. if (
  53033. location &&
  53034. opts.followRedirects &&
  53035. statusCode >= 300 &&
  53036. statusCode < 400
  53037. ) {
  53038. if (++websocket._redirects > opts.maxRedirects) {
  53039. abortHandshake$1(websocket, req, 'Maximum redirects exceeded');
  53040. return;
  53041. }
  53042. req.abort();
  53043. let addr;
  53044. try {
  53045. addr = new URL$2(location, address);
  53046. } catch (e) {
  53047. const err = new SyntaxError(`Invalid URL: ${location}`);
  53048. emitErrorAndClose(websocket, err);
  53049. return;
  53050. }
  53051. initAsClient(websocket, addr, protocols, options);
  53052. } else if (!websocket.emit('unexpected-response', req, res)) {
  53053. abortHandshake$1(
  53054. websocket,
  53055. req,
  53056. `Unexpected server response: ${res.statusCode}`
  53057. );
  53058. }
  53059. });
  53060. req.on('upgrade', (res, socket, head) => {
  53061. websocket.emit('upgrade', res);
  53062. //
  53063. // The user may have closed the connection from a listener of the
  53064. // `'upgrade'` event.
  53065. //
  53066. if (websocket.readyState !== WebSocket$1.CONNECTING) return;
  53067. req = websocket._req = null;
  53068. if (res.headers.upgrade.toLowerCase() !== 'websocket') {
  53069. abortHandshake$1(websocket, socket, 'Invalid Upgrade header');
  53070. return;
  53071. }
  53072. const digest = createHash$1('sha1')
  53073. .update(key + GUID$1)
  53074. .digest('base64');
  53075. if (res.headers['sec-websocket-accept'] !== digest) {
  53076. abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  53077. return;
  53078. }
  53079. const serverProt = res.headers['sec-websocket-protocol'];
  53080. let protError;
  53081. if (serverProt !== undefined) {
  53082. if (!protocolSet.size) {
  53083. protError = 'Server sent a subprotocol but none was requested';
  53084. } else if (!protocolSet.has(serverProt)) {
  53085. protError = 'Server sent an invalid subprotocol';
  53086. }
  53087. } else if (protocolSet.size) {
  53088. protError = 'Server sent no subprotocol';
  53089. }
  53090. if (protError) {
  53091. abortHandshake$1(websocket, socket, protError);
  53092. return;
  53093. }
  53094. if (serverProt) websocket._protocol = serverProt;
  53095. const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
  53096. if (secWebSocketExtensions !== undefined) {
  53097. if (!perMessageDeflate) {
  53098. const message =
  53099. 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
  53100. 'was requested';
  53101. abortHandshake$1(websocket, socket, message);
  53102. return;
  53103. }
  53104. let extensions;
  53105. try {
  53106. extensions = parse$3(secWebSocketExtensions);
  53107. } catch (err) {
  53108. const message = 'Invalid Sec-WebSocket-Extensions header';
  53109. abortHandshake$1(websocket, socket, message);
  53110. return;
  53111. }
  53112. const extensionNames = Object.keys(extensions);
  53113. if (
  53114. extensionNames.length !== 1 ||
  53115. extensionNames[0] !== PerMessageDeflate$1.extensionName
  53116. ) {
  53117. const message = 'Server indicated an extension that was not requested';
  53118. abortHandshake$1(websocket, socket, message);
  53119. return;
  53120. }
  53121. try {
  53122. perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]);
  53123. } catch (err) {
  53124. const message = 'Invalid Sec-WebSocket-Extensions header';
  53125. abortHandshake$1(websocket, socket, message);
  53126. return;
  53127. }
  53128. websocket._extensions[PerMessageDeflate$1.extensionName] =
  53129. perMessageDeflate;
  53130. }
  53131. websocket.setSocket(socket, head, {
  53132. generateMask: opts.generateMask,
  53133. maxPayload: opts.maxPayload,
  53134. skipUTF8Validation: opts.skipUTF8Validation
  53135. });
  53136. });
  53137. if (opts.finishRequest) {
  53138. opts.finishRequest(req, websocket);
  53139. } else {
  53140. req.end();
  53141. }
  53142. }
  53143. /**
  53144. * Emit the `'error'` and `'close'` events.
  53145. *
  53146. * @param {WebSocket} websocket The WebSocket instance
  53147. * @param {Error} The error to emit
  53148. * @private
  53149. */
  53150. function emitErrorAndClose(websocket, err) {
  53151. websocket._readyState = WebSocket$1.CLOSING;
  53152. websocket.emit('error', err);
  53153. websocket.emitClose();
  53154. }
  53155. /**
  53156. * Create a `net.Socket` and initiate a connection.
  53157. *
  53158. * @param {Object} options Connection options
  53159. * @return {net.Socket} The newly created socket used to start the connection
  53160. * @private
  53161. */
  53162. function netConnect(options) {
  53163. options.path = options.socketPath;
  53164. return net.connect(options);
  53165. }
  53166. /**
  53167. * Create a `tls.TLSSocket` and initiate a connection.
  53168. *
  53169. * @param {Object} options Connection options
  53170. * @return {tls.TLSSocket} The newly created socket used to start the connection
  53171. * @private
  53172. */
  53173. function tlsConnect(options) {
  53174. options.path = undefined;
  53175. if (!options.servername && options.servername !== '') {
  53176. options.servername = net.isIP(options.host) ? '' : options.host;
  53177. }
  53178. return tls.connect(options);
  53179. }
  53180. /**
  53181. * Abort the handshake and emit an error.
  53182. *
  53183. * @param {WebSocket} websocket The WebSocket instance
  53184. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  53185. * abort or the socket to destroy
  53186. * @param {String} message The error message
  53187. * @private
  53188. */
  53189. function abortHandshake$1(websocket, stream, message) {
  53190. websocket._readyState = WebSocket$1.CLOSING;
  53191. const err = new Error(message);
  53192. Error.captureStackTrace(err, abortHandshake$1);
  53193. if (stream.setHeader) {
  53194. stream[kAborted] = true;
  53195. stream.abort();
  53196. if (stream.socket && !stream.socket.destroyed) {
  53197. //
  53198. // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
  53199. // called after the request completed. See
  53200. // https://github.com/websockets/ws/issues/1869.
  53201. //
  53202. stream.socket.destroy();
  53203. }
  53204. process.nextTick(emitErrorAndClose, websocket, err);
  53205. } else {
  53206. stream.destroy(err);
  53207. stream.once('error', websocket.emit.bind(websocket, 'error'));
  53208. stream.once('close', websocket.emitClose.bind(websocket));
  53209. }
  53210. }
  53211. /**
  53212. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  53213. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  53214. *
  53215. * @param {WebSocket} websocket The WebSocket instance
  53216. * @param {*} [data] The data to send
  53217. * @param {Function} [cb] Callback
  53218. * @private
  53219. */
  53220. function sendAfterClose(websocket, data, cb) {
  53221. if (data) {
  53222. const length = toBuffer(data).length;
  53223. //
  53224. // The `_bufferedAmount` property is used only when the peer is a client and
  53225. // the opening handshake fails. Under these circumstances, in fact, the
  53226. // `setSocket()` method is not called, so the `_socket` and `_sender`
  53227. // properties are set to `null`.
  53228. //
  53229. if (websocket._socket) websocket._sender._bufferedBytes += length;
  53230. else websocket._bufferedAmount += length;
  53231. }
  53232. if (cb) {
  53233. const err = new Error(
  53234. `WebSocket is not open: readyState ${websocket.readyState} ` +
  53235. `(${readyStates[websocket.readyState]})`
  53236. );
  53237. process.nextTick(cb, err);
  53238. }
  53239. }
  53240. /**
  53241. * The listener of the `Receiver` `'conclude'` event.
  53242. *
  53243. * @param {Number} code The status code
  53244. * @param {Buffer} reason The reason for closing
  53245. * @private
  53246. */
  53247. function receiverOnConclude(code, reason) {
  53248. const websocket = this[kWebSocket$1];
  53249. websocket._closeFrameReceived = true;
  53250. websocket._closeMessage = reason;
  53251. websocket._closeCode = code;
  53252. if (websocket._socket[kWebSocket$1] === undefined) return;
  53253. websocket._socket.removeListener('data', socketOnData);
  53254. process.nextTick(resume, websocket._socket);
  53255. if (code === 1005) websocket.close();
  53256. else websocket.close(code, reason);
  53257. }
  53258. /**
  53259. * The listener of the `Receiver` `'drain'` event.
  53260. *
  53261. * @private
  53262. */
  53263. function receiverOnDrain() {
  53264. const websocket = this[kWebSocket$1];
  53265. if (!websocket.isPaused) websocket._socket.resume();
  53266. }
  53267. /**
  53268. * The listener of the `Receiver` `'error'` event.
  53269. *
  53270. * @param {(RangeError|Error)} err The emitted error
  53271. * @private
  53272. */
  53273. function receiverOnError(err) {
  53274. const websocket = this[kWebSocket$1];
  53275. if (websocket._socket[kWebSocket$1] !== undefined) {
  53276. websocket._socket.removeListener('data', socketOnData);
  53277. //
  53278. // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
  53279. // https://github.com/websockets/ws/issues/1940.
  53280. //
  53281. process.nextTick(resume, websocket._socket);
  53282. websocket.close(err[kStatusCode]);
  53283. }
  53284. websocket.emit('error', err);
  53285. }
  53286. /**
  53287. * The listener of the `Receiver` `'finish'` event.
  53288. *
  53289. * @private
  53290. */
  53291. function receiverOnFinish() {
  53292. this[kWebSocket$1].emitClose();
  53293. }
  53294. /**
  53295. * The listener of the `Receiver` `'message'` event.
  53296. *
  53297. * @param {Buffer|ArrayBuffer|Buffer[])} data The message
  53298. * @param {Boolean} isBinary Specifies whether the message is binary or not
  53299. * @private
  53300. */
  53301. function receiverOnMessage(data, isBinary) {
  53302. this[kWebSocket$1].emit('message', data, isBinary);
  53303. }
  53304. /**
  53305. * The listener of the `Receiver` `'ping'` event.
  53306. *
  53307. * @param {Buffer} data The data included in the ping frame
  53308. * @private
  53309. */
  53310. function receiverOnPing(data) {
  53311. const websocket = this[kWebSocket$1];
  53312. websocket.pong(data, !websocket._isServer, NOOP);
  53313. websocket.emit('ping', data);
  53314. }
  53315. /**
  53316. * The listener of the `Receiver` `'pong'` event.
  53317. *
  53318. * @param {Buffer} data The data included in the pong frame
  53319. * @private
  53320. */
  53321. function receiverOnPong(data) {
  53322. this[kWebSocket$1].emit('pong', data);
  53323. }
  53324. /**
  53325. * Resume a readable stream
  53326. *
  53327. * @param {Readable} stream The readable stream
  53328. * @private
  53329. */
  53330. function resume(stream) {
  53331. stream.resume();
  53332. }
  53333. /**
  53334. * The listener of the `net.Socket` `'close'` event.
  53335. *
  53336. * @private
  53337. */
  53338. function socketOnClose() {
  53339. const websocket = this[kWebSocket$1];
  53340. this.removeListener('close', socketOnClose);
  53341. this.removeListener('data', socketOnData);
  53342. this.removeListener('end', socketOnEnd);
  53343. websocket._readyState = WebSocket$1.CLOSING;
  53344. let chunk;
  53345. //
  53346. // The close frame might not have been received or the `'end'` event emitted,
  53347. // for example, if the socket was destroyed due to an error. Ensure that the
  53348. // `receiver` stream is closed after writing any remaining buffered data to
  53349. // it. If the readable side of the socket is in flowing mode then there is no
  53350. // buffered data as everything has been already written and `readable.read()`
  53351. // will return `null`. If instead, the socket is paused, any possible buffered
  53352. // data will be read as a single chunk.
  53353. //
  53354. if (
  53355. !this._readableState.endEmitted &&
  53356. !websocket._closeFrameReceived &&
  53357. !websocket._receiver._writableState.errorEmitted &&
  53358. (chunk = websocket._socket.read()) !== null
  53359. ) {
  53360. websocket._receiver.write(chunk);
  53361. }
  53362. websocket._receiver.end();
  53363. this[kWebSocket$1] = undefined;
  53364. clearTimeout(websocket._closeTimer);
  53365. if (
  53366. websocket._receiver._writableState.finished ||
  53367. websocket._receiver._writableState.errorEmitted
  53368. ) {
  53369. websocket.emitClose();
  53370. } else {
  53371. websocket._receiver.on('error', receiverOnFinish);
  53372. websocket._receiver.on('finish', receiverOnFinish);
  53373. }
  53374. }
  53375. /**
  53376. * The listener of the `net.Socket` `'data'` event.
  53377. *
  53378. * @param {Buffer} chunk A chunk of data
  53379. * @private
  53380. */
  53381. function socketOnData(chunk) {
  53382. if (!this[kWebSocket$1]._receiver.write(chunk)) {
  53383. this.pause();
  53384. }
  53385. }
  53386. /**
  53387. * The listener of the `net.Socket` `'end'` event.
  53388. *
  53389. * @private
  53390. */
  53391. function socketOnEnd() {
  53392. const websocket = this[kWebSocket$1];
  53393. websocket._readyState = WebSocket$1.CLOSING;
  53394. websocket._receiver.end();
  53395. this.end();
  53396. }
  53397. /**
  53398. * The listener of the `net.Socket` `'error'` event.
  53399. *
  53400. * @private
  53401. */
  53402. function socketOnError$1() {
  53403. const websocket = this[kWebSocket$1];
  53404. this.removeListener('error', socketOnError$1);
  53405. this.on('error', NOOP);
  53406. if (websocket) {
  53407. websocket._readyState = WebSocket$1.CLOSING;
  53408. this.destroy();
  53409. }
  53410. }
  53411. const { tokenChars } = validationExports;
  53412. /**
  53413. * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
  53414. *
  53415. * @param {String} header The field value of the header
  53416. * @return {Set} The subprotocol names
  53417. * @public
  53418. */
  53419. function parse$2(header) {
  53420. const protocols = new Set();
  53421. let start = -1;
  53422. let end = -1;
  53423. let i = 0;
  53424. for (i; i < header.length; i++) {
  53425. const code = header.charCodeAt(i);
  53426. if (end === -1 && tokenChars[code] === 1) {
  53427. if (start === -1) start = i;
  53428. } else if (
  53429. i !== 0 &&
  53430. (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
  53431. ) {
  53432. if (end === -1 && start !== -1) end = i;
  53433. } else if (code === 0x2c /* ',' */) {
  53434. if (start === -1) {
  53435. throw new SyntaxError(`Unexpected character at index ${i}`);
  53436. }
  53437. if (end === -1) end = i;
  53438. const protocol = header.slice(start, end);
  53439. if (protocols.has(protocol)) {
  53440. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  53441. }
  53442. protocols.add(protocol);
  53443. start = end = -1;
  53444. } else {
  53445. throw new SyntaxError(`Unexpected character at index ${i}`);
  53446. }
  53447. }
  53448. if (start === -1 || end !== -1) {
  53449. throw new SyntaxError('Unexpected end of input');
  53450. }
  53451. const protocol = header.slice(start, i);
  53452. if (protocols.has(protocol)) {
  53453. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  53454. }
  53455. protocols.add(protocol);
  53456. return protocols;
  53457. }
  53458. var subprotocol$1 = { parse: parse$2 };
  53459. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */
  53460. const EventEmitter = require$$0$5;
  53461. const http$2 = require$$1$1;
  53462. const { createHash } = require$$5$1;
  53463. const extension = extension$1;
  53464. const PerMessageDeflate = permessageDeflate;
  53465. const subprotocol = subprotocol$1;
  53466. const WebSocket = websocket;
  53467. const { GUID, kWebSocket } = constants;
  53468. const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  53469. const RUNNING = 0;
  53470. const CLOSING = 1;
  53471. const CLOSED = 2;
  53472. /**
  53473. * Class representing a WebSocket server.
  53474. *
  53475. * @extends EventEmitter
  53476. */
  53477. class WebSocketServer extends EventEmitter {
  53478. /**
  53479. * Create a `WebSocketServer` instance.
  53480. *
  53481. * @param {Object} options Configuration options
  53482. * @param {Number} [options.backlog=511] The maximum length of the queue of
  53483. * pending connections
  53484. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  53485. * track clients
  53486. * @param {Function} [options.handleProtocols] A hook to handle protocols
  53487. * @param {String} [options.host] The hostname where to bind the server
  53488. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  53489. * size
  53490. * @param {Boolean} [options.noServer=false] Enable no server mode
  53491. * @param {String} [options.path] Accept only connections matching this path
  53492. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  53493. * permessage-deflate
  53494. * @param {Number} [options.port] The port where to bind the server
  53495. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  53496. * server to use
  53497. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  53498. * not to skip UTF-8 validation for text and close messages
  53499. * @param {Function} [options.verifyClient] A hook to reject connections
  53500. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  53501. * class to use. It must be the `WebSocket` class or class that extends it
  53502. * @param {Function} [callback] A listener for the `listening` event
  53503. */
  53504. constructor(options, callback) {
  53505. super();
  53506. options = {
  53507. maxPayload: 100 * 1024 * 1024,
  53508. skipUTF8Validation: false,
  53509. perMessageDeflate: false,
  53510. handleProtocols: null,
  53511. clientTracking: true,
  53512. verifyClient: null,
  53513. noServer: false,
  53514. backlog: null, // use default (511 as implemented in net.js)
  53515. server: null,
  53516. host: null,
  53517. path: null,
  53518. port: null,
  53519. WebSocket,
  53520. ...options
  53521. };
  53522. if (
  53523. (options.port == null && !options.server && !options.noServer) ||
  53524. (options.port != null && (options.server || options.noServer)) ||
  53525. (options.server && options.noServer)
  53526. ) {
  53527. throw new TypeError(
  53528. 'One and only one of the "port", "server", or "noServer" options ' +
  53529. 'must be specified'
  53530. );
  53531. }
  53532. if (options.port != null) {
  53533. this._server = http$2.createServer((req, res) => {
  53534. const body = http$2.STATUS_CODES[426];
  53535. res.writeHead(426, {
  53536. 'Content-Length': body.length,
  53537. 'Content-Type': 'text/plain'
  53538. });
  53539. res.end(body);
  53540. });
  53541. this._server.listen(
  53542. options.port,
  53543. options.host,
  53544. options.backlog,
  53545. callback
  53546. );
  53547. } else if (options.server) {
  53548. this._server = options.server;
  53549. }
  53550. if (this._server) {
  53551. const emitConnection = this.emit.bind(this, 'connection');
  53552. this._removeListeners = addListeners(this._server, {
  53553. listening: this.emit.bind(this, 'listening'),
  53554. error: this.emit.bind(this, 'error'),
  53555. upgrade: (req, socket, head) => {
  53556. this.handleUpgrade(req, socket, head, emitConnection);
  53557. }
  53558. });
  53559. }
  53560. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  53561. if (options.clientTracking) {
  53562. this.clients = new Set();
  53563. this._shouldEmitClose = false;
  53564. }
  53565. this.options = options;
  53566. this._state = RUNNING;
  53567. }
  53568. /**
  53569. * Returns the bound address, the address family name, and port of the server
  53570. * as reported by the operating system if listening on an IP socket.
  53571. * If the server is listening on a pipe or UNIX domain socket, the name is
  53572. * returned as a string.
  53573. *
  53574. * @return {(Object|String|null)} The address of the server
  53575. * @public
  53576. */
  53577. address() {
  53578. if (this.options.noServer) {
  53579. throw new Error('The server is operating in "noServer" mode');
  53580. }
  53581. if (!this._server) return null;
  53582. return this._server.address();
  53583. }
  53584. /**
  53585. * Stop the server from accepting new connections and emit the `'close'` event
  53586. * when all existing connections are closed.
  53587. *
  53588. * @param {Function} [cb] A one-time listener for the `'close'` event
  53589. * @public
  53590. */
  53591. close(cb) {
  53592. if (this._state === CLOSED) {
  53593. if (cb) {
  53594. this.once('close', () => {
  53595. cb(new Error('The server is not running'));
  53596. });
  53597. }
  53598. process.nextTick(emitClose, this);
  53599. return;
  53600. }
  53601. if (cb) this.once('close', cb);
  53602. if (this._state === CLOSING) return;
  53603. this._state = CLOSING;
  53604. if (this.options.noServer || this.options.server) {
  53605. if (this._server) {
  53606. this._removeListeners();
  53607. this._removeListeners = this._server = null;
  53608. }
  53609. if (this.clients) {
  53610. if (!this.clients.size) {
  53611. process.nextTick(emitClose, this);
  53612. } else {
  53613. this._shouldEmitClose = true;
  53614. }
  53615. } else {
  53616. process.nextTick(emitClose, this);
  53617. }
  53618. } else {
  53619. const server = this._server;
  53620. this._removeListeners();
  53621. this._removeListeners = this._server = null;
  53622. //
  53623. // The HTTP/S server was created internally. Close it, and rely on its
  53624. // `'close'` event.
  53625. //
  53626. server.close(() => {
  53627. emitClose(this);
  53628. });
  53629. }
  53630. }
  53631. /**
  53632. * See if a given request should be handled by this server instance.
  53633. *
  53634. * @param {http.IncomingMessage} req Request object to inspect
  53635. * @return {Boolean} `true` if the request is valid, else `false`
  53636. * @public
  53637. */
  53638. shouldHandle(req) {
  53639. if (this.options.path) {
  53640. const index = req.url.indexOf('?');
  53641. const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
  53642. if (pathname !== this.options.path) return false;
  53643. }
  53644. return true;
  53645. }
  53646. /**
  53647. * Handle a HTTP Upgrade request.
  53648. *
  53649. * @param {http.IncomingMessage} req The request object
  53650. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  53651. * server and client
  53652. * @param {Buffer} head The first packet of the upgraded stream
  53653. * @param {Function} cb Callback
  53654. * @public
  53655. */
  53656. handleUpgrade(req, socket, head, cb) {
  53657. socket.on('error', socketOnError);
  53658. const key = req.headers['sec-websocket-key'];
  53659. const version = +req.headers['sec-websocket-version'];
  53660. if (req.method !== 'GET') {
  53661. const message = 'Invalid HTTP method';
  53662. abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
  53663. return;
  53664. }
  53665. if (req.headers.upgrade.toLowerCase() !== 'websocket') {
  53666. const message = 'Invalid Upgrade header';
  53667. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  53668. return;
  53669. }
  53670. if (!key || !keyRegex.test(key)) {
  53671. const message = 'Missing or invalid Sec-WebSocket-Key header';
  53672. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  53673. return;
  53674. }
  53675. if (version !== 8 && version !== 13) {
  53676. const message = 'Missing or invalid Sec-WebSocket-Version header';
  53677. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  53678. return;
  53679. }
  53680. if (!this.shouldHandle(req)) {
  53681. abortHandshake(socket, 400);
  53682. return;
  53683. }
  53684. const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
  53685. let protocols = new Set();
  53686. if (secWebSocketProtocol !== undefined) {
  53687. try {
  53688. protocols = subprotocol.parse(secWebSocketProtocol);
  53689. } catch (err) {
  53690. const message = 'Invalid Sec-WebSocket-Protocol header';
  53691. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  53692. return;
  53693. }
  53694. }
  53695. const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
  53696. const extensions = {};
  53697. if (
  53698. this.options.perMessageDeflate &&
  53699. secWebSocketExtensions !== undefined
  53700. ) {
  53701. const perMessageDeflate = new PerMessageDeflate(
  53702. this.options.perMessageDeflate,
  53703. true,
  53704. this.options.maxPayload
  53705. );
  53706. try {
  53707. const offers = extension.parse(secWebSocketExtensions);
  53708. if (offers[PerMessageDeflate.extensionName]) {
  53709. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  53710. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  53711. }
  53712. } catch (err) {
  53713. const message =
  53714. 'Invalid or unacceptable Sec-WebSocket-Extensions header';
  53715. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  53716. return;
  53717. }
  53718. }
  53719. //
  53720. // Optionally call external client verification handler.
  53721. //
  53722. if (this.options.verifyClient) {
  53723. const info = {
  53724. origin:
  53725. req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
  53726. secure: !!(req.socket.authorized || req.socket.encrypted),
  53727. req
  53728. };
  53729. if (this.options.verifyClient.length === 2) {
  53730. this.options.verifyClient(info, (verified, code, message, headers) => {
  53731. if (!verified) {
  53732. return abortHandshake(socket, code || 401, message, headers);
  53733. }
  53734. this.completeUpgrade(
  53735. extensions,
  53736. key,
  53737. protocols,
  53738. req,
  53739. socket,
  53740. head,
  53741. cb
  53742. );
  53743. });
  53744. return;
  53745. }
  53746. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  53747. }
  53748. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  53749. }
  53750. /**
  53751. * Upgrade the connection to WebSocket.
  53752. *
  53753. * @param {Object} extensions The accepted extensions
  53754. * @param {String} key The value of the `Sec-WebSocket-Key` header
  53755. * @param {Set} protocols The subprotocols
  53756. * @param {http.IncomingMessage} req The request object
  53757. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  53758. * server and client
  53759. * @param {Buffer} head The first packet of the upgraded stream
  53760. * @param {Function} cb Callback
  53761. * @throws {Error} If called more than once with the same socket
  53762. * @private
  53763. */
  53764. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  53765. //
  53766. // Destroy the socket if the client has already sent a FIN packet.
  53767. //
  53768. if (!socket.readable || !socket.writable) return socket.destroy();
  53769. if (socket[kWebSocket]) {
  53770. throw new Error(
  53771. 'server.handleUpgrade() was called more than once with the same ' +
  53772. 'socket, possibly due to a misconfiguration'
  53773. );
  53774. }
  53775. if (this._state > RUNNING) return abortHandshake(socket, 503);
  53776. const digest = createHash('sha1')
  53777. .update(key + GUID)
  53778. .digest('base64');
  53779. const headers = [
  53780. 'HTTP/1.1 101 Switching Protocols',
  53781. 'Upgrade: websocket',
  53782. 'Connection: Upgrade',
  53783. `Sec-WebSocket-Accept: ${digest}`
  53784. ];
  53785. const ws = new this.options.WebSocket(null);
  53786. if (protocols.size) {
  53787. //
  53788. // Optionally call external protocol selection handler.
  53789. //
  53790. const protocol = this.options.handleProtocols
  53791. ? this.options.handleProtocols(protocols, req)
  53792. : protocols.values().next().value;
  53793. if (protocol) {
  53794. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  53795. ws._protocol = protocol;
  53796. }
  53797. }
  53798. if (extensions[PerMessageDeflate.extensionName]) {
  53799. const params = extensions[PerMessageDeflate.extensionName].params;
  53800. const value = extension.format({
  53801. [PerMessageDeflate.extensionName]: [params]
  53802. });
  53803. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  53804. ws._extensions = extensions;
  53805. }
  53806. //
  53807. // Allow external modification/inspection of handshake headers.
  53808. //
  53809. this.emit('headers', headers, req);
  53810. socket.write(headers.concat('\r\n').join('\r\n'));
  53811. socket.removeListener('error', socketOnError);
  53812. ws.setSocket(socket, head, {
  53813. maxPayload: this.options.maxPayload,
  53814. skipUTF8Validation: this.options.skipUTF8Validation
  53815. });
  53816. if (this.clients) {
  53817. this.clients.add(ws);
  53818. ws.on('close', () => {
  53819. this.clients.delete(ws);
  53820. if (this._shouldEmitClose && !this.clients.size) {
  53821. process.nextTick(emitClose, this);
  53822. }
  53823. });
  53824. }
  53825. cb(ws, req);
  53826. }
  53827. }
  53828. var websocketServer = WebSocketServer;
  53829. /**
  53830. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  53831. * pairs.
  53832. *
  53833. * @param {EventEmitter} server The event emitter
  53834. * @param {Object.<String, Function>} map The listeners to add
  53835. * @return {Function} A function that will remove the added listeners when
  53836. * called
  53837. * @private
  53838. */
  53839. function addListeners(server, map) {
  53840. for (const event of Object.keys(map)) server.on(event, map[event]);
  53841. return function removeListeners() {
  53842. for (const event of Object.keys(map)) {
  53843. server.removeListener(event, map[event]);
  53844. }
  53845. };
  53846. }
  53847. /**
  53848. * Emit a `'close'` event on an `EventEmitter`.
  53849. *
  53850. * @param {EventEmitter} server The event emitter
  53851. * @private
  53852. */
  53853. function emitClose(server) {
  53854. server._state = CLOSED;
  53855. server.emit('close');
  53856. }
  53857. /**
  53858. * Handle socket errors.
  53859. *
  53860. * @private
  53861. */
  53862. function socketOnError() {
  53863. this.destroy();
  53864. }
  53865. /**
  53866. * Close the connection when preconditions are not fulfilled.
  53867. *
  53868. * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
  53869. * @param {Number} code The HTTP response status code
  53870. * @param {String} [message] The HTTP response body
  53871. * @param {Object} [headers] Additional HTTP response headers
  53872. * @private
  53873. */
  53874. function abortHandshake(socket, code, message, headers) {
  53875. //
  53876. // The socket is writable unless the user destroyed or ended it before calling
  53877. // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
  53878. // error. Handling this does not make much sense as the worst that can happen
  53879. // is that some of the data written by the user might be discarded due to the
  53880. // call to `socket.end()` below, which triggers an `'error'` event that in
  53881. // turn causes the socket to be destroyed.
  53882. //
  53883. message = message || http$2.STATUS_CODES[code];
  53884. headers = {
  53885. Connection: 'close',
  53886. 'Content-Type': 'text/html',
  53887. 'Content-Length': Buffer.byteLength(message),
  53888. ...headers
  53889. };
  53890. socket.once('finish', socket.destroy);
  53891. socket.end(
  53892. `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` +
  53893. Object.keys(headers)
  53894. .map((h) => `${h}: ${headers[h]}`)
  53895. .join('\r\n') +
  53896. '\r\n\r\n' +
  53897. message
  53898. );
  53899. }
  53900. /**
  53901. * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
  53902. * one listener for it, otherwise call `abortHandshake()`.
  53903. *
  53904. * @param {WebSocketServer} server The WebSocket server
  53905. * @param {http.IncomingMessage} req The request object
  53906. * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
  53907. * @param {Number} code The HTTP response status code
  53908. * @param {String} message The HTTP response body
  53909. * @private
  53910. */
  53911. function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
  53912. if (server.listenerCount('wsClientError')) {
  53913. const err = new Error(message);
  53914. Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
  53915. server.emit('wsClientError', err, socket, req);
  53916. } else {
  53917. abortHandshake(socket, code, message);
  53918. }
  53919. }
  53920. var WebSocketServerRaw = /*@__PURE__*/getDefaultExportFromCjs(websocketServer);
  53921. const HMR_HEADER = 'vite-hmr';
  53922. const wsServerEvents = [
  53923. 'connection',
  53924. 'error',
  53925. 'headers',
  53926. 'listening',
  53927. 'message',
  53928. ];
  53929. function createWebSocketServer(server, config, httpsOptions) {
  53930. let wss;
  53931. let wsHttpServer = undefined;
  53932. const hmr = isObject$2(config.server.hmr) && config.server.hmr;
  53933. const hmrServer = hmr && hmr.server;
  53934. const hmrPort = hmr && hmr.port;
  53935. // TODO: the main server port may not have been chosen yet as it may use the next available
  53936. const portsAreCompatible = !hmrPort || hmrPort === config.server.port;
  53937. const wsServer = hmrServer || (portsAreCompatible && server);
  53938. const customListeners = new Map();
  53939. const clientsMap = new WeakMap();
  53940. const port = hmrPort || 24678;
  53941. const host = (hmr && hmr.host) || undefined;
  53942. if (wsServer) {
  53943. wss = new WebSocketServerRaw({ noServer: true });
  53944. wsServer.on('upgrade', (req, socket, head) => {
  53945. if (req.headers['sec-websocket-protocol'] === HMR_HEADER) {
  53946. wss.handleUpgrade(req, socket, head, (ws) => {
  53947. wss.emit('connection', ws, req);
  53948. });
  53949. }
  53950. });
  53951. }
  53952. else {
  53953. // http server request handler keeps the same with
  53954. // https://github.com/websockets/ws/blob/45e17acea791d865df6b255a55182e9c42e5877a/lib/websocket-server.js#L88-L96
  53955. const route = ((_, res) => {
  53956. const statusCode = 426;
  53957. const body = STATUS_CODES[statusCode];
  53958. if (!body)
  53959. throw new Error(`No body text found for the ${statusCode} status code`);
  53960. res.writeHead(statusCode, {
  53961. 'Content-Length': body.length,
  53962. 'Content-Type': 'text/plain',
  53963. });
  53964. res.end(body);
  53965. });
  53966. if (httpsOptions) {
  53967. wsHttpServer = createServer$2(httpsOptions, route);
  53968. }
  53969. else {
  53970. wsHttpServer = createServer$3(route);
  53971. }
  53972. // vite dev server in middleware mode
  53973. // need to call ws listen manually
  53974. wss = new WebSocketServerRaw({ server: wsHttpServer });
  53975. }
  53976. wss.on('connection', (socket) => {
  53977. socket.on('message', (raw) => {
  53978. if (!customListeners.size)
  53979. return;
  53980. let parsed;
  53981. try {
  53982. parsed = JSON.parse(String(raw));
  53983. }
  53984. catch { }
  53985. if (!parsed || parsed.type !== 'custom' || !parsed.event)
  53986. return;
  53987. const listeners = customListeners.get(parsed.event);
  53988. if (!listeners?.size)
  53989. return;
  53990. const client = getSocketClient(socket);
  53991. listeners.forEach((listener) => listener(parsed.data, client));
  53992. });
  53993. socket.on('error', (err) => {
  53994. config.logger.error(`${colors$1.red(`ws error:`)}\n${err.stack}`, {
  53995. timestamp: true,
  53996. error: err,
  53997. });
  53998. });
  53999. socket.send(JSON.stringify({ type: 'connected' }));
  54000. if (bufferedError) {
  54001. socket.send(JSON.stringify(bufferedError));
  54002. bufferedError = null;
  54003. }
  54004. });
  54005. wss.on('error', (e) => {
  54006. if (e.code === 'EADDRINUSE') {
  54007. config.logger.error(colors$1.red(`WebSocket server error: Port is already in use`), { error: e });
  54008. }
  54009. else {
  54010. config.logger.error(colors$1.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  54011. }
  54012. });
  54013. // Provide a wrapper to the ws client so we can send messages in JSON format
  54014. // To be consistent with server.ws.send
  54015. function getSocketClient(socket) {
  54016. if (!clientsMap.has(socket)) {
  54017. clientsMap.set(socket, {
  54018. send: (...args) => {
  54019. let payload;
  54020. if (typeof args[0] === 'string') {
  54021. payload = {
  54022. type: 'custom',
  54023. event: args[0],
  54024. data: args[1],
  54025. };
  54026. }
  54027. else {
  54028. payload = args[0];
  54029. }
  54030. socket.send(JSON.stringify(payload));
  54031. },
  54032. socket,
  54033. });
  54034. }
  54035. return clientsMap.get(socket);
  54036. }
  54037. // On page reloads, if a file fails to compile and returns 500, the server
  54038. // sends the error payload before the client connection is established.
  54039. // If we have no open clients, buffer the error and send it to the next
  54040. // connected client.
  54041. let bufferedError = null;
  54042. return {
  54043. listen: () => {
  54044. wsHttpServer?.listen(port, host);
  54045. },
  54046. on: ((event, fn) => {
  54047. if (wsServerEvents.includes(event))
  54048. wss.on(event, fn);
  54049. else {
  54050. if (!customListeners.has(event)) {
  54051. customListeners.set(event, new Set());
  54052. }
  54053. customListeners.get(event).add(fn);
  54054. }
  54055. }),
  54056. off: ((event, fn) => {
  54057. if (wsServerEvents.includes(event)) {
  54058. wss.off(event, fn);
  54059. }
  54060. else {
  54061. customListeners.get(event)?.delete(fn);
  54062. }
  54063. }),
  54064. get clients() {
  54065. return new Set(Array.from(wss.clients).map(getSocketClient));
  54066. },
  54067. send(...args) {
  54068. let payload;
  54069. if (typeof args[0] === 'string') {
  54070. payload = {
  54071. type: 'custom',
  54072. event: args[0],
  54073. data: args[1],
  54074. };
  54075. }
  54076. else {
  54077. payload = args[0];
  54078. }
  54079. if (payload.type === 'error' && !wss.clients.size) {
  54080. bufferedError = payload;
  54081. return;
  54082. }
  54083. const stringified = JSON.stringify(payload);
  54084. wss.clients.forEach((client) => {
  54085. // readyState 1 means the connection is open
  54086. if (client.readyState === 1) {
  54087. client.send(stringified);
  54088. }
  54089. });
  54090. },
  54091. close() {
  54092. return new Promise((resolve, reject) => {
  54093. wss.clients.forEach((client) => {
  54094. client.terminate();
  54095. });
  54096. wss.close((err) => {
  54097. if (err) {
  54098. reject(err);
  54099. }
  54100. else {
  54101. if (wsHttpServer) {
  54102. wsHttpServer.close((err) => {
  54103. if (err) {
  54104. reject(err);
  54105. }
  54106. else {
  54107. resolve();
  54108. }
  54109. });
  54110. }
  54111. else {
  54112. resolve();
  54113. }
  54114. }
  54115. });
  54116. });
  54117. },
  54118. };
  54119. }
  54120. // this middleware is only active when (base !== '/')
  54121. function baseMiddleware({ config, }) {
  54122. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  54123. return function viteBaseMiddleware(req, res, next) {
  54124. const url = req.url;
  54125. const parsed = new URL(url, 'http://vitejs.dev');
  54126. const path = parsed.pathname || '/';
  54127. const base = config.rawBase;
  54128. if (path.startsWith(base)) {
  54129. // rewrite url to remove base. this ensures that other middleware does
  54130. // not need to consider base being prepended or not
  54131. req.url = stripBase(url, base);
  54132. return next();
  54133. }
  54134. // skip redirect and error fallback on middleware mode, #4057
  54135. if (config.server.middlewareMode) {
  54136. return next();
  54137. }
  54138. if (path === '/' || path === '/index.html') {
  54139. // redirect root visit to based url with search and hash
  54140. res.writeHead(302, {
  54141. Location: base + (parsed.search || '') + (parsed.hash || ''),
  54142. });
  54143. res.end();
  54144. return;
  54145. }
  54146. else if (req.headers.accept?.includes('text/html')) {
  54147. // non-based page visit
  54148. const redirectPath = url + '/' !== base ? joinUrlSegments(base, url) : base;
  54149. res.writeHead(404, {
  54150. 'Content-Type': 'text/html',
  54151. });
  54152. res.end(`The server is configured with a public base URL of ${base} - ` +
  54153. `did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
  54154. return;
  54155. }
  54156. next();
  54157. };
  54158. }
  54159. var httpProxy$3 = {exports: {}};
  54160. var eventemitter3 = {exports: {}};
  54161. (function (module) {
  54162. var has = Object.prototype.hasOwnProperty
  54163. , prefix = '~';
  54164. /**
  54165. * Constructor to create a storage for our `EE` objects.
  54166. * An `Events` instance is a plain object whose properties are event names.
  54167. *
  54168. * @constructor
  54169. * @private
  54170. */
  54171. function Events() {}
  54172. //
  54173. // We try to not inherit from `Object.prototype`. In some engines creating an
  54174. // instance in this way is faster than calling `Object.create(null)` directly.
  54175. // If `Object.create(null)` is not supported we prefix the event names with a
  54176. // character to make sure that the built-in object properties are not
  54177. // overridden or used as an attack vector.
  54178. //
  54179. if (Object.create) {
  54180. Events.prototype = Object.create(null);
  54181. //
  54182. // This hack is needed because the `__proto__` property is still inherited in
  54183. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  54184. //
  54185. if (!new Events().__proto__) prefix = false;
  54186. }
  54187. /**
  54188. * Representation of a single event listener.
  54189. *
  54190. * @param {Function} fn The listener function.
  54191. * @param {*} context The context to invoke the listener with.
  54192. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  54193. * @constructor
  54194. * @private
  54195. */
  54196. function EE(fn, context, once) {
  54197. this.fn = fn;
  54198. this.context = context;
  54199. this.once = once || false;
  54200. }
  54201. /**
  54202. * Add a listener for a given event.
  54203. *
  54204. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  54205. * @param {(String|Symbol)} event The event name.
  54206. * @param {Function} fn The listener function.
  54207. * @param {*} context The context to invoke the listener with.
  54208. * @param {Boolean} once Specify if the listener is a one-time listener.
  54209. * @returns {EventEmitter}
  54210. * @private
  54211. */
  54212. function addListener(emitter, event, fn, context, once) {
  54213. if (typeof fn !== 'function') {
  54214. throw new TypeError('The listener must be a function');
  54215. }
  54216. var listener = new EE(fn, context || emitter, once)
  54217. , evt = prefix ? prefix + event : event;
  54218. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  54219. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  54220. else emitter._events[evt] = [emitter._events[evt], listener];
  54221. return emitter;
  54222. }
  54223. /**
  54224. * Clear event by name.
  54225. *
  54226. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  54227. * @param {(String|Symbol)} evt The Event name.
  54228. * @private
  54229. */
  54230. function clearEvent(emitter, evt) {
  54231. if (--emitter._eventsCount === 0) emitter._events = new Events();
  54232. else delete emitter._events[evt];
  54233. }
  54234. /**
  54235. * Minimal `EventEmitter` interface that is molded against the Node.js
  54236. * `EventEmitter` interface.
  54237. *
  54238. * @constructor
  54239. * @public
  54240. */
  54241. function EventEmitter() {
  54242. this._events = new Events();
  54243. this._eventsCount = 0;
  54244. }
  54245. /**
  54246. * Return an array listing the events for which the emitter has registered
  54247. * listeners.
  54248. *
  54249. * @returns {Array}
  54250. * @public
  54251. */
  54252. EventEmitter.prototype.eventNames = function eventNames() {
  54253. var names = []
  54254. , events
  54255. , name;
  54256. if (this._eventsCount === 0) return names;
  54257. for (name in (events = this._events)) {
  54258. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  54259. }
  54260. if (Object.getOwnPropertySymbols) {
  54261. return names.concat(Object.getOwnPropertySymbols(events));
  54262. }
  54263. return names;
  54264. };
  54265. /**
  54266. * Return the listeners registered for a given event.
  54267. *
  54268. * @param {(String|Symbol)} event The event name.
  54269. * @returns {Array} The registered listeners.
  54270. * @public
  54271. */
  54272. EventEmitter.prototype.listeners = function listeners(event) {
  54273. var evt = prefix ? prefix + event : event
  54274. , handlers = this._events[evt];
  54275. if (!handlers) return [];
  54276. if (handlers.fn) return [handlers.fn];
  54277. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  54278. ee[i] = handlers[i].fn;
  54279. }
  54280. return ee;
  54281. };
  54282. /**
  54283. * Return the number of listeners listening to a given event.
  54284. *
  54285. * @param {(String|Symbol)} event The event name.
  54286. * @returns {Number} The number of listeners.
  54287. * @public
  54288. */
  54289. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  54290. var evt = prefix ? prefix + event : event
  54291. , listeners = this._events[evt];
  54292. if (!listeners) return 0;
  54293. if (listeners.fn) return 1;
  54294. return listeners.length;
  54295. };
  54296. /**
  54297. * Calls each of the listeners registered for a given event.
  54298. *
  54299. * @param {(String|Symbol)} event The event name.
  54300. * @returns {Boolean} `true` if the event had listeners, else `false`.
  54301. * @public
  54302. */
  54303. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  54304. var evt = prefix ? prefix + event : event;
  54305. if (!this._events[evt]) return false;
  54306. var listeners = this._events[evt]
  54307. , len = arguments.length
  54308. , args
  54309. , i;
  54310. if (listeners.fn) {
  54311. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  54312. switch (len) {
  54313. case 1: return listeners.fn.call(listeners.context), true;
  54314. case 2: return listeners.fn.call(listeners.context, a1), true;
  54315. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  54316. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  54317. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  54318. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  54319. }
  54320. for (i = 1, args = new Array(len -1); i < len; i++) {
  54321. args[i - 1] = arguments[i];
  54322. }
  54323. listeners.fn.apply(listeners.context, args);
  54324. } else {
  54325. var length = listeners.length
  54326. , j;
  54327. for (i = 0; i < length; i++) {
  54328. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  54329. switch (len) {
  54330. case 1: listeners[i].fn.call(listeners[i].context); break;
  54331. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  54332. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  54333. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  54334. default:
  54335. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  54336. args[j - 1] = arguments[j];
  54337. }
  54338. listeners[i].fn.apply(listeners[i].context, args);
  54339. }
  54340. }
  54341. }
  54342. return true;
  54343. };
  54344. /**
  54345. * Add a listener for a given event.
  54346. *
  54347. * @param {(String|Symbol)} event The event name.
  54348. * @param {Function} fn The listener function.
  54349. * @param {*} [context=this] The context to invoke the listener with.
  54350. * @returns {EventEmitter} `this`.
  54351. * @public
  54352. */
  54353. EventEmitter.prototype.on = function on(event, fn, context) {
  54354. return addListener(this, event, fn, context, false);
  54355. };
  54356. /**
  54357. * Add a one-time listener for a given event.
  54358. *
  54359. * @param {(String|Symbol)} event The event name.
  54360. * @param {Function} fn The listener function.
  54361. * @param {*} [context=this] The context to invoke the listener with.
  54362. * @returns {EventEmitter} `this`.
  54363. * @public
  54364. */
  54365. EventEmitter.prototype.once = function once(event, fn, context) {
  54366. return addListener(this, event, fn, context, true);
  54367. };
  54368. /**
  54369. * Remove the listeners of a given event.
  54370. *
  54371. * @param {(String|Symbol)} event The event name.
  54372. * @param {Function} fn Only remove the listeners that match this function.
  54373. * @param {*} context Only remove the listeners that have this context.
  54374. * @param {Boolean} once Only remove one-time listeners.
  54375. * @returns {EventEmitter} `this`.
  54376. * @public
  54377. */
  54378. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  54379. var evt = prefix ? prefix + event : event;
  54380. if (!this._events[evt]) return this;
  54381. if (!fn) {
  54382. clearEvent(this, evt);
  54383. return this;
  54384. }
  54385. var listeners = this._events[evt];
  54386. if (listeners.fn) {
  54387. if (
  54388. listeners.fn === fn &&
  54389. (!once || listeners.once) &&
  54390. (!context || listeners.context === context)
  54391. ) {
  54392. clearEvent(this, evt);
  54393. }
  54394. } else {
  54395. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  54396. if (
  54397. listeners[i].fn !== fn ||
  54398. (once && !listeners[i].once) ||
  54399. (context && listeners[i].context !== context)
  54400. ) {
  54401. events.push(listeners[i]);
  54402. }
  54403. }
  54404. //
  54405. // Reset the array, or remove it completely if we have no more listeners.
  54406. //
  54407. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  54408. else clearEvent(this, evt);
  54409. }
  54410. return this;
  54411. };
  54412. /**
  54413. * Remove all listeners, or those of the specified event.
  54414. *
  54415. * @param {(String|Symbol)} [event] The event name.
  54416. * @returns {EventEmitter} `this`.
  54417. * @public
  54418. */
  54419. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  54420. var evt;
  54421. if (event) {
  54422. evt = prefix ? prefix + event : event;
  54423. if (this._events[evt]) clearEvent(this, evt);
  54424. } else {
  54425. this._events = new Events();
  54426. this._eventsCount = 0;
  54427. }
  54428. return this;
  54429. };
  54430. //
  54431. // Alias methods names because people roll like that.
  54432. //
  54433. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  54434. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  54435. //
  54436. // Expose the prefix.
  54437. //
  54438. EventEmitter.prefixed = prefix;
  54439. //
  54440. // Allow `EventEmitter` to be imported as module namespace.
  54441. //
  54442. EventEmitter.EventEmitter = EventEmitter;
  54443. //
  54444. // Expose the module.
  54445. //
  54446. {
  54447. module.exports = EventEmitter;
  54448. }
  54449. } (eventemitter3));
  54450. var eventemitter3Exports = eventemitter3.exports;
  54451. var common$3 = {};
  54452. /**
  54453. * Check if we're required to add a port number.
  54454. *
  54455. * @see https://url.spec.whatwg.org/#default-port
  54456. * @param {Number|String} port Port number we need to check
  54457. * @param {String} protocol Protocol we need to check against.
  54458. * @returns {Boolean} Is it a default port for the given protocol
  54459. * @api private
  54460. */
  54461. var requiresPort = function required(port, protocol) {
  54462. protocol = protocol.split(':')[0];
  54463. port = +port;
  54464. if (!port) return false;
  54465. switch (protocol) {
  54466. case 'http':
  54467. case 'ws':
  54468. return port !== 80;
  54469. case 'https':
  54470. case 'wss':
  54471. return port !== 443;
  54472. case 'ftp':
  54473. return port !== 21;
  54474. case 'gopher':
  54475. return port !== 70;
  54476. case 'file':
  54477. return false;
  54478. }
  54479. return port !== 0;
  54480. };
  54481. (function (exports) {
  54482. var common = exports,
  54483. url = require$$0$9,
  54484. extend = require$$0$6._extend,
  54485. required = requiresPort;
  54486. var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
  54487. isSSL = /^https|wss/;
  54488. /**
  54489. * Simple Regex for testing if protocol is https
  54490. */
  54491. common.isSSL = isSSL;
  54492. /**
  54493. * Copies the right headers from `options` and `req` to
  54494. * `outgoing` which is then used to fire the proxied
  54495. * request.
  54496. *
  54497. * Examples:
  54498. *
  54499. * common.setupOutgoing(outgoing, options, req)
  54500. * // => { host: ..., hostname: ...}
  54501. *
  54502. * @param {Object} Outgoing Base object to be filled with required properties
  54503. * @param {Object} Options Config object passed to the proxy
  54504. * @param {ClientRequest} Req Request Object
  54505. * @param {String} Forward String to select forward or target
  54506. * @return {Object} Outgoing Object with all required properties set
  54507. *
  54508. * @api private
  54509. */
  54510. common.setupOutgoing = function(outgoing, options, req, forward) {
  54511. outgoing.port = options[forward || 'target'].port ||
  54512. (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80);
  54513. ['host', 'hostname', 'socketPath', 'pfx', 'key',
  54514. 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach(
  54515. function(e) { outgoing[e] = options[forward || 'target'][e]; }
  54516. );
  54517. outgoing.method = options.method || req.method;
  54518. outgoing.headers = extend({}, req.headers);
  54519. if (options.headers){
  54520. extend(outgoing.headers, options.headers);
  54521. }
  54522. if (options.auth) {
  54523. outgoing.auth = options.auth;
  54524. }
  54525. if (options.ca) {
  54526. outgoing.ca = options.ca;
  54527. }
  54528. if (isSSL.test(options[forward || 'target'].protocol)) {
  54529. outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure;
  54530. }
  54531. outgoing.agent = options.agent || false;
  54532. outgoing.localAddress = options.localAddress;
  54533. //
  54534. // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do
  54535. // as node core doesn't handle this COMPLETELY properly yet.
  54536. //
  54537. if (!outgoing.agent) {
  54538. outgoing.headers = outgoing.headers || {};
  54539. if (typeof outgoing.headers.connection !== 'string'
  54540. || !upgradeHeader.test(outgoing.headers.connection)
  54541. ) { outgoing.headers.connection = 'close'; }
  54542. }
  54543. // the final path is target path + relative path requested by user:
  54544. var target = options[forward || 'target'];
  54545. var targetPath = target && options.prependPath !== false
  54546. ? (target.path || '')
  54547. : '';
  54548. //
  54549. // Remark: Can we somehow not use url.parse as a perf optimization?
  54550. //
  54551. var outgoingPath = !options.toProxy
  54552. ? (url.parse(req.url).path || '')
  54553. : req.url;
  54554. //
  54555. // Remark: ignorePath will just straight up ignore whatever the request's
  54556. // path is. This can be labeled as FOOT-GUN material if you do not know what
  54557. // you are doing and are using conflicting options.
  54558. //
  54559. outgoingPath = !options.ignorePath ? outgoingPath : '';
  54560. outgoing.path = common.urlJoin(targetPath, outgoingPath);
  54561. if (options.changeOrigin) {
  54562. outgoing.headers.host =
  54563. required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host)
  54564. ? outgoing.host + ':' + outgoing.port
  54565. : outgoing.host;
  54566. }
  54567. return outgoing;
  54568. };
  54569. /**
  54570. * Set the proper configuration for sockets,
  54571. * set no delay and set keep alive, also set
  54572. * the timeout to 0.
  54573. *
  54574. * Examples:
  54575. *
  54576. * common.setupSocket(socket)
  54577. * // => Socket
  54578. *
  54579. * @param {Socket} Socket instance to setup
  54580. * @return {Socket} Return the configured socket.
  54581. *
  54582. * @api private
  54583. */
  54584. common.setupSocket = function(socket) {
  54585. socket.setTimeout(0);
  54586. socket.setNoDelay(true);
  54587. socket.setKeepAlive(true, 0);
  54588. return socket;
  54589. };
  54590. /**
  54591. * Get the port number from the host. Or guess it based on the connection type.
  54592. *
  54593. * @param {Request} req Incoming HTTP request.
  54594. *
  54595. * @return {String} The port number.
  54596. *
  54597. * @api private
  54598. */
  54599. common.getPort = function(req) {
  54600. var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : '';
  54601. return res ?
  54602. res[1] :
  54603. common.hasEncryptedConnection(req) ? '443' : '80';
  54604. };
  54605. /**
  54606. * Check if the request has an encrypted connection.
  54607. *
  54608. * @param {Request} req Incoming HTTP request.
  54609. *
  54610. * @return {Boolean} Whether the connection is encrypted or not.
  54611. *
  54612. * @api private
  54613. */
  54614. common.hasEncryptedConnection = function(req) {
  54615. return Boolean(req.connection.encrypted || req.connection.pair);
  54616. };
  54617. /**
  54618. * OS-agnostic join (doesn't break on URLs like path.join does on Windows)>
  54619. *
  54620. * @return {String} The generated path.
  54621. *
  54622. * @api private
  54623. */
  54624. common.urlJoin = function() {
  54625. //
  54626. // We do not want to mess with the query string. All we want to touch is the path.
  54627. //
  54628. var args = Array.prototype.slice.call(arguments),
  54629. lastIndex = args.length - 1,
  54630. last = args[lastIndex],
  54631. lastSegs = last.split('?'),
  54632. retSegs;
  54633. args[lastIndex] = lastSegs.shift();
  54634. //
  54635. // Join all strings, but remove empty strings so we don't get extra slashes from
  54636. // joining e.g. ['', 'am']
  54637. //
  54638. retSegs = [
  54639. args.filter(Boolean).join('/')
  54640. .replace(/\/+/g, '/')
  54641. .replace('http:/', 'http://')
  54642. .replace('https:/', 'https://')
  54643. ];
  54644. // Only join the query string if it exists so we don't have trailing a '?'
  54645. // on every request
  54646. // Handle case where there could be multiple ? in the URL.
  54647. retSegs.push.apply(retSegs, lastSegs);
  54648. return retSegs.join('?')
  54649. };
  54650. /**
  54651. * Rewrites or removes the domain of a cookie header
  54652. *
  54653. * @param {String|Array} Header
  54654. * @param {Object} Config, mapping of domain to rewritten domain.
  54655. * '*' key to match any domain, null value to remove the domain.
  54656. *
  54657. * @api private
  54658. */
  54659. common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {
  54660. if (Array.isArray(header)) {
  54661. return header.map(function (headerElement) {
  54662. return rewriteCookieProperty(headerElement, config, property);
  54663. });
  54664. }
  54665. return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) {
  54666. var newValue;
  54667. if (previousValue in config) {
  54668. newValue = config[previousValue];
  54669. } else if ('*' in config) {
  54670. newValue = config['*'];
  54671. } else {
  54672. //no match, return previous value
  54673. return match;
  54674. }
  54675. if (newValue) {
  54676. //replace value
  54677. return prefix + newValue;
  54678. } else {
  54679. //remove value
  54680. return '';
  54681. }
  54682. });
  54683. };
  54684. /**
  54685. * Check the host and see if it potentially has a port in it (keep it simple)
  54686. *
  54687. * @returns {Boolean} Whether we have one or not
  54688. *
  54689. * @api private
  54690. */
  54691. function hasPort(host) {
  54692. return !!~host.indexOf(':');
  54693. }} (common$3));
  54694. var url$1 = require$$0$9,
  54695. common$2 = common$3;
  54696. var redirectRegex = /^201|30(1|2|7|8)$/;
  54697. /*!
  54698. * Array of passes.
  54699. *
  54700. * A `pass` is just a function that is executed on `req, res, options`
  54701. * so that you can easily add new checks while still keeping the base
  54702. * flexible.
  54703. */
  54704. var webOutgoing = { // <--
  54705. /**
  54706. * If is a HTTP 1.0 request, remove chunk headers
  54707. *
  54708. * @param {ClientRequest} Req Request object
  54709. * @param {IncomingMessage} Res Response object
  54710. * @param {proxyResponse} Res Response object from the proxy request
  54711. *
  54712. * @api private
  54713. */
  54714. removeChunked: function removeChunked(req, res, proxyRes) {
  54715. if (req.httpVersion === '1.0') {
  54716. delete proxyRes.headers['transfer-encoding'];
  54717. }
  54718. },
  54719. /**
  54720. * If is a HTTP 1.0 request, set the correct connection header
  54721. * or if connection header not present, then use `keep-alive`
  54722. *
  54723. * @param {ClientRequest} Req Request object
  54724. * @param {IncomingMessage} Res Response object
  54725. * @param {proxyResponse} Res Response object from the proxy request
  54726. *
  54727. * @api private
  54728. */
  54729. setConnection: function setConnection(req, res, proxyRes) {
  54730. if (req.httpVersion === '1.0') {
  54731. proxyRes.headers.connection = req.headers.connection || 'close';
  54732. } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {
  54733. proxyRes.headers.connection = req.headers.connection || 'keep-alive';
  54734. }
  54735. },
  54736. setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {
  54737. if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
  54738. && proxyRes.headers['location']
  54739. && redirectRegex.test(proxyRes.statusCode)) {
  54740. var target = url$1.parse(options.target);
  54741. var u = url$1.parse(proxyRes.headers['location']);
  54742. // make sure the redirected host matches the target host before rewriting
  54743. if (target.host != u.host) {
  54744. return;
  54745. }
  54746. if (options.hostRewrite) {
  54747. u.host = options.hostRewrite;
  54748. } else if (options.autoRewrite) {
  54749. u.host = req.headers['host'];
  54750. }
  54751. if (options.protocolRewrite) {
  54752. u.protocol = options.protocolRewrite;
  54753. }
  54754. proxyRes.headers['location'] = u.format();
  54755. }
  54756. },
  54757. /**
  54758. * Copy headers from proxyResponse to response
  54759. * set each header in response object.
  54760. *
  54761. * @param {ClientRequest} Req Request object
  54762. * @param {IncomingMessage} Res Response object
  54763. * @param {proxyResponse} Res Response object from the proxy request
  54764. * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
  54765. *
  54766. * @api private
  54767. */
  54768. writeHeaders: function writeHeaders(req, res, proxyRes, options) {
  54769. var rewriteCookieDomainConfig = options.cookieDomainRewrite,
  54770. rewriteCookiePathConfig = options.cookiePathRewrite,
  54771. preserveHeaderKeyCase = options.preserveHeaderKeyCase,
  54772. rawHeaderKeyMap,
  54773. setHeader = function(key, header) {
  54774. if (header == undefined) return;
  54775. if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
  54776. header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');
  54777. }
  54778. if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {
  54779. header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');
  54780. }
  54781. res.setHeader(String(key).trim(), header);
  54782. };
  54783. if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''
  54784. rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
  54785. }
  54786. if (typeof rewriteCookiePathConfig === 'string') { //also test for ''
  54787. rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };
  54788. }
  54789. // message.rawHeaders is added in: v0.11.6
  54790. // https://nodejs.org/api/http.html#http_message_rawheaders
  54791. if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
  54792. rawHeaderKeyMap = {};
  54793. for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
  54794. var key = proxyRes.rawHeaders[i];
  54795. rawHeaderKeyMap[key.toLowerCase()] = key;
  54796. }
  54797. }
  54798. Object.keys(proxyRes.headers).forEach(function(key) {
  54799. var header = proxyRes.headers[key];
  54800. if (preserveHeaderKeyCase && rawHeaderKeyMap) {
  54801. key = rawHeaderKeyMap[key] || key;
  54802. }
  54803. setHeader(key, header);
  54804. });
  54805. },
  54806. /**
  54807. * Set the statusCode from the proxyResponse
  54808. *
  54809. * @param {ClientRequest} Req Request object
  54810. * @param {IncomingMessage} Res Response object
  54811. * @param {proxyResponse} Res Response object from the proxy request
  54812. *
  54813. * @api private
  54814. */
  54815. writeStatusCode: function writeStatusCode(req, res, proxyRes) {
  54816. // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
  54817. if(proxyRes.statusMessage) {
  54818. res.statusCode = proxyRes.statusCode;
  54819. res.statusMessage = proxyRes.statusMessage;
  54820. } else {
  54821. res.statusCode = proxyRes.statusCode;
  54822. }
  54823. }
  54824. };
  54825. var followRedirects$1 = {exports: {}};
  54826. var debug$3;
  54827. var debug_1 = function () {
  54828. if (!debug$3) {
  54829. try {
  54830. /* eslint global-require: off */
  54831. debug$3 = srcExports$1("follow-redirects");
  54832. }
  54833. catch (error) { /* */ }
  54834. if (typeof debug$3 !== "function") {
  54835. debug$3 = function () { /* */ };
  54836. }
  54837. }
  54838. debug$3.apply(null, arguments);
  54839. };
  54840. var url = require$$0$9;
  54841. var URL$1 = url.URL;
  54842. var http$1 = require$$1$1;
  54843. var https$1 = require$$1$2;
  54844. var Writable = require$$0$7.Writable;
  54845. var assert = require$$5;
  54846. var debug$2 = debug_1;
  54847. // Create handlers that pass events from native requests
  54848. var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
  54849. var eventHandlers = Object.create(null);
  54850. events.forEach(function (event) {
  54851. eventHandlers[event] = function (arg1, arg2, arg3) {
  54852. this._redirectable.emit(event, arg1, arg2, arg3);
  54853. };
  54854. });
  54855. // Error types with codes
  54856. var RedirectionError = createErrorType(
  54857. "ERR_FR_REDIRECTION_FAILURE",
  54858. "Redirected request failed"
  54859. );
  54860. var TooManyRedirectsError = createErrorType(
  54861. "ERR_FR_TOO_MANY_REDIRECTS",
  54862. "Maximum number of redirects exceeded"
  54863. );
  54864. var MaxBodyLengthExceededError = createErrorType(
  54865. "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
  54866. "Request body larger than maxBodyLength limit"
  54867. );
  54868. var WriteAfterEndError = createErrorType(
  54869. "ERR_STREAM_WRITE_AFTER_END",
  54870. "write after end"
  54871. );
  54872. // An HTTP(S) request that can be redirected
  54873. function RedirectableRequest(options, responseCallback) {
  54874. // Initialize the request
  54875. Writable.call(this);
  54876. this._sanitizeOptions(options);
  54877. this._options = options;
  54878. this._ended = false;
  54879. this._ending = false;
  54880. this._redirectCount = 0;
  54881. this._redirects = [];
  54882. this._requestBodyLength = 0;
  54883. this._requestBodyBuffers = [];
  54884. // Attach a callback if passed
  54885. if (responseCallback) {
  54886. this.on("response", responseCallback);
  54887. }
  54888. // React to responses of native requests
  54889. var self = this;
  54890. this._onNativeResponse = function (response) {
  54891. self._processResponse(response);
  54892. };
  54893. // Perform the first request
  54894. this._performRequest();
  54895. }
  54896. RedirectableRequest.prototype = Object.create(Writable.prototype);
  54897. RedirectableRequest.prototype.abort = function () {
  54898. abortRequest(this._currentRequest);
  54899. this.emit("abort");
  54900. };
  54901. // Writes buffered data to the current native request
  54902. RedirectableRequest.prototype.write = function (data, encoding, callback) {
  54903. // Writing is not allowed if end has been called
  54904. if (this._ending) {
  54905. throw new WriteAfterEndError();
  54906. }
  54907. // Validate input and shift parameters if necessary
  54908. if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
  54909. throw new TypeError("data should be a string, Buffer or Uint8Array");
  54910. }
  54911. if (typeof encoding === "function") {
  54912. callback = encoding;
  54913. encoding = null;
  54914. }
  54915. // Ignore empty buffers, since writing them doesn't invoke the callback
  54916. // https://github.com/nodejs/node/issues/22066
  54917. if (data.length === 0) {
  54918. if (callback) {
  54919. callback();
  54920. }
  54921. return;
  54922. }
  54923. // Only write when we don't exceed the maximum body length
  54924. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  54925. this._requestBodyLength += data.length;
  54926. this._requestBodyBuffers.push({ data: data, encoding: encoding });
  54927. this._currentRequest.write(data, encoding, callback);
  54928. }
  54929. // Error when we exceed the maximum body length
  54930. else {
  54931. this.emit("error", new MaxBodyLengthExceededError());
  54932. this.abort();
  54933. }
  54934. };
  54935. // Ends the current native request
  54936. RedirectableRequest.prototype.end = function (data, encoding, callback) {
  54937. // Shift parameters if necessary
  54938. if (typeof data === "function") {
  54939. callback = data;
  54940. data = encoding = null;
  54941. }
  54942. else if (typeof encoding === "function") {
  54943. callback = encoding;
  54944. encoding = null;
  54945. }
  54946. // Write data if needed and end
  54947. if (!data) {
  54948. this._ended = this._ending = true;
  54949. this._currentRequest.end(null, null, callback);
  54950. }
  54951. else {
  54952. var self = this;
  54953. var currentRequest = this._currentRequest;
  54954. this.write(data, encoding, function () {
  54955. self._ended = true;
  54956. currentRequest.end(null, null, callback);
  54957. });
  54958. this._ending = true;
  54959. }
  54960. };
  54961. // Sets a header value on the current native request
  54962. RedirectableRequest.prototype.setHeader = function (name, value) {
  54963. this._options.headers[name] = value;
  54964. this._currentRequest.setHeader(name, value);
  54965. };
  54966. // Clears a header value on the current native request
  54967. RedirectableRequest.prototype.removeHeader = function (name) {
  54968. delete this._options.headers[name];
  54969. this._currentRequest.removeHeader(name);
  54970. };
  54971. // Global timeout for all underlying requests
  54972. RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
  54973. var self = this;
  54974. // Destroys the socket on timeout
  54975. function destroyOnTimeout(socket) {
  54976. socket.setTimeout(msecs);
  54977. socket.removeListener("timeout", socket.destroy);
  54978. socket.addListener("timeout", socket.destroy);
  54979. }
  54980. // Sets up a timer to trigger a timeout event
  54981. function startTimer(socket) {
  54982. if (self._timeout) {
  54983. clearTimeout(self._timeout);
  54984. }
  54985. self._timeout = setTimeout(function () {
  54986. self.emit("timeout");
  54987. clearTimer();
  54988. }, msecs);
  54989. destroyOnTimeout(socket);
  54990. }
  54991. // Stops a timeout from triggering
  54992. function clearTimer() {
  54993. // Clear the timeout
  54994. if (self._timeout) {
  54995. clearTimeout(self._timeout);
  54996. self._timeout = null;
  54997. }
  54998. // Clean up all attached listeners
  54999. self.removeListener("abort", clearTimer);
  55000. self.removeListener("error", clearTimer);
  55001. self.removeListener("response", clearTimer);
  55002. if (callback) {
  55003. self.removeListener("timeout", callback);
  55004. }
  55005. if (!self.socket) {
  55006. self._currentRequest.removeListener("socket", startTimer);
  55007. }
  55008. }
  55009. // Attach callback if passed
  55010. if (callback) {
  55011. this.on("timeout", callback);
  55012. }
  55013. // Start the timer if or when the socket is opened
  55014. if (this.socket) {
  55015. startTimer(this.socket);
  55016. }
  55017. else {
  55018. this._currentRequest.once("socket", startTimer);
  55019. }
  55020. // Clean up on events
  55021. this.on("socket", destroyOnTimeout);
  55022. this.on("abort", clearTimer);
  55023. this.on("error", clearTimer);
  55024. this.on("response", clearTimer);
  55025. return this;
  55026. };
  55027. // Proxy all other public ClientRequest methods
  55028. [
  55029. "flushHeaders", "getHeader",
  55030. "setNoDelay", "setSocketKeepAlive",
  55031. ].forEach(function (method) {
  55032. RedirectableRequest.prototype[method] = function (a, b) {
  55033. return this._currentRequest[method](a, b);
  55034. };
  55035. });
  55036. // Proxy all public ClientRequest properties
  55037. ["aborted", "connection", "socket"].forEach(function (property) {
  55038. Object.defineProperty(RedirectableRequest.prototype, property, {
  55039. get: function () { return this._currentRequest[property]; },
  55040. });
  55041. });
  55042. RedirectableRequest.prototype._sanitizeOptions = function (options) {
  55043. // Ensure headers are always present
  55044. if (!options.headers) {
  55045. options.headers = {};
  55046. }
  55047. // Since http.request treats host as an alias of hostname,
  55048. // but the url module interprets host as hostname plus port,
  55049. // eliminate the host property to avoid confusion.
  55050. if (options.host) {
  55051. // Use hostname if set, because it has precedence
  55052. if (!options.hostname) {
  55053. options.hostname = options.host;
  55054. }
  55055. delete options.host;
  55056. }
  55057. // Complete the URL object when necessary
  55058. if (!options.pathname && options.path) {
  55059. var searchPos = options.path.indexOf("?");
  55060. if (searchPos < 0) {
  55061. options.pathname = options.path;
  55062. }
  55063. else {
  55064. options.pathname = options.path.substring(0, searchPos);
  55065. options.search = options.path.substring(searchPos);
  55066. }
  55067. }
  55068. };
  55069. // Executes the next native request (initial or redirect)
  55070. RedirectableRequest.prototype._performRequest = function () {
  55071. // Load the native protocol
  55072. var protocol = this._options.protocol;
  55073. var nativeProtocol = this._options.nativeProtocols[protocol];
  55074. if (!nativeProtocol) {
  55075. this.emit("error", new TypeError("Unsupported protocol " + protocol));
  55076. return;
  55077. }
  55078. // If specified, use the agent corresponding to the protocol
  55079. // (HTTP and HTTPS use different types of agents)
  55080. if (this._options.agents) {
  55081. var scheme = protocol.slice(0, -1);
  55082. this._options.agent = this._options.agents[scheme];
  55083. }
  55084. // Create the native request
  55085. var request = this._currentRequest =
  55086. nativeProtocol.request(this._options, this._onNativeResponse);
  55087. this._currentUrl = url.format(this._options);
  55088. // Set up event handlers
  55089. request._redirectable = this;
  55090. for (var e = 0; e < events.length; e++) {
  55091. request.on(events[e], eventHandlers[events[e]]);
  55092. }
  55093. // End a redirected request
  55094. // (The first request must be ended explicitly with RedirectableRequest#end)
  55095. if (this._isRedirect) {
  55096. // Write the request entity and end.
  55097. var i = 0;
  55098. var self = this;
  55099. var buffers = this._requestBodyBuffers;
  55100. (function writeNext(error) {
  55101. // Only write if this request has not been redirected yet
  55102. /* istanbul ignore else */
  55103. if (request === self._currentRequest) {
  55104. // Report any write errors
  55105. /* istanbul ignore if */
  55106. if (error) {
  55107. self.emit("error", error);
  55108. }
  55109. // Write the next buffer if there are still left
  55110. else if (i < buffers.length) {
  55111. var buffer = buffers[i++];
  55112. /* istanbul ignore else */
  55113. if (!request.finished) {
  55114. request.write(buffer.data, buffer.encoding, writeNext);
  55115. }
  55116. }
  55117. // End the request if `end` has been called on us
  55118. else if (self._ended) {
  55119. request.end();
  55120. }
  55121. }
  55122. }());
  55123. }
  55124. };
  55125. // Processes a response from the current native request
  55126. RedirectableRequest.prototype._processResponse = function (response) {
  55127. // Store the redirected response
  55128. var statusCode = response.statusCode;
  55129. if (this._options.trackRedirects) {
  55130. this._redirects.push({
  55131. url: this._currentUrl,
  55132. headers: response.headers,
  55133. statusCode: statusCode,
  55134. });
  55135. }
  55136. // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
  55137. // that further action needs to be taken by the user agent in order to
  55138. // fulfill the request. If a Location header field is provided,
  55139. // the user agent MAY automatically redirect its request to the URI
  55140. // referenced by the Location field value,
  55141. // even if the specific status code is not understood.
  55142. // If the response is not a redirect; return it as-is
  55143. var location = response.headers.location;
  55144. if (!location || this._options.followRedirects === false ||
  55145. statusCode < 300 || statusCode >= 400) {
  55146. response.responseUrl = this._currentUrl;
  55147. response.redirects = this._redirects;
  55148. this.emit("response", response);
  55149. // Clean up
  55150. this._requestBodyBuffers = [];
  55151. return;
  55152. }
  55153. // The response is a redirect, so abort the current request
  55154. abortRequest(this._currentRequest);
  55155. // Discard the remainder of the response to avoid waiting for data
  55156. response.destroy();
  55157. // RFC7231§6.4: A client SHOULD detect and intervene
  55158. // in cyclical redirections (i.e., "infinite" redirection loops).
  55159. if (++this._redirectCount > this._options.maxRedirects) {
  55160. this.emit("error", new TooManyRedirectsError());
  55161. return;
  55162. }
  55163. // Store the request headers if applicable
  55164. var requestHeaders;
  55165. var beforeRedirect = this._options.beforeRedirect;
  55166. if (beforeRedirect) {
  55167. requestHeaders = Object.assign({
  55168. // The Host header was set by nativeProtocol.request
  55169. Host: response.req.getHeader("host"),
  55170. }, this._options.headers);
  55171. }
  55172. // RFC7231§6.4: Automatic redirection needs to done with
  55173. // care for methods not known to be safe, […]
  55174. // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
  55175. // the request method from POST to GET for the subsequent request.
  55176. var method = this._options.method;
  55177. if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
  55178. // RFC7231§6.4.4: The 303 (See Other) status code indicates that
  55179. // the server is redirecting the user agent to a different resource […]
  55180. // A user agent can perform a retrieval request targeting that URI
  55181. // (a GET or HEAD request if using HTTP) […]
  55182. (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
  55183. this._options.method = "GET";
  55184. // Drop a possible entity and headers related to it
  55185. this._requestBodyBuffers = [];
  55186. removeMatchingHeaders(/^content-/i, this._options.headers);
  55187. }
  55188. // Drop the Host header, as the redirect might lead to a different host
  55189. var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
  55190. // If the redirect is relative, carry over the host of the last request
  55191. var currentUrlParts = url.parse(this._currentUrl);
  55192. var currentHost = currentHostHeader || currentUrlParts.host;
  55193. var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
  55194. url.format(Object.assign(currentUrlParts, { host: currentHost }));
  55195. // Determine the URL of the redirection
  55196. var redirectUrl;
  55197. try {
  55198. redirectUrl = url.resolve(currentUrl, location);
  55199. }
  55200. catch (cause) {
  55201. this.emit("error", new RedirectionError(cause));
  55202. return;
  55203. }
  55204. // Create the redirected request
  55205. debug$2("redirecting to", redirectUrl);
  55206. this._isRedirect = true;
  55207. var redirectUrlParts = url.parse(redirectUrl);
  55208. Object.assign(this._options, redirectUrlParts);
  55209. // Drop confidential headers when redirecting to a less secure protocol
  55210. // or to a different domain that is not a superdomain
  55211. if (redirectUrlParts.protocol !== currentUrlParts.protocol &&
  55212. redirectUrlParts.protocol !== "https:" ||
  55213. redirectUrlParts.host !== currentHost &&
  55214. !isSubdomain(redirectUrlParts.host, currentHost)) {
  55215. removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
  55216. }
  55217. // Evaluate the beforeRedirect callback
  55218. if (typeof beforeRedirect === "function") {
  55219. var responseDetails = {
  55220. headers: response.headers,
  55221. statusCode: statusCode,
  55222. };
  55223. var requestDetails = {
  55224. url: currentUrl,
  55225. method: method,
  55226. headers: requestHeaders,
  55227. };
  55228. try {
  55229. beforeRedirect(this._options, responseDetails, requestDetails);
  55230. }
  55231. catch (err) {
  55232. this.emit("error", err);
  55233. return;
  55234. }
  55235. this._sanitizeOptions(this._options);
  55236. }
  55237. // Perform the redirected request
  55238. try {
  55239. this._performRequest();
  55240. }
  55241. catch (cause) {
  55242. this.emit("error", new RedirectionError(cause));
  55243. }
  55244. };
  55245. // Wraps the key/value object of protocols with redirect functionality
  55246. function wrap(protocols) {
  55247. // Default settings
  55248. var exports = {
  55249. maxRedirects: 21,
  55250. maxBodyLength: 10 * 1024 * 1024,
  55251. };
  55252. // Wrap each protocol
  55253. var nativeProtocols = {};
  55254. Object.keys(protocols).forEach(function (scheme) {
  55255. var protocol = scheme + ":";
  55256. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  55257. var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
  55258. // Executes a request, following redirects
  55259. function request(input, options, callback) {
  55260. // Parse parameters
  55261. if (typeof input === "string") {
  55262. var urlStr = input;
  55263. try {
  55264. input = urlToOptions(new URL$1(urlStr));
  55265. }
  55266. catch (err) {
  55267. /* istanbul ignore next */
  55268. input = url.parse(urlStr);
  55269. }
  55270. }
  55271. else if (URL$1 && (input instanceof URL$1)) {
  55272. input = urlToOptions(input);
  55273. }
  55274. else {
  55275. callback = options;
  55276. options = input;
  55277. input = { protocol: protocol };
  55278. }
  55279. if (typeof options === "function") {
  55280. callback = options;
  55281. options = null;
  55282. }
  55283. // Set defaults
  55284. options = Object.assign({
  55285. maxRedirects: exports.maxRedirects,
  55286. maxBodyLength: exports.maxBodyLength,
  55287. }, input, options);
  55288. options.nativeProtocols = nativeProtocols;
  55289. assert.equal(options.protocol, protocol, "protocol mismatch");
  55290. debug$2("options", options);
  55291. return new RedirectableRequest(options, callback);
  55292. }
  55293. // Executes a GET request, following redirects
  55294. function get(input, options, callback) {
  55295. var wrappedRequest = wrappedProtocol.request(input, options, callback);
  55296. wrappedRequest.end();
  55297. return wrappedRequest;
  55298. }
  55299. // Expose the properties on the wrapped protocol
  55300. Object.defineProperties(wrappedProtocol, {
  55301. request: { value: request, configurable: true, enumerable: true, writable: true },
  55302. get: { value: get, configurable: true, enumerable: true, writable: true },
  55303. });
  55304. });
  55305. return exports;
  55306. }
  55307. /* istanbul ignore next */
  55308. function noop$1() { /* empty */ }
  55309. // from https://github.com/nodejs/node/blob/master/lib/internal/url.js
  55310. function urlToOptions(urlObject) {
  55311. var options = {
  55312. protocol: urlObject.protocol,
  55313. hostname: urlObject.hostname.startsWith("[") ?
  55314. /* istanbul ignore next */
  55315. urlObject.hostname.slice(1, -1) :
  55316. urlObject.hostname,
  55317. hash: urlObject.hash,
  55318. search: urlObject.search,
  55319. pathname: urlObject.pathname,
  55320. path: urlObject.pathname + urlObject.search,
  55321. href: urlObject.href,
  55322. };
  55323. if (urlObject.port !== "") {
  55324. options.port = Number(urlObject.port);
  55325. }
  55326. return options;
  55327. }
  55328. function removeMatchingHeaders(regex, headers) {
  55329. var lastValue;
  55330. for (var header in headers) {
  55331. if (regex.test(header)) {
  55332. lastValue = headers[header];
  55333. delete headers[header];
  55334. }
  55335. }
  55336. return (lastValue === null || typeof lastValue === "undefined") ?
  55337. undefined : String(lastValue).trim();
  55338. }
  55339. function createErrorType(code, defaultMessage) {
  55340. function CustomError(cause) {
  55341. Error.captureStackTrace(this, this.constructor);
  55342. if (!cause) {
  55343. this.message = defaultMessage;
  55344. }
  55345. else {
  55346. this.message = defaultMessage + ": " + cause.message;
  55347. this.cause = cause;
  55348. }
  55349. }
  55350. CustomError.prototype = new Error();
  55351. CustomError.prototype.constructor = CustomError;
  55352. CustomError.prototype.name = "Error [" + code + "]";
  55353. CustomError.prototype.code = code;
  55354. return CustomError;
  55355. }
  55356. function abortRequest(request) {
  55357. for (var e = 0; e < events.length; e++) {
  55358. request.removeListener(events[e], eventHandlers[events[e]]);
  55359. }
  55360. request.on("error", noop$1);
  55361. request.abort();
  55362. }
  55363. function isSubdomain(subdomain, domain) {
  55364. const dot = subdomain.length - domain.length - 1;
  55365. return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
  55366. }
  55367. // Exports
  55368. followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
  55369. followRedirects$1.exports.wrap = wrap;
  55370. var followRedirectsExports = followRedirects$1.exports;
  55371. var httpNative = require$$1$1,
  55372. httpsNative = require$$1$2,
  55373. web_o = webOutgoing,
  55374. common$1 = common$3,
  55375. followRedirects = followRedirectsExports;
  55376. web_o = Object.keys(web_o).map(function(pass) {
  55377. return web_o[pass];
  55378. });
  55379. var nativeAgents = { http: httpNative, https: httpsNative };
  55380. /*!
  55381. * Array of passes.
  55382. *
  55383. * A `pass` is just a function that is executed on `req, res, options`
  55384. * so that you can easily add new checks while still keeping the base
  55385. * flexible.
  55386. */
  55387. var webIncoming = {
  55388. /**
  55389. * Sets `content-length` to '0' if request is of DELETE type.
  55390. *
  55391. * @param {ClientRequest} Req Request object
  55392. * @param {IncomingMessage} Res Response object
  55393. * @param {Object} Options Config object passed to the proxy
  55394. *
  55395. * @api private
  55396. */
  55397. deleteLength: function deleteLength(req, res, options) {
  55398. if((req.method === 'DELETE' || req.method === 'OPTIONS')
  55399. && !req.headers['content-length']) {
  55400. req.headers['content-length'] = '0';
  55401. delete req.headers['transfer-encoding'];
  55402. }
  55403. },
  55404. /**
  55405. * Sets timeout in request socket if it was specified in options.
  55406. *
  55407. * @param {ClientRequest} Req Request object
  55408. * @param {IncomingMessage} Res Response object
  55409. * @param {Object} Options Config object passed to the proxy
  55410. *
  55411. * @api private
  55412. */
  55413. timeout: function timeout(req, res, options) {
  55414. if(options.timeout) {
  55415. req.socket.setTimeout(options.timeout);
  55416. }
  55417. },
  55418. /**
  55419. * Sets `x-forwarded-*` headers if specified in config.
  55420. *
  55421. * @param {ClientRequest} Req Request object
  55422. * @param {IncomingMessage} Res Response object
  55423. * @param {Object} Options Config object passed to the proxy
  55424. *
  55425. * @api private
  55426. */
  55427. XHeaders: function XHeaders(req, res, options) {
  55428. if(!options.xfwd) return;
  55429. var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req);
  55430. var values = {
  55431. for : req.connection.remoteAddress || req.socket.remoteAddress,
  55432. port : common$1.getPort(req),
  55433. proto: encrypted ? 'https' : 'http'
  55434. };
  55435. ['for', 'port', 'proto'].forEach(function(header) {
  55436. req.headers['x-forwarded-' + header] =
  55437. (req.headers['x-forwarded-' + header] || '') +
  55438. (req.headers['x-forwarded-' + header] ? ',' : '') +
  55439. values[header];
  55440. });
  55441. req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';
  55442. },
  55443. /**
  55444. * Does the actual proxying. If `forward` is enabled fires up
  55445. * a ForwardStream, same happens for ProxyStream. The request
  55446. * just dies otherwise.
  55447. *
  55448. * @param {ClientRequest} Req Request object
  55449. * @param {IncomingMessage} Res Response object
  55450. * @param {Object} Options Config object passed to the proxy
  55451. *
  55452. * @api private
  55453. */
  55454. stream: function stream(req, res, options, _, server, clb) {
  55455. // And we begin!
  55456. server.emit('start', req, res, options.target || options.forward);
  55457. var agents = options.followRedirects ? followRedirects : nativeAgents;
  55458. var http = agents.http;
  55459. var https = agents.https;
  55460. if(options.forward) {
  55461. // If forward enable, so just pipe the request
  55462. var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
  55463. common$1.setupOutgoing(options.ssl || {}, options, req, 'forward')
  55464. );
  55465. // error handler (e.g. ECONNRESET, ECONNREFUSED)
  55466. // Handle errors on incoming request as well as it makes sense to
  55467. var forwardError = createErrorHandler(forwardReq, options.forward);
  55468. req.on('error', forwardError);
  55469. forwardReq.on('error', forwardError);
  55470. (options.buffer || req).pipe(forwardReq);
  55471. if(!options.target) { return res.end(); }
  55472. }
  55473. // Request initalization
  55474. var proxyReq = (options.target.protocol === 'https:' ? https : http).request(
  55475. common$1.setupOutgoing(options.ssl || {}, options, req)
  55476. );
  55477. // Enable developers to modify the proxyReq before headers are sent
  55478. proxyReq.on('socket', function(socket) {
  55479. if(server && !proxyReq.getHeader('expect')) {
  55480. server.emit('proxyReq', proxyReq, req, res, options);
  55481. }
  55482. });
  55483. // allow outgoing socket to timeout so that we could
  55484. // show an error page at the initial request
  55485. if(options.proxyTimeout) {
  55486. proxyReq.setTimeout(options.proxyTimeout, function() {
  55487. proxyReq.abort();
  55488. });
  55489. }
  55490. // Ensure we abort proxy if request is aborted
  55491. req.on('aborted', function () {
  55492. proxyReq.abort();
  55493. });
  55494. // handle errors in proxy and incoming request, just like for forward proxy
  55495. var proxyError = createErrorHandler(proxyReq, options.target);
  55496. req.on('error', proxyError);
  55497. proxyReq.on('error', proxyError);
  55498. function createErrorHandler(proxyReq, url) {
  55499. return function proxyError(err) {
  55500. if (req.socket.destroyed && err.code === 'ECONNRESET') {
  55501. server.emit('econnreset', err, req, res, url);
  55502. return proxyReq.abort();
  55503. }
  55504. if (clb) {
  55505. clb(err, req, res, url);
  55506. } else {
  55507. server.emit('error', err, req, res, url);
  55508. }
  55509. }
  55510. }
  55511. (options.buffer || req).pipe(proxyReq);
  55512. proxyReq.on('response', function(proxyRes) {
  55513. if(server) { server.emit('proxyRes', proxyRes, req, res); }
  55514. if(!res.headersSent && !options.selfHandleResponse) {
  55515. for(var i=0; i < web_o.length; i++) {
  55516. if(web_o[i](req, res, proxyRes, options)) { break; }
  55517. }
  55518. }
  55519. if (!res.finished) {
  55520. // Allow us to listen when the proxy has completed
  55521. proxyRes.on('end', function () {
  55522. if (server) server.emit('end', req, res, proxyRes);
  55523. });
  55524. // We pipe to the response unless its expected to be handled by the user
  55525. if (!options.selfHandleResponse) proxyRes.pipe(res);
  55526. } else {
  55527. if (server) server.emit('end', req, res, proxyRes);
  55528. }
  55529. });
  55530. }
  55531. };
  55532. var http = require$$1$1,
  55533. https = require$$1$2,
  55534. common = common$3;
  55535. /*!
  55536. * Array of passes.
  55537. *
  55538. * A `pass` is just a function that is executed on `req, socket, options`
  55539. * so that you can easily add new checks while still keeping the base
  55540. * flexible.
  55541. */
  55542. /*
  55543. * Websockets Passes
  55544. *
  55545. */
  55546. var wsIncoming = {
  55547. /**
  55548. * WebSocket requests must have the `GET` method and
  55549. * the `upgrade:websocket` header
  55550. *
  55551. * @param {ClientRequest} Req Request object
  55552. * @param {Socket} Websocket
  55553. *
  55554. * @api private
  55555. */
  55556. checkMethodAndHeader : function checkMethodAndHeader(req, socket) {
  55557. if (req.method !== 'GET' || !req.headers.upgrade) {
  55558. socket.destroy();
  55559. return true;
  55560. }
  55561. if (req.headers.upgrade.toLowerCase() !== 'websocket') {
  55562. socket.destroy();
  55563. return true;
  55564. }
  55565. },
  55566. /**
  55567. * Sets `x-forwarded-*` headers if specified in config.
  55568. *
  55569. * @param {ClientRequest} Req Request object
  55570. * @param {Socket} Websocket
  55571. * @param {Object} Options Config object passed to the proxy
  55572. *
  55573. * @api private
  55574. */
  55575. XHeaders : function XHeaders(req, socket, options) {
  55576. if(!options.xfwd) return;
  55577. var values = {
  55578. for : req.connection.remoteAddress || req.socket.remoteAddress,
  55579. port : common.getPort(req),
  55580. proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws'
  55581. };
  55582. ['for', 'port', 'proto'].forEach(function(header) {
  55583. req.headers['x-forwarded-' + header] =
  55584. (req.headers['x-forwarded-' + header] || '') +
  55585. (req.headers['x-forwarded-' + header] ? ',' : '') +
  55586. values[header];
  55587. });
  55588. },
  55589. /**
  55590. * Does the actual proxying. Make the request and upgrade it
  55591. * send the Switching Protocols request and pipe the sockets.
  55592. *
  55593. * @param {ClientRequest} Req Request object
  55594. * @param {Socket} Websocket
  55595. * @param {Object} Options Config object passed to the proxy
  55596. *
  55597. * @api private
  55598. */
  55599. stream : function stream(req, socket, options, head, server, clb) {
  55600. var createHttpHeader = function(line, headers) {
  55601. return Object.keys(headers).reduce(function (head, key) {
  55602. var value = headers[key];
  55603. if (!Array.isArray(value)) {
  55604. head.push(key + ': ' + value);
  55605. return head;
  55606. }
  55607. for (var i = 0; i < value.length; i++) {
  55608. head.push(key + ': ' + value[i]);
  55609. }
  55610. return head;
  55611. }, [line])
  55612. .join('\r\n') + '\r\n\r\n';
  55613. };
  55614. common.setupSocket(socket);
  55615. if (head && head.length) socket.unshift(head);
  55616. var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request(
  55617. common.setupOutgoing(options.ssl || {}, options, req)
  55618. );
  55619. // Enable developers to modify the proxyReq before headers are sent
  55620. if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }
  55621. // Error Handler
  55622. proxyReq.on('error', onOutgoingError);
  55623. proxyReq.on('response', function (res) {
  55624. // if upgrade event isn't going to happen, close the socket
  55625. if (!res.upgrade) {
  55626. socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
  55627. res.pipe(socket);
  55628. }
  55629. });
  55630. proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
  55631. proxySocket.on('error', onOutgoingError);
  55632. // Allow us to listen when the websocket has completed
  55633. proxySocket.on('end', function () {
  55634. server.emit('close', proxyRes, proxySocket, proxyHead);
  55635. });
  55636. // The pipe below will end proxySocket if socket closes cleanly, but not
  55637. // if it errors (eg, vanishes from the net and starts returning
  55638. // EHOSTUNREACH). We need to do that explicitly.
  55639. socket.on('error', function () {
  55640. proxySocket.end();
  55641. });
  55642. common.setupSocket(proxySocket);
  55643. if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
  55644. //
  55645. // Remark: Handle writing the headers to the socket when switching protocols
  55646. // Also handles when a header is an array
  55647. //
  55648. socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
  55649. proxySocket.pipe(socket).pipe(proxySocket);
  55650. server.emit('open', proxySocket);
  55651. server.emit('proxySocket', proxySocket); //DEPRECATED.
  55652. });
  55653. return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
  55654. function onOutgoingError(err) {
  55655. if (clb) {
  55656. clb(err, req, socket);
  55657. } else {
  55658. server.emit('error', err, req, socket);
  55659. }
  55660. socket.end();
  55661. }
  55662. }
  55663. };
  55664. (function (module) {
  55665. var httpProxy = module.exports,
  55666. extend = require$$0$6._extend,
  55667. parse_url = require$$0$9.parse,
  55668. EE3 = eventemitter3Exports,
  55669. http = require$$1$1,
  55670. https = require$$1$2,
  55671. web = webIncoming,
  55672. ws = wsIncoming;
  55673. httpProxy.Server = ProxyServer;
  55674. /**
  55675. * Returns a function that creates the loader for
  55676. * either `ws` or `web`'s passes.
  55677. *
  55678. * Examples:
  55679. *
  55680. * httpProxy.createRightProxy('ws')
  55681. * // => [Function]
  55682. *
  55683. * @param {String} Type Either 'ws' or 'web'
  55684. * @return {Function} Loader Function that when called returns an iterator for the right passes
  55685. *
  55686. * @api private
  55687. */
  55688. function createRightProxy(type) {
  55689. return function(options) {
  55690. return function(req, res /*, [head], [opts] */) {
  55691. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  55692. args = [].slice.call(arguments),
  55693. cntr = args.length - 1,
  55694. head, cbl;
  55695. /* optional args parse begin */
  55696. if(typeof args[cntr] === 'function') {
  55697. cbl = args[cntr];
  55698. cntr--;
  55699. }
  55700. var requestOptions = options;
  55701. if(
  55702. !(args[cntr] instanceof Buffer) &&
  55703. args[cntr] !== res
  55704. ) {
  55705. //Copy global options
  55706. requestOptions = extend({}, options);
  55707. //Overwrite with request options
  55708. extend(requestOptions, args[cntr]);
  55709. cntr--;
  55710. }
  55711. if(args[cntr] instanceof Buffer) {
  55712. head = args[cntr];
  55713. }
  55714. /* optional args parse end */
  55715. ['target', 'forward'].forEach(function(e) {
  55716. if (typeof requestOptions[e] === 'string')
  55717. requestOptions[e] = parse_url(requestOptions[e]);
  55718. });
  55719. if (!requestOptions.target && !requestOptions.forward) {
  55720. return this.emit('error', new Error('Must provide a proper URL as target'));
  55721. }
  55722. for(var i=0; i < passes.length; i++) {
  55723. /**
  55724. * Call of passes functions
  55725. * pass(req, res, options, head)
  55726. *
  55727. * In WebSockets case the `res` variable
  55728. * refer to the connection socket
  55729. * pass(req, socket, options, head)
  55730. */
  55731. if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop
  55732. break;
  55733. }
  55734. }
  55735. };
  55736. };
  55737. }
  55738. httpProxy.createRightProxy = createRightProxy;
  55739. function ProxyServer(options) {
  55740. EE3.call(this);
  55741. options = options || {};
  55742. options.prependPath = options.prependPath === false ? false : true;
  55743. this.web = this.proxyRequest = createRightProxy('web')(options);
  55744. this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
  55745. this.options = options;
  55746. this.webPasses = Object.keys(web).map(function(pass) {
  55747. return web[pass];
  55748. });
  55749. this.wsPasses = Object.keys(ws).map(function(pass) {
  55750. return ws[pass];
  55751. });
  55752. this.on('error', this.onError, this);
  55753. }
  55754. require$$0$6.inherits(ProxyServer, EE3);
  55755. ProxyServer.prototype.onError = function (err) {
  55756. //
  55757. // Remark: Replicate node core behavior using EE3
  55758. // so we force people to handle their own errors
  55759. //
  55760. if(this.listeners('error').length === 1) {
  55761. throw err;
  55762. }
  55763. };
  55764. ProxyServer.prototype.listen = function(port, hostname) {
  55765. var self = this,
  55766. closure = function(req, res) { self.web(req, res); };
  55767. this._server = this.options.ssl ?
  55768. https.createServer(this.options.ssl, closure) :
  55769. http.createServer(closure);
  55770. if(this.options.ws) {
  55771. this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); });
  55772. }
  55773. this._server.listen(port, hostname);
  55774. return this;
  55775. };
  55776. ProxyServer.prototype.close = function(callback) {
  55777. var self = this;
  55778. if (this._server) {
  55779. this._server.close(done);
  55780. }
  55781. // Wrap callback to nullify server after all open connections are closed.
  55782. function done() {
  55783. self._server = null;
  55784. if (callback) {
  55785. callback.apply(null, arguments);
  55786. }
  55787. } };
  55788. ProxyServer.prototype.before = function(type, passName, callback) {
  55789. if (type !== 'ws' && type !== 'web') {
  55790. throw new Error('type must be `web` or `ws`');
  55791. }
  55792. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  55793. i = false;
  55794. passes.forEach(function(v, idx) {
  55795. if(v.name === passName) i = idx;
  55796. });
  55797. if(i === false) throw new Error('No such pass');
  55798. passes.splice(i, 0, callback);
  55799. };
  55800. ProxyServer.prototype.after = function(type, passName, callback) {
  55801. if (type !== 'ws' && type !== 'web') {
  55802. throw new Error('type must be `web` or `ws`');
  55803. }
  55804. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  55805. i = false;
  55806. passes.forEach(function(v, idx) {
  55807. if(v.name === passName) i = idx;
  55808. });
  55809. if(i === false) throw new Error('No such pass');
  55810. passes.splice(i++, 0, callback);
  55811. };
  55812. } (httpProxy$3));
  55813. var httpProxyExports = httpProxy$3.exports;
  55814. // Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!)
  55815. var ProxyServer = httpProxyExports.Server;
  55816. /**
  55817. * Creates the proxy server.
  55818. *
  55819. * Examples:
  55820. *
  55821. * httpProxy.createProxyServer({ .. }, 8000)
  55822. * // => '{ web: [Function], ws: [Function] ... }'
  55823. *
  55824. * @param {Object} Options Config object passed to the proxy
  55825. *
  55826. * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
  55827. *
  55828. * @api public
  55829. */
  55830. function createProxyServer(options) {
  55831. /*
  55832. * `options` is needed and it must have the following layout:
  55833. *
  55834. * {
  55835. * target : <url string to be parsed with the url module>
  55836. * forward: <url string to be parsed with the url module>
  55837. * agent : <object to be passed to http(s).request>
  55838. * ssl : <object to be passed to https.createServer()>
  55839. * ws : <true/false, if you want to proxy websockets>
  55840. * xfwd : <true/false, adds x-forward headers>
  55841. * secure : <true/false, verify SSL certificate>
  55842. * toProxy: <true/false, explicitly specify if we are proxying to another proxy>
  55843. * prependPath: <true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
  55844. * ignorePath: <true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
  55845. * localAddress : <Local interface string to bind for outgoing connections>
  55846. * changeOrigin: <true/false, Default: false - changes the origin of the host header to the target URL>
  55847. * preserveHeaderKeyCase: <true/false, Default: false - specify whether you want to keep letter case of response header key >
  55848. * auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
  55849. * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.
  55850. * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
  55851. * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
  55852. * }
  55853. *
  55854. * NOTE: `options.ws` and `options.ssl` are optional.
  55855. * `options.target and `options.forward` cannot be
  55856. * both missing
  55857. * }
  55858. */
  55859. return new ProxyServer(options);
  55860. }
  55861. ProxyServer.createProxyServer = createProxyServer;
  55862. ProxyServer.createServer = createProxyServer;
  55863. ProxyServer.createProxy = createProxyServer;
  55864. /**
  55865. * Export the proxy "Server" as the main export.
  55866. */
  55867. var httpProxy$2 = ProxyServer;
  55868. /*!
  55869. * Caron dimonio, con occhi di bragia
  55870. * loro accennando, tutte le raccoglie;
  55871. * batte col remo qualunque s’adagia
  55872. *
  55873. * Charon the demon, with the eyes of glede,
  55874. * Beckoning to them, collects them all together,
  55875. * Beats with his oar whoever lags behind
  55876. *
  55877. * Dante - The Divine Comedy (Canto III)
  55878. */
  55879. var httpProxy = httpProxy$2;
  55880. var httpProxy$1 = /*@__PURE__*/getDefaultExportFromCjs(httpProxy);
  55881. const debug$1 = createDebugger('vite:proxy');
  55882. function proxyMiddleware(httpServer, options, config) {
  55883. // lazy require only when proxy is used
  55884. const proxies = {};
  55885. Object.keys(options).forEach((context) => {
  55886. let opts = options[context];
  55887. if (!opts) {
  55888. return;
  55889. }
  55890. if (typeof opts === 'string') {
  55891. opts = { target: opts, changeOrigin: true };
  55892. }
  55893. const proxy = httpProxy$1.createProxyServer(opts);
  55894. if (opts.configure) {
  55895. opts.configure(proxy, opts);
  55896. }
  55897. proxy.on('error', (err, req, originalRes) => {
  55898. // When it is ws proxy, res is net.Socket
  55899. const res = originalRes;
  55900. if ('req' in res) {
  55901. config.logger.error(`${colors$1.red(`http proxy error at ${originalRes.req.url}:`)}\n${err.stack}`, {
  55902. timestamp: true,
  55903. error: err,
  55904. });
  55905. if (!res.headersSent && !res.writableEnded) {
  55906. res
  55907. .writeHead(500, {
  55908. 'Content-Type': 'text/plain',
  55909. })
  55910. .end();
  55911. }
  55912. }
  55913. else {
  55914. config.logger.error(`${colors$1.red(`ws proxy error:`)}\n${err.stack}`, {
  55915. timestamp: true,
  55916. error: err,
  55917. });
  55918. res.end();
  55919. }
  55920. });
  55921. // clone before saving because http-proxy mutates the options
  55922. proxies[context] = [proxy, { ...opts }];
  55923. });
  55924. if (httpServer) {
  55925. httpServer.on('upgrade', (req, socket, head) => {
  55926. const url = req.url;
  55927. for (const context in proxies) {
  55928. if (doesProxyContextMatchUrl(context, url)) {
  55929. const [proxy, opts] = proxies[context];
  55930. if ((opts.ws ||
  55931. opts.target?.toString().startsWith('ws:') ||
  55932. opts.target?.toString().startsWith('wss:')) &&
  55933. req.headers['sec-websocket-protocol'] !== HMR_HEADER) {
  55934. if (opts.rewrite) {
  55935. req.url = opts.rewrite(url);
  55936. }
  55937. debug$1?.(`${req.url} -> ws ${opts.target}`);
  55938. proxy.ws(req, socket, head);
  55939. return;
  55940. }
  55941. }
  55942. }
  55943. });
  55944. }
  55945. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  55946. return function viteProxyMiddleware(req, res, next) {
  55947. const url = req.url;
  55948. for (const context in proxies) {
  55949. if (doesProxyContextMatchUrl(context, url)) {
  55950. const [proxy, opts] = proxies[context];
  55951. const options = {};
  55952. if (opts.bypass) {
  55953. const bypassResult = opts.bypass(req, res, opts);
  55954. if (typeof bypassResult === 'string') {
  55955. req.url = bypassResult;
  55956. debug$1?.(`bypass: ${req.url} -> ${bypassResult}`);
  55957. return next();
  55958. }
  55959. else if (bypassResult === false) {
  55960. debug$1?.(`bypass: ${req.url} -> 404`);
  55961. return res.end(404);
  55962. }
  55963. }
  55964. debug$1?.(`${req.url} -> ${opts.target || opts.forward}`);
  55965. if (opts.rewrite) {
  55966. req.url = opts.rewrite(req.url);
  55967. }
  55968. proxy.web(req, res, options);
  55969. return;
  55970. }
  55971. }
  55972. next();
  55973. };
  55974. }
  55975. function doesProxyContextMatchUrl(context, url) {
  55976. return ((context[0] === '^' && new RegExp(context).test(url)) ||
  55977. url.startsWith(context));
  55978. }
  55979. var lib = {exports: {}};
  55980. (function (module, exports) {
  55981. var url = require$$0$9;
  55982. module.exports = function historyApiFallback(options) {
  55983. options = options || {};
  55984. var logger = getLogger(options);
  55985. return function(req, res, next) {
  55986. var headers = req.headers;
  55987. if (req.method !== 'GET' && req.method !== 'HEAD') {
  55988. logger(
  55989. 'Not rewriting',
  55990. req.method,
  55991. req.url,
  55992. 'because the method is not GET or HEAD.'
  55993. );
  55994. return next();
  55995. } else if (!headers || typeof headers.accept !== 'string') {
  55996. logger(
  55997. 'Not rewriting',
  55998. req.method,
  55999. req.url,
  56000. 'because the client did not send an HTTP accept header.'
  56001. );
  56002. return next();
  56003. } else if (headers.accept.indexOf('application/json') === 0) {
  56004. logger(
  56005. 'Not rewriting',
  56006. req.method,
  56007. req.url,
  56008. 'because the client prefers JSON.'
  56009. );
  56010. return next();
  56011. } else if (!acceptsHtml(headers.accept, options)) {
  56012. logger(
  56013. 'Not rewriting',
  56014. req.method,
  56015. req.url,
  56016. 'because the client does not accept HTML.'
  56017. );
  56018. return next();
  56019. }
  56020. var parsedUrl = url.parse(req.url);
  56021. var rewriteTarget;
  56022. options.rewrites = options.rewrites || [];
  56023. for (var i = 0; i < options.rewrites.length; i++) {
  56024. var rewrite = options.rewrites[i];
  56025. var match = parsedUrl.pathname.match(rewrite.from);
  56026. if (match !== null) {
  56027. rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req);
  56028. if(rewriteTarget.charAt(0) !== '/') {
  56029. logger(
  56030. 'We recommend using an absolute path for the rewrite target.',
  56031. 'Received a non-absolute rewrite target',
  56032. rewriteTarget,
  56033. 'for URL',
  56034. req.url
  56035. );
  56036. }
  56037. logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
  56038. req.url = rewriteTarget;
  56039. return next();
  56040. }
  56041. }
  56042. var pathname = parsedUrl.pathname;
  56043. if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') &&
  56044. options.disableDotRule !== true) {
  56045. logger(
  56046. 'Not rewriting',
  56047. req.method,
  56048. req.url,
  56049. 'because the path includes a dot (.) character.'
  56050. );
  56051. return next();
  56052. }
  56053. rewriteTarget = options.index || '/index.html';
  56054. logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
  56055. req.url = rewriteTarget;
  56056. next();
  56057. };
  56058. };
  56059. function evaluateRewriteRule(parsedUrl, match, rule, req) {
  56060. if (typeof rule === 'string') {
  56061. return rule;
  56062. } else if (typeof rule !== 'function') {
  56063. throw new Error('Rewrite rule can only be of type string or function.');
  56064. }
  56065. return rule({
  56066. parsedUrl: parsedUrl,
  56067. match: match,
  56068. request: req
  56069. });
  56070. }
  56071. function acceptsHtml(header, options) {
  56072. options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*'];
  56073. for (var i = 0; i < options.htmlAcceptHeaders.length; i++) {
  56074. if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) {
  56075. return true;
  56076. }
  56077. }
  56078. return false;
  56079. }
  56080. function getLogger(options) {
  56081. if (options && options.logger) {
  56082. return options.logger;
  56083. } else if (options && options.verbose) {
  56084. // eslint-disable-next-line no-console
  56085. return console.log.bind(console);
  56086. }
  56087. return function(){};
  56088. }
  56089. } (lib));
  56090. var libExports = lib.exports;
  56091. var history = /*@__PURE__*/getDefaultExportFromCjs(libExports);
  56092. function htmlFallbackMiddleware(root, spaFallback) {
  56093. const historyHtmlFallbackMiddleware = history({
  56094. logger: createDebugger('vite:html-fallback'),
  56095. // support /dir/ without explicit index.html
  56096. rewrites: [
  56097. {
  56098. from: /\/$/,
  56099. to({ parsedUrl, request }) {
  56100. const rewritten = decodeURIComponent(parsedUrl.pathname) + 'index.html';
  56101. if (fs$l.existsSync(path$o.join(root, rewritten))) {
  56102. return rewritten;
  56103. }
  56104. return spaFallback ? `/index.html` : request.url;
  56105. },
  56106. },
  56107. ],
  56108. });
  56109. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  56110. return function viteHtmlFallbackMiddleware(req, res, next) {
  56111. return historyHtmlFallbackMiddleware(req, res, next);
  56112. };
  56113. }
  56114. const debugCache = createDebugger('vite:cache');
  56115. const knownIgnoreList = new Set(['/', '/favicon.ico']);
  56116. function transformMiddleware(server) {
  56117. const { config: { root, logger }, moduleGraph, } = server;
  56118. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  56119. return async function viteTransformMiddleware(req, res, next) {
  56120. if (req.method !== 'GET' || knownIgnoreList.has(req.url)) {
  56121. return next();
  56122. }
  56123. let url;
  56124. try {
  56125. url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, '\0');
  56126. }
  56127. catch (e) {
  56128. return next(e);
  56129. }
  56130. const withoutQuery = cleanUrl(url);
  56131. try {
  56132. const isSourceMap = withoutQuery.endsWith('.map');
  56133. // since we generate source map references, handle those requests here
  56134. if (isSourceMap) {
  56135. const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr
  56136. if (depsOptimizer?.isOptimizedDepUrl(url)) {
  56137. // If the browser is requesting a source map for an optimized dep, it
  56138. // means that the dependency has already been pre-bundled and loaded
  56139. const sourcemapPath = url.startsWith(FS_PREFIX)
  56140. ? fsPathFromId(url)
  56141. : normalizePath$3(path$o.resolve(root, url.slice(1)));
  56142. try {
  56143. const map = JSON.parse(await fsp.readFile(sourcemapPath, 'utf-8'));
  56144. applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, logger);
  56145. return send$2(req, res, JSON.stringify(map), 'json', {
  56146. headers: server.config.server.headers,
  56147. });
  56148. }
  56149. catch (e) {
  56150. // Outdated source map request for optimized deps, this isn't an error
  56151. // but part of the normal flow when re-optimizing after missing deps
  56152. // Send back an empty source map so the browser doesn't issue warnings
  56153. const dummySourceMap = {
  56154. version: 3,
  56155. file: sourcemapPath.replace(/\.map$/, ''),
  56156. sources: [],
  56157. sourcesContent: [],
  56158. names: [],
  56159. mappings: ';;;;;;;;;',
  56160. };
  56161. return send$2(req, res, JSON.stringify(dummySourceMap), 'json', {
  56162. cacheControl: 'no-cache',
  56163. headers: server.config.server.headers,
  56164. });
  56165. }
  56166. }
  56167. else {
  56168. const originalUrl = url.replace(/\.map($|\?)/, '$1');
  56169. const map = (await moduleGraph.getModuleByUrl(originalUrl, false))
  56170. ?.transformResult?.map;
  56171. if (map) {
  56172. return send$2(req, res, JSON.stringify(map), 'json', {
  56173. headers: server.config.server.headers,
  56174. });
  56175. }
  56176. else {
  56177. return next();
  56178. }
  56179. }
  56180. }
  56181. // check if public dir is inside root dir
  56182. const publicDir = normalizePath$3(server.config.publicDir);
  56183. const rootDir = normalizePath$3(server.config.root);
  56184. if (publicDir.startsWith(rootDir)) {
  56185. const publicPath = `${publicDir.slice(rootDir.length)}/`;
  56186. // warn explicit public paths
  56187. if (url.startsWith(publicPath)) {
  56188. let warning;
  56189. if (isImportRequest(url)) {
  56190. const rawUrl = removeImportQuery(url);
  56191. warning =
  56192. 'Assets in public cannot be imported from JavaScript.\n' +
  56193. `Instead of ${colors$1.cyan(rawUrl)}, put the file in the src directory, and use ${colors$1.cyan(rawUrl.replace(publicPath, '/src/'))} instead.`;
  56194. }
  56195. else {
  56196. warning =
  56197. `files in the public directory are served at the root path.\n` +
  56198. `Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(url.replace(publicPath, '/'))}.`;
  56199. }
  56200. logger.warn(colors$1.yellow(warning));
  56201. }
  56202. }
  56203. if (isJSRequest(url) ||
  56204. isImportRequest(url) ||
  56205. isCSSRequest(url) ||
  56206. isHTMLProxy(url)) {
  56207. // strip ?import
  56208. url = removeImportQuery(url);
  56209. // Strip valid id prefix. This is prepended to resolved Ids that are
  56210. // not valid browser import specifiers by the importAnalysis plugin.
  56211. url = unwrapId(url);
  56212. // for CSS, we need to differentiate between normal CSS requests and
  56213. // imports
  56214. if (isCSSRequest(url) &&
  56215. !isDirectRequest(url) &&
  56216. req.headers.accept?.includes('text/css')) {
  56217. url = injectQuery(url, 'direct');
  56218. }
  56219. // check if we can return 304 early
  56220. const ifNoneMatch = req.headers['if-none-match'];
  56221. if (ifNoneMatch &&
  56222. (await moduleGraph.getModuleByUrl(url, false))?.transformResult
  56223. ?.etag === ifNoneMatch) {
  56224. debugCache?.(`[304] ${prettifyUrl(url, root)}`);
  56225. res.statusCode = 304;
  56226. return res.end();
  56227. }
  56228. // resolve, load and transform using the plugin container
  56229. const result = await transformRequest(url, server, {
  56230. html: req.headers.accept?.includes('text/html'),
  56231. });
  56232. if (result) {
  56233. const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr
  56234. const type = isDirectCSSRequest(url) ? 'css' : 'js';
  56235. const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
  56236. return send$2(req, res, result.code, type, {
  56237. etag: result.etag,
  56238. // allow browser to cache npm deps!
  56239. cacheControl: isDep ? 'max-age=31536000,immutable' : 'no-cache',
  56240. headers: server.config.server.headers,
  56241. map: result.map,
  56242. });
  56243. }
  56244. }
  56245. }
  56246. catch (e) {
  56247. if (e?.code === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) {
  56248. // Skip if response has already been sent
  56249. if (!res.writableEnded) {
  56250. res.statusCode = 504; // status code request timeout
  56251. res.statusMessage = 'Optimize Deps Processing Error';
  56252. res.end();
  56253. }
  56254. // This timeout is unexpected
  56255. logger.error(e.message);
  56256. return;
  56257. }
  56258. if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
  56259. // Skip if response has already been sent
  56260. if (!res.writableEnded) {
  56261. res.statusCode = 504; // status code request timeout
  56262. res.statusMessage = 'Outdated Optimize Dep';
  56263. res.end();
  56264. }
  56265. // We don't need to log an error in this case, the request
  56266. // is outdated because new dependencies were discovered and
  56267. // the new pre-bundle dependencies have changed.
  56268. // A full-page reload has been issued, and these old requests
  56269. // can't be properly fulfilled. This isn't an unexpected
  56270. // error but a normal part of the missing deps discovery flow
  56271. return;
  56272. }
  56273. if (e?.code === ERR_LOAD_URL) {
  56274. // Let other middleware handle if we can't load the url via transformRequest
  56275. return next();
  56276. }
  56277. return next(e);
  56278. }
  56279. next();
  56280. };
  56281. }
  56282. function createDevHtmlTransformFn(server) {
  56283. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(server.config.plugins);
  56284. return (url, html, originalUrl) => {
  56285. return applyHtmlTransforms(html, [
  56286. preImportMapHook(server.config),
  56287. ...preHooks,
  56288. htmlEnvHook(server.config),
  56289. devHtmlHook,
  56290. ...normalHooks,
  56291. ...postHooks,
  56292. postImportMapHook(),
  56293. ], {
  56294. path: url,
  56295. filename: getHtmlFilename(url, server),
  56296. server,
  56297. originalUrl,
  56298. });
  56299. };
  56300. }
  56301. function getHtmlFilename(url, server) {
  56302. if (url.startsWith(FS_PREFIX)) {
  56303. return decodeURIComponent(fsPathFromId(url));
  56304. }
  56305. else {
  56306. return decodeURIComponent(normalizePath$3(path$o.join(server.config.root, url.slice(1))));
  56307. }
  56308. }
  56309. const processNodeUrl = (attr, sourceCodeLocation, s, config, htmlPath, originalUrl, server) => {
  56310. let url = attr.value || '';
  56311. if (server?.moduleGraph) {
  56312. const mod = server.moduleGraph.urlToModuleMap.get(url);
  56313. if (mod && mod.lastHMRTimestamp > 0) {
  56314. url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  56315. }
  56316. }
  56317. const devBase = config.base;
  56318. if (url[0] === '/' && url[1] !== '/') {
  56319. // prefix with base (dev only, base is never relative)
  56320. const fullUrl = path$o.posix.join(devBase, url);
  56321. overwriteAttrValue(s, sourceCodeLocation, fullUrl);
  56322. if (server && !checkPublicFile(url, config)) {
  56323. preTransformRequest(server, fullUrl, devBase);
  56324. }
  56325. }
  56326. else if (url[0] === '.' &&
  56327. originalUrl &&
  56328. originalUrl !== '/' &&
  56329. htmlPath === '/index.html') {
  56330. // prefix with base (dev only, base is never relative)
  56331. const replacer = (url) => {
  56332. const fullUrl = path$o.posix.join(devBase, url);
  56333. if (server && !checkPublicFile(url, config)) {
  56334. preTransformRequest(server, fullUrl, devBase);
  56335. }
  56336. return fullUrl;
  56337. };
  56338. // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
  56339. // path will add `/a/` prefix, it will caused 404.
  56340. // rewrite before `./index.js` -> `localhost:5173/a/index.js`.
  56341. // rewrite after `../index.js` -> `localhost:5173/index.js`.
  56342. const processedUrl = attr.name === 'srcset' && attr.prefix === undefined
  56343. ? processSrcSetSync(url, ({ url }) => replacer(url))
  56344. : replacer(url);
  56345. overwriteAttrValue(s, sourceCodeLocation, processedUrl);
  56346. }
  56347. };
  56348. const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
  56349. const { config, moduleGraph, watcher } = server;
  56350. const base = config.base || '/';
  56351. let proxyModulePath;
  56352. let proxyModuleUrl;
  56353. const trailingSlash = htmlPath.endsWith('/');
  56354. if (!trailingSlash && fs$l.existsSync(filename)) {
  56355. proxyModulePath = htmlPath;
  56356. proxyModuleUrl = joinUrlSegments(base, htmlPath);
  56357. }
  56358. else {
  56359. // There are users of vite.transformIndexHtml calling it with url '/'
  56360. // for SSR integrations #7993, filename is root for this case
  56361. // A user may also use a valid name for a virtual html file
  56362. // Mark the path as virtual in both cases so sourcemaps aren't processed
  56363. // and ids are properly handled
  56364. const validPath = `${htmlPath}${trailingSlash ? 'index.html' : ''}`;
  56365. proxyModulePath = `\0${validPath}`;
  56366. proxyModuleUrl = wrapId(proxyModulePath);
  56367. }
  56368. const s = new MagicString(html);
  56369. let inlineModuleIndex = -1;
  56370. const proxyCacheUrl = cleanUrl(proxyModulePath).replace(normalizePath$3(config.root), '');
  56371. const styleUrl = [];
  56372. const addInlineModule = (node, ext) => {
  56373. inlineModuleIndex++;
  56374. const contentNode = node.childNodes[0];
  56375. const code = contentNode.value;
  56376. let map;
  56377. if (proxyModulePath[0] !== '\0') {
  56378. map = new MagicString(html)
  56379. .snip(contentNode.sourceCodeLocation.startOffset, contentNode.sourceCodeLocation.endOffset)
  56380. .generateMap({ hires: true });
  56381. map.sources = [filename];
  56382. map.file = filename;
  56383. }
  56384. // add HTML Proxy to Map
  56385. addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, { code, map });
  56386. // inline js module. convert to src="proxy" (dev only, base is never relative)
  56387. const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
  56388. // invalidate the module so the newly cached contents will be served
  56389. const module = server?.moduleGraph.getModuleById(modulePath);
  56390. if (module) {
  56391. server?.moduleGraph.invalidateModule(module);
  56392. }
  56393. s.update(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset, `<script type="module" src="${modulePath}"></script>`);
  56394. preTransformRequest(server, modulePath, base);
  56395. };
  56396. await traverseHtml(html, filename, (node) => {
  56397. if (!nodeIsElement(node)) {
  56398. return;
  56399. }
  56400. // script tags
  56401. if (node.nodeName === 'script') {
  56402. const { src, sourceCodeLocation, isModule } = getScriptInfo(node);
  56403. if (src) {
  56404. processNodeUrl(src, sourceCodeLocation, s, config, htmlPath, originalUrl, server);
  56405. }
  56406. else if (isModule && node.childNodes.length) {
  56407. addInlineModule(node, 'js');
  56408. }
  56409. }
  56410. if (node.nodeName === 'style' && node.childNodes.length) {
  56411. const children = node.childNodes[0];
  56412. styleUrl.push({
  56413. start: children.sourceCodeLocation.startOffset,
  56414. end: children.sourceCodeLocation.endOffset,
  56415. code: children.value,
  56416. });
  56417. }
  56418. // elements with [href/src] attrs
  56419. const assetAttrs = assetAttrsConfig[node.nodeName];
  56420. if (assetAttrs) {
  56421. for (const p of node.attrs) {
  56422. const attrKey = getAttrKey(p);
  56423. if (p.value && assetAttrs.includes(attrKey)) {
  56424. processNodeUrl(p, node.sourceCodeLocation.attrs[attrKey], s, config, htmlPath, originalUrl);
  56425. }
  56426. }
  56427. }
  56428. });
  56429. await Promise.all(styleUrl.map(async ({ start, end, code }, index) => {
  56430. const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
  56431. // ensure module in graph after successful load
  56432. const mod = await moduleGraph.ensureEntryFromUrl(url, false);
  56433. ensureWatchedFile(watcher, mod.file, config.root);
  56434. const result = await server.pluginContainer.transform(code, mod.id);
  56435. s.overwrite(start, end, result?.code || '');
  56436. }));
  56437. html = s.toString();
  56438. return {
  56439. html,
  56440. tags: [
  56441. {
  56442. tag: 'script',
  56443. attrs: {
  56444. type: 'module',
  56445. src: path$o.posix.join(base, CLIENT_PUBLIC_PATH),
  56446. },
  56447. injectTo: 'head-prepend',
  56448. },
  56449. ],
  56450. };
  56451. };
  56452. function indexHtmlMiddleware(server) {
  56453. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  56454. return async function viteIndexHtmlMiddleware(req, res, next) {
  56455. if (res.writableEnded) {
  56456. return next();
  56457. }
  56458. const url = req.url && cleanUrl(req.url);
  56459. // htmlFallbackMiddleware appends '.html' to URLs
  56460. if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') {
  56461. const filename = getHtmlFilename(url, server);
  56462. if (fs$l.existsSync(filename)) {
  56463. try {
  56464. let html = await fsp.readFile(filename, 'utf-8');
  56465. html = await server.transformIndexHtml(url, html, req.originalUrl);
  56466. return send$2(req, res, html, 'html', {
  56467. headers: server.config.server.headers,
  56468. });
  56469. }
  56470. catch (e) {
  56471. return next(e);
  56472. }
  56473. }
  56474. }
  56475. next();
  56476. };
  56477. }
  56478. function preTransformRequest(server, url, base) {
  56479. if (!server.config.server.preTransformRequests)
  56480. return;
  56481. url = unwrapId(stripBase(url, base));
  56482. // transform all url as non-ssr as html includes client-side assets only
  56483. server.transformRequest(url).catch((e) => {
  56484. // Unexpected error, log the issue but avoid an unhandled exception
  56485. server.config.logger.error(e.message);
  56486. });
  56487. }
  56488. const logTime = createDebugger('vite:time');
  56489. function timeMiddleware(root) {
  56490. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  56491. return function viteTimeMiddleware(req, res, next) {
  56492. const start = performance$1.now();
  56493. const end = res.end;
  56494. res.end = (...args) => {
  56495. logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
  56496. return end.call(res, ...args);
  56497. };
  56498. next();
  56499. };
  56500. }
  56501. class ModuleNode {
  56502. /**
  56503. * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
  56504. */
  56505. constructor(url, setIsSelfAccepting = true) {
  56506. /**
  56507. * Resolved file system path + query
  56508. */
  56509. this.id = null;
  56510. this.file = null;
  56511. this.importers = new Set();
  56512. this.importedModules = new Set();
  56513. this.acceptedHmrDeps = new Set();
  56514. this.acceptedHmrExports = null;
  56515. this.importedBindings = null;
  56516. this.transformResult = null;
  56517. this.ssrTransformResult = null;
  56518. this.ssrModule = null;
  56519. this.ssrError = null;
  56520. this.lastHMRTimestamp = 0;
  56521. this.lastInvalidationTimestamp = 0;
  56522. this.url = url;
  56523. this.type = isDirectCSSRequest(url) ? 'css' : 'js';
  56524. if (setIsSelfAccepting) {
  56525. this.isSelfAccepting = false;
  56526. }
  56527. }
  56528. }
  56529. class ModuleGraph {
  56530. constructor(resolveId) {
  56531. this.resolveId = resolveId;
  56532. this.urlToModuleMap = new Map();
  56533. this.idToModuleMap = new Map();
  56534. // a single file may corresponds to multiple modules with different queries
  56535. this.fileToModulesMap = new Map();
  56536. this.safeModulesPath = new Set();
  56537. /**
  56538. * @internal
  56539. */
  56540. this._unresolvedUrlToModuleMap = new Map();
  56541. /**
  56542. * @internal
  56543. */
  56544. this._ssrUnresolvedUrlToModuleMap = new Map();
  56545. }
  56546. async getModuleByUrl(rawUrl, ssr) {
  56547. // Quick path, if we already have a module for this rawUrl (even without extension)
  56548. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  56549. const mod = this._getUnresolvedUrlToModule(rawUrl, ssr);
  56550. if (mod) {
  56551. return mod;
  56552. }
  56553. const [url] = await this._resolveUrl(rawUrl, ssr);
  56554. return this.urlToModuleMap.get(url);
  56555. }
  56556. getModuleById(id) {
  56557. return this.idToModuleMap.get(removeTimestampQuery(id));
  56558. }
  56559. getModulesByFile(file) {
  56560. return this.fileToModulesMap.get(file);
  56561. }
  56562. onFileChange(file) {
  56563. const mods = this.getModulesByFile(file);
  56564. if (mods) {
  56565. const seen = new Set();
  56566. mods.forEach((mod) => {
  56567. this.invalidateModule(mod, seen);
  56568. });
  56569. }
  56570. }
  56571. invalidateModule(mod, seen = new Set(), timestamp = Date.now(), isHmr = false) {
  56572. if (seen.has(mod)) {
  56573. return;
  56574. }
  56575. seen.add(mod);
  56576. if (isHmr) {
  56577. mod.lastHMRTimestamp = timestamp;
  56578. }
  56579. else {
  56580. // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started
  56581. // processing being done for this module
  56582. mod.lastInvalidationTimestamp = timestamp;
  56583. }
  56584. // Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline
  56585. // Invalidating the transform result is enough to ensure this module is re-processed next time it is requested
  56586. mod.transformResult = null;
  56587. mod.ssrTransformResult = null;
  56588. mod.ssrModule = null;
  56589. mod.ssrError = null;
  56590. mod.importers.forEach((importer) => {
  56591. if (!importer.acceptedHmrDeps.has(mod)) {
  56592. this.invalidateModule(importer, seen, timestamp, isHmr);
  56593. }
  56594. });
  56595. }
  56596. invalidateAll() {
  56597. const timestamp = Date.now();
  56598. const seen = new Set();
  56599. this.idToModuleMap.forEach((mod) => {
  56600. this.invalidateModule(mod, seen, timestamp);
  56601. });
  56602. }
  56603. /**
  56604. * Update the module graph based on a module's updated imports information
  56605. * If there are dependencies that no longer have any importers, they are
  56606. * returned as a Set.
  56607. */
  56608. async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr) {
  56609. mod.isSelfAccepting = isSelfAccepting;
  56610. const prevImports = mod.importedModules;
  56611. let noLongerImported;
  56612. let resolvePromises = [];
  56613. let resolveResults = new Array(importedModules.size);
  56614. let index = 0;
  56615. // update import graph
  56616. for (const imported of importedModules) {
  56617. const nextIndex = index++;
  56618. if (typeof imported === 'string') {
  56619. resolvePromises.push(this.ensureEntryFromUrl(imported, ssr).then((dep) => {
  56620. dep.importers.add(mod);
  56621. resolveResults[nextIndex] = dep;
  56622. }));
  56623. }
  56624. else {
  56625. imported.importers.add(mod);
  56626. resolveResults[nextIndex] = imported;
  56627. }
  56628. }
  56629. if (resolvePromises.length) {
  56630. await Promise.all(resolvePromises);
  56631. }
  56632. const nextImports = (mod.importedModules = new Set(resolveResults));
  56633. // remove the importer from deps that were imported but no longer are.
  56634. prevImports.forEach((dep) => {
  56635. if (!nextImports.has(dep)) {
  56636. dep.importers.delete(mod);
  56637. if (!dep.importers.size) {
  56638. (noLongerImported || (noLongerImported = new Set())).add(dep);
  56639. }
  56640. }
  56641. });
  56642. // update accepted hmr deps
  56643. resolvePromises = [];
  56644. resolveResults = new Array(acceptedModules.size);
  56645. index = 0;
  56646. for (const accepted of acceptedModules) {
  56647. const nextIndex = index++;
  56648. if (typeof accepted === 'string') {
  56649. resolvePromises.push(this.ensureEntryFromUrl(accepted, ssr).then((dep) => {
  56650. resolveResults[nextIndex] = dep;
  56651. }));
  56652. }
  56653. else {
  56654. resolveResults[nextIndex] = accepted;
  56655. }
  56656. }
  56657. if (resolvePromises.length) {
  56658. await Promise.all(resolvePromises);
  56659. }
  56660. mod.acceptedHmrDeps = new Set(resolveResults);
  56661. // update accepted hmr exports
  56662. mod.acceptedHmrExports = acceptedExports;
  56663. mod.importedBindings = importedBindings;
  56664. return noLongerImported;
  56665. }
  56666. async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) {
  56667. return this._ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting);
  56668. }
  56669. /**
  56670. * @internal
  56671. */
  56672. async _ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true,
  56673. // Optimization, avoid resolving the same url twice if the caller already did it
  56674. resolved) {
  56675. // Quick path, if we already have a module for this rawUrl (even without extension)
  56676. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  56677. let mod = this._getUnresolvedUrlToModule(rawUrl, ssr);
  56678. if (mod) {
  56679. return mod;
  56680. }
  56681. const modPromise = (async () => {
  56682. const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, ssr, resolved);
  56683. mod = this.idToModuleMap.get(resolvedId);
  56684. if (!mod) {
  56685. mod = new ModuleNode(url, setIsSelfAccepting);
  56686. if (meta)
  56687. mod.meta = meta;
  56688. this.urlToModuleMap.set(url, mod);
  56689. mod.id = resolvedId;
  56690. this.idToModuleMap.set(resolvedId, mod);
  56691. const file = (mod.file = cleanUrl(resolvedId));
  56692. let fileMappedModules = this.fileToModulesMap.get(file);
  56693. if (!fileMappedModules) {
  56694. fileMappedModules = new Set();
  56695. this.fileToModulesMap.set(file, fileMappedModules);
  56696. }
  56697. fileMappedModules.add(mod);
  56698. }
  56699. // multiple urls can map to the same module and id, make sure we register
  56700. // the url to the existing module in that case
  56701. else if (!this.urlToModuleMap.has(url)) {
  56702. this.urlToModuleMap.set(url, mod);
  56703. }
  56704. this._setUnresolvedUrlToModule(rawUrl, mod, ssr);
  56705. return mod;
  56706. })();
  56707. // Also register the clean url to the module, so that we can short-circuit
  56708. // resolving the same url twice
  56709. this._setUnresolvedUrlToModule(rawUrl, modPromise, ssr);
  56710. return modPromise;
  56711. }
  56712. // some deps, like a css file referenced via @import, don't have its own
  56713. // url because they are inlined into the main css import. But they still
  56714. // need to be represented in the module graph so that they can trigger
  56715. // hmr in the importing css file.
  56716. createFileOnlyEntry(file) {
  56717. file = normalizePath$3(file);
  56718. let fileMappedModules = this.fileToModulesMap.get(file);
  56719. if (!fileMappedModules) {
  56720. fileMappedModules = new Set();
  56721. this.fileToModulesMap.set(file, fileMappedModules);
  56722. }
  56723. const url = `${FS_PREFIX}${file}`;
  56724. for (const m of fileMappedModules) {
  56725. if (m.url === url || m.id === file) {
  56726. return m;
  56727. }
  56728. }
  56729. const mod = new ModuleNode(url);
  56730. mod.file = file;
  56731. fileMappedModules.add(mod);
  56732. return mod;
  56733. }
  56734. // for incoming urls, it is important to:
  56735. // 1. remove the HMR timestamp query (?t=xxxx) and the ?import query
  56736. // 2. resolve its extension so that urls with or without extension all map to
  56737. // the same module
  56738. async resolveUrl(url, ssr) {
  56739. url = removeImportQuery(removeTimestampQuery(url));
  56740. const mod = await this._getUnresolvedUrlToModule(url, ssr);
  56741. if (mod?.id) {
  56742. return [mod.url, mod.id, mod.meta];
  56743. }
  56744. return this._resolveUrl(url, ssr);
  56745. }
  56746. /**
  56747. * @internal
  56748. */
  56749. _getUnresolvedUrlToModule(url, ssr) {
  56750. return (ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap).get(url);
  56751. }
  56752. /**
  56753. * @internal
  56754. */
  56755. _setUnresolvedUrlToModule(url, mod, ssr) {
  56756. (ssr
  56757. ? this._ssrUnresolvedUrlToModuleMap
  56758. : this._unresolvedUrlToModuleMap).set(url, mod);
  56759. }
  56760. /**
  56761. * @internal
  56762. */
  56763. async _resolveUrl(url, ssr, alreadyResolved) {
  56764. const resolved = alreadyResolved ?? (await this.resolveId(url, !!ssr));
  56765. const resolvedId = resolved?.id || url;
  56766. if (url !== resolvedId &&
  56767. !url.includes('\0') &&
  56768. !url.startsWith(`virtual:`)) {
  56769. const ext = extname$1(cleanUrl(resolvedId));
  56770. if (ext) {
  56771. const pathname = cleanUrl(url);
  56772. if (!pathname.endsWith(ext)) {
  56773. url = pathname + ext + url.slice(pathname.length);
  56774. }
  56775. }
  56776. }
  56777. return [url, resolvedId, resolved?.meta];
  56778. }
  56779. }
  56780. var isWsl$2 = {exports: {}};
  56781. const fs$3 = require$$0__default;
  56782. let isDocker$2;
  56783. function hasDockerEnv() {
  56784. try {
  56785. fs$3.statSync('/.dockerenv');
  56786. return true;
  56787. } catch (_) {
  56788. return false;
  56789. }
  56790. }
  56791. function hasDockerCGroup() {
  56792. try {
  56793. return fs$3.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
  56794. } catch (_) {
  56795. return false;
  56796. }
  56797. }
  56798. var isDocker_1 = () => {
  56799. if (isDocker$2 === undefined) {
  56800. isDocker$2 = hasDockerEnv() || hasDockerCGroup();
  56801. }
  56802. return isDocker$2;
  56803. };
  56804. const os = require$$2;
  56805. const fs$2 = require$$0__default;
  56806. const isDocker$1 = isDocker_1;
  56807. const isWsl$1 = () => {
  56808. if (process.platform !== 'linux') {
  56809. return false;
  56810. }
  56811. if (os.release().toLowerCase().includes('microsoft')) {
  56812. if (isDocker$1()) {
  56813. return false;
  56814. }
  56815. return true;
  56816. }
  56817. try {
  56818. return fs$2.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?
  56819. !isDocker$1() : false;
  56820. } catch (_) {
  56821. return false;
  56822. }
  56823. };
  56824. if (process.env.__IS_WSL_TEST__) {
  56825. isWsl$2.exports = isWsl$1;
  56826. } else {
  56827. isWsl$2.exports = isWsl$1();
  56828. }
  56829. var isWslExports = isWsl$2.exports;
  56830. var defineLazyProp = (object, propertyName, fn) => {
  56831. const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});
  56832. Object.defineProperty(object, propertyName, {
  56833. configurable: true,
  56834. enumerable: true,
  56835. get() {
  56836. const result = fn();
  56837. define(result);
  56838. return result;
  56839. },
  56840. set(value) {
  56841. define(value);
  56842. }
  56843. });
  56844. return object;
  56845. };
  56846. const path$3 = require$$0$4;
  56847. const childProcess = require$$2$1;
  56848. const {promises: fs$1, constants: fsConstants} = require$$0__default;
  56849. const isWsl = isWslExports;
  56850. const isDocker = isDocker_1;
  56851. const defineLazyProperty = defineLazyProp;
  56852. // Path to included `xdg-open`.
  56853. const localXdgOpenPath = path$3.join(__dirname, 'xdg-open');
  56854. const {platform, arch} = process;
  56855. // Podman detection
  56856. const hasContainerEnv = () => {
  56857. try {
  56858. fs$1.statSync('/run/.containerenv');
  56859. return true;
  56860. } catch {
  56861. return false;
  56862. }
  56863. };
  56864. let cachedResult;
  56865. function isInsideContainer() {
  56866. if (cachedResult === undefined) {
  56867. cachedResult = hasContainerEnv() || isDocker();
  56868. }
  56869. return cachedResult;
  56870. }
  56871. /**
  56872. Get the mount point for fixed drives in WSL.
  56873. @inner
  56874. @returns {string} The mount point.
  56875. */
  56876. const getWslDrivesMountPoint = (() => {
  56877. // Default value for "root" param
  56878. // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
  56879. const defaultMountPoint = '/mnt/';
  56880. let mountPoint;
  56881. return async function () {
  56882. if (mountPoint) {
  56883. // Return memoized mount point value
  56884. return mountPoint;
  56885. }
  56886. const configFilePath = '/etc/wsl.conf';
  56887. let isConfigFileExists = false;
  56888. try {
  56889. await fs$1.access(configFilePath, fsConstants.F_OK);
  56890. isConfigFileExists = true;
  56891. } catch {}
  56892. if (!isConfigFileExists) {
  56893. return defaultMountPoint;
  56894. }
  56895. const configContent = await fs$1.readFile(configFilePath, {encoding: 'utf8'});
  56896. const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
  56897. if (!configMountPoint) {
  56898. return defaultMountPoint;
  56899. }
  56900. mountPoint = configMountPoint.groups.mountPoint.trim();
  56901. mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
  56902. return mountPoint;
  56903. };
  56904. })();
  56905. const pTryEach = async (array, mapper) => {
  56906. let latestError;
  56907. for (const item of array) {
  56908. try {
  56909. return await mapper(item); // eslint-disable-line no-await-in-loop
  56910. } catch (error) {
  56911. latestError = error;
  56912. }
  56913. }
  56914. throw latestError;
  56915. };
  56916. const baseOpen = async options => {
  56917. options = {
  56918. wait: false,
  56919. background: false,
  56920. newInstance: false,
  56921. allowNonzeroExitCode: false,
  56922. ...options
  56923. };
  56924. if (Array.isArray(options.app)) {
  56925. return pTryEach(options.app, singleApp => baseOpen({
  56926. ...options,
  56927. app: singleApp
  56928. }));
  56929. }
  56930. let {name: app, arguments: appArguments = []} = options.app || {};
  56931. appArguments = [...appArguments];
  56932. if (Array.isArray(app)) {
  56933. return pTryEach(app, appName => baseOpen({
  56934. ...options,
  56935. app: {
  56936. name: appName,
  56937. arguments: appArguments
  56938. }
  56939. }));
  56940. }
  56941. let command;
  56942. const cliArguments = [];
  56943. const childProcessOptions = {};
  56944. if (platform === 'darwin') {
  56945. command = 'open';
  56946. if (options.wait) {
  56947. cliArguments.push('--wait-apps');
  56948. }
  56949. if (options.background) {
  56950. cliArguments.push('--background');
  56951. }
  56952. if (options.newInstance) {
  56953. cliArguments.push('--new');
  56954. }
  56955. if (app) {
  56956. cliArguments.push('-a', app);
  56957. }
  56958. } else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) {
  56959. const mountPoint = await getWslDrivesMountPoint();
  56960. command = isWsl ?
  56961. `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :
  56962. `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
  56963. cliArguments.push(
  56964. '-NoProfile',
  56965. '-NonInteractive',
  56966. '–ExecutionPolicy',
  56967. 'Bypass',
  56968. '-EncodedCommand'
  56969. );
  56970. if (!isWsl) {
  56971. childProcessOptions.windowsVerbatimArguments = true;
  56972. }
  56973. const encodedArguments = ['Start'];
  56974. if (options.wait) {
  56975. encodedArguments.push('-Wait');
  56976. }
  56977. if (app) {
  56978. // Double quote with double quotes to ensure the inner quotes are passed through.
  56979. // Inner quotes are delimited for PowerShell interpretation with backticks.
  56980. encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
  56981. if (options.target) {
  56982. appArguments.unshift(options.target);
  56983. }
  56984. } else if (options.target) {
  56985. encodedArguments.push(`"${options.target}"`);
  56986. }
  56987. if (appArguments.length > 0) {
  56988. appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
  56989. encodedArguments.push(appArguments.join(','));
  56990. }
  56991. // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
  56992. options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
  56993. } else {
  56994. if (app) {
  56995. command = app;
  56996. } else {
  56997. // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
  56998. const isBundled = !__dirname || __dirname === '/';
  56999. // Check if local `xdg-open` exists and is executable.
  57000. let exeLocalXdgOpen = false;
  57001. try {
  57002. await fs$1.access(localXdgOpenPath, fsConstants.X_OK);
  57003. exeLocalXdgOpen = true;
  57004. } catch {}
  57005. const useSystemXdgOpen = process.versions.electron ||
  57006. platform === 'android' || isBundled || !exeLocalXdgOpen;
  57007. command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
  57008. }
  57009. if (appArguments.length > 0) {
  57010. cliArguments.push(...appArguments);
  57011. }
  57012. if (!options.wait) {
  57013. // `xdg-open` will block the process unless stdio is ignored
  57014. // and it's detached from the parent even if it's unref'd.
  57015. childProcessOptions.stdio = 'ignore';
  57016. childProcessOptions.detached = true;
  57017. }
  57018. }
  57019. if (options.target) {
  57020. cliArguments.push(options.target);
  57021. }
  57022. if (platform === 'darwin' && appArguments.length > 0) {
  57023. cliArguments.push('--args', ...appArguments);
  57024. }
  57025. const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
  57026. if (options.wait) {
  57027. return new Promise((resolve, reject) => {
  57028. subprocess.once('error', reject);
  57029. subprocess.once('close', exitCode => {
  57030. if (!options.allowNonzeroExitCode && exitCode > 0) {
  57031. reject(new Error(`Exited with code ${exitCode}`));
  57032. return;
  57033. }
  57034. resolve(subprocess);
  57035. });
  57036. });
  57037. }
  57038. subprocess.unref();
  57039. return subprocess;
  57040. };
  57041. const open = (target, options) => {
  57042. if (typeof target !== 'string') {
  57043. throw new TypeError('Expected a `target`');
  57044. }
  57045. return baseOpen({
  57046. ...options,
  57047. target
  57048. });
  57049. };
  57050. const openApp = (name, options) => {
  57051. if (typeof name !== 'string') {
  57052. throw new TypeError('Expected a `name`');
  57053. }
  57054. const {arguments: appArguments = []} = options || {};
  57055. if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {
  57056. throw new TypeError('Expected `appArguments` as Array type');
  57057. }
  57058. return baseOpen({
  57059. ...options,
  57060. app: {
  57061. name,
  57062. arguments: appArguments
  57063. }
  57064. });
  57065. };
  57066. function detectArchBinary(binary) {
  57067. if (typeof binary === 'string' || Array.isArray(binary)) {
  57068. return binary;
  57069. }
  57070. const {[arch]: archBinary} = binary;
  57071. if (!archBinary) {
  57072. throw new Error(`${arch} is not supported`);
  57073. }
  57074. return archBinary;
  57075. }
  57076. function detectPlatformBinary({[platform]: platformBinary}, {wsl}) {
  57077. if (wsl && isWsl) {
  57078. return detectArchBinary(wsl);
  57079. }
  57080. if (!platformBinary) {
  57081. throw new Error(`${platform} is not supported`);
  57082. }
  57083. return detectArchBinary(platformBinary);
  57084. }
  57085. const apps = {};
  57086. defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({
  57087. darwin: 'google chrome',
  57088. win32: 'chrome',
  57089. linux: ['google-chrome', 'google-chrome-stable', 'chromium']
  57090. }, {
  57091. wsl: {
  57092. ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
  57093. x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']
  57094. }
  57095. }));
  57096. defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({
  57097. darwin: 'firefox',
  57098. win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
  57099. linux: 'firefox'
  57100. }, {
  57101. wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'
  57102. }));
  57103. defineLazyProperty(apps, 'edge', () => detectPlatformBinary({
  57104. darwin: 'microsoft edge',
  57105. win32: 'msedge',
  57106. linux: ['microsoft-edge', 'microsoft-edge-dev']
  57107. }, {
  57108. wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
  57109. }));
  57110. open.apps = apps;
  57111. open.openApp = openApp;
  57112. var open_1 = open;
  57113. var open$1 = /*@__PURE__*/getDefaultExportFromCjs(open_1);
  57114. var crossSpawn = {exports: {}};
  57115. var windows;
  57116. var hasRequiredWindows;
  57117. function requireWindows () {
  57118. if (hasRequiredWindows) return windows;
  57119. hasRequiredWindows = 1;
  57120. windows = isexe;
  57121. isexe.sync = sync;
  57122. var fs = require$$0__default;
  57123. function checkPathExt (path, options) {
  57124. var pathext = options.pathExt !== undefined ?
  57125. options.pathExt : process.env.PATHEXT;
  57126. if (!pathext) {
  57127. return true
  57128. }
  57129. pathext = pathext.split(';');
  57130. if (pathext.indexOf('') !== -1) {
  57131. return true
  57132. }
  57133. for (var i = 0; i < pathext.length; i++) {
  57134. var p = pathext[i].toLowerCase();
  57135. if (p && path.substr(-p.length).toLowerCase() === p) {
  57136. return true
  57137. }
  57138. }
  57139. return false
  57140. }
  57141. function checkStat (stat, path, options) {
  57142. if (!stat.isSymbolicLink() && !stat.isFile()) {
  57143. return false
  57144. }
  57145. return checkPathExt(path, options)
  57146. }
  57147. function isexe (path, options, cb) {
  57148. fs.stat(path, function (er, stat) {
  57149. cb(er, er ? false : checkStat(stat, path, options));
  57150. });
  57151. }
  57152. function sync (path, options) {
  57153. return checkStat(fs.statSync(path), path, options)
  57154. }
  57155. return windows;
  57156. }
  57157. var mode;
  57158. var hasRequiredMode;
  57159. function requireMode () {
  57160. if (hasRequiredMode) return mode;
  57161. hasRequiredMode = 1;
  57162. mode = isexe;
  57163. isexe.sync = sync;
  57164. var fs = require$$0__default;
  57165. function isexe (path, options, cb) {
  57166. fs.stat(path, function (er, stat) {
  57167. cb(er, er ? false : checkStat(stat, options));
  57168. });
  57169. }
  57170. function sync (path, options) {
  57171. return checkStat(fs.statSync(path), options)
  57172. }
  57173. function checkStat (stat, options) {
  57174. return stat.isFile() && checkMode(stat, options)
  57175. }
  57176. function checkMode (stat, options) {
  57177. var mod = stat.mode;
  57178. var uid = stat.uid;
  57179. var gid = stat.gid;
  57180. var myUid = options.uid !== undefined ?
  57181. options.uid : process.getuid && process.getuid();
  57182. var myGid = options.gid !== undefined ?
  57183. options.gid : process.getgid && process.getgid();
  57184. var u = parseInt('100', 8);
  57185. var g = parseInt('010', 8);
  57186. var o = parseInt('001', 8);
  57187. var ug = u | g;
  57188. var ret = (mod & o) ||
  57189. (mod & g) && gid === myGid ||
  57190. (mod & u) && uid === myUid ||
  57191. (mod & ug) && myUid === 0;
  57192. return ret
  57193. }
  57194. return mode;
  57195. }
  57196. var core;
  57197. if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) {
  57198. core = requireWindows();
  57199. } else {
  57200. core = requireMode();
  57201. }
  57202. var isexe_1 = isexe$1;
  57203. isexe$1.sync = sync;
  57204. function isexe$1 (path, options, cb) {
  57205. if (typeof options === 'function') {
  57206. cb = options;
  57207. options = {};
  57208. }
  57209. if (!cb) {
  57210. if (typeof Promise !== 'function') {
  57211. throw new TypeError('callback not provided')
  57212. }
  57213. return new Promise(function (resolve, reject) {
  57214. isexe$1(path, options || {}, function (er, is) {
  57215. if (er) {
  57216. reject(er);
  57217. } else {
  57218. resolve(is);
  57219. }
  57220. });
  57221. })
  57222. }
  57223. core(path, options || {}, function (er, is) {
  57224. // ignore EACCES because that just means we aren't allowed to run it
  57225. if (er) {
  57226. if (er.code === 'EACCES' || options && options.ignoreErrors) {
  57227. er = null;
  57228. is = false;
  57229. }
  57230. }
  57231. cb(er, is);
  57232. });
  57233. }
  57234. function sync (path, options) {
  57235. // my kingdom for a filtered catch
  57236. try {
  57237. return core.sync(path, options || {})
  57238. } catch (er) {
  57239. if (options && options.ignoreErrors || er.code === 'EACCES') {
  57240. return false
  57241. } else {
  57242. throw er
  57243. }
  57244. }
  57245. }
  57246. const isWindows = process.platform === 'win32' ||
  57247. process.env.OSTYPE === 'cygwin' ||
  57248. process.env.OSTYPE === 'msys';
  57249. const path$2 = require$$0$4;
  57250. const COLON = isWindows ? ';' : ':';
  57251. const isexe = isexe_1;
  57252. const getNotFoundError = (cmd) =>
  57253. Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
  57254. const getPathInfo = (cmd, opt) => {
  57255. const colon = opt.colon || COLON;
  57256. // If it has a slash, then we don't bother searching the pathenv.
  57257. // just check the file itself, and that's it.
  57258. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
  57259. : (
  57260. [
  57261. // windows always checks the cwd first
  57262. ...(isWindows ? [process.cwd()] : []),
  57263. ...(opt.path || process.env.PATH ||
  57264. /* istanbul ignore next: very unusual */ '').split(colon),
  57265. ]
  57266. );
  57267. const pathExtExe = isWindows
  57268. ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
  57269. : '';
  57270. const pathExt = isWindows ? pathExtExe.split(colon) : [''];
  57271. if (isWindows) {
  57272. if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
  57273. pathExt.unshift('');
  57274. }
  57275. return {
  57276. pathEnv,
  57277. pathExt,
  57278. pathExtExe,
  57279. }
  57280. };
  57281. const which$1 = (cmd, opt, cb) => {
  57282. if (typeof opt === 'function') {
  57283. cb = opt;
  57284. opt = {};
  57285. }
  57286. if (!opt)
  57287. opt = {};
  57288. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  57289. const found = [];
  57290. const step = i => new Promise((resolve, reject) => {
  57291. if (i === pathEnv.length)
  57292. return opt.all && found.length ? resolve(found)
  57293. : reject(getNotFoundError(cmd))
  57294. const ppRaw = pathEnv[i];
  57295. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  57296. const pCmd = path$2.join(pathPart, cmd);
  57297. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  57298. : pCmd;
  57299. resolve(subStep(p, i, 0));
  57300. });
  57301. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  57302. if (ii === pathExt.length)
  57303. return resolve(step(i + 1))
  57304. const ext = pathExt[ii];
  57305. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  57306. if (!er && is) {
  57307. if (opt.all)
  57308. found.push(p + ext);
  57309. else
  57310. return resolve(p + ext)
  57311. }
  57312. return resolve(subStep(p, i, ii + 1))
  57313. });
  57314. });
  57315. return cb ? step(0).then(res => cb(null, res), cb) : step(0)
  57316. };
  57317. const whichSync = (cmd, opt) => {
  57318. opt = opt || {};
  57319. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  57320. const found = [];
  57321. for (let i = 0; i < pathEnv.length; i ++) {
  57322. const ppRaw = pathEnv[i];
  57323. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  57324. const pCmd = path$2.join(pathPart, cmd);
  57325. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  57326. : pCmd;
  57327. for (let j = 0; j < pathExt.length; j ++) {
  57328. const cur = p + pathExt[j];
  57329. try {
  57330. const is = isexe.sync(cur, { pathExt: pathExtExe });
  57331. if (is) {
  57332. if (opt.all)
  57333. found.push(cur);
  57334. else
  57335. return cur
  57336. }
  57337. } catch (ex) {}
  57338. }
  57339. }
  57340. if (opt.all && found.length)
  57341. return found
  57342. if (opt.nothrow)
  57343. return null
  57344. throw getNotFoundError(cmd)
  57345. };
  57346. var which_1 = which$1;
  57347. which$1.sync = whichSync;
  57348. var pathKey$1 = {exports: {}};
  57349. const pathKey = (options = {}) => {
  57350. const environment = options.env || process.env;
  57351. const platform = options.platform || process.platform;
  57352. if (platform !== 'win32') {
  57353. return 'PATH';
  57354. }
  57355. return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  57356. };
  57357. pathKey$1.exports = pathKey;
  57358. // TODO: Remove this for the next major release
  57359. pathKey$1.exports.default = pathKey;
  57360. var pathKeyExports = pathKey$1.exports;
  57361. const path$1 = require$$0$4;
  57362. const which = which_1;
  57363. const getPathKey = pathKeyExports;
  57364. function resolveCommandAttempt(parsed, withoutPathExt) {
  57365. const env = parsed.options.env || process.env;
  57366. const cwd = process.cwd();
  57367. const hasCustomCwd = parsed.options.cwd != null;
  57368. // Worker threads do not have process.chdir()
  57369. const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
  57370. // If a custom `cwd` was specified, we need to change the process cwd
  57371. // because `which` will do stat calls but does not support a custom cwd
  57372. if (shouldSwitchCwd) {
  57373. try {
  57374. process.chdir(parsed.options.cwd);
  57375. } catch (err) {
  57376. /* Empty */
  57377. }
  57378. }
  57379. let resolved;
  57380. try {
  57381. resolved = which.sync(parsed.command, {
  57382. path: env[getPathKey({ env })],
  57383. pathExt: withoutPathExt ? path$1.delimiter : undefined,
  57384. });
  57385. } catch (e) {
  57386. /* Empty */
  57387. } finally {
  57388. if (shouldSwitchCwd) {
  57389. process.chdir(cwd);
  57390. }
  57391. }
  57392. // If we successfully resolved, ensure that an absolute path is returned
  57393. // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
  57394. if (resolved) {
  57395. resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
  57396. }
  57397. return resolved;
  57398. }
  57399. function resolveCommand$1(parsed) {
  57400. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  57401. }
  57402. var resolveCommand_1 = resolveCommand$1;
  57403. var _escape = {};
  57404. // See http://www.robvanderwoude.com/escapechars.php
  57405. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  57406. function escapeCommand(arg) {
  57407. // Escape meta chars
  57408. arg = arg.replace(metaCharsRegExp, '^$1');
  57409. return arg;
  57410. }
  57411. function escapeArgument(arg, doubleEscapeMetaChars) {
  57412. // Convert to string
  57413. arg = `${arg}`;
  57414. // Algorithm below is based on https://qntm.org/cmd
  57415. // Sequence of backslashes followed by a double quote:
  57416. // double up all the backslashes and escape the double quote
  57417. arg = arg.replace(/(\\*)"/g, '$1$1\\"');
  57418. // Sequence of backslashes followed by the end of the string
  57419. // (which will become a double quote later):
  57420. // double up all the backslashes
  57421. arg = arg.replace(/(\\*)$/, '$1$1');
  57422. // All other backslashes occur literally
  57423. // Quote the whole thing:
  57424. arg = `"${arg}"`;
  57425. // Escape meta chars
  57426. arg = arg.replace(metaCharsRegExp, '^$1');
  57427. // Double escape meta chars if necessary
  57428. if (doubleEscapeMetaChars) {
  57429. arg = arg.replace(metaCharsRegExp, '^$1');
  57430. }
  57431. return arg;
  57432. }
  57433. _escape.command = escapeCommand;
  57434. _escape.argument = escapeArgument;
  57435. var shebangRegex$1 = /^#!(.*)/;
  57436. const shebangRegex = shebangRegex$1;
  57437. var shebangCommand$1 = (string = '') => {
  57438. const match = string.match(shebangRegex);
  57439. if (!match) {
  57440. return null;
  57441. }
  57442. const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
  57443. const binary = path.split('/').pop();
  57444. if (binary === 'env') {
  57445. return argument;
  57446. }
  57447. return argument ? `${binary} ${argument}` : binary;
  57448. };
  57449. const fs = require$$0__default;
  57450. const shebangCommand = shebangCommand$1;
  57451. function readShebang$1(command) {
  57452. // Read the first 150 bytes from the file
  57453. const size = 150;
  57454. const buffer = Buffer.alloc(size);
  57455. let fd;
  57456. try {
  57457. fd = fs.openSync(command, 'r');
  57458. fs.readSync(fd, buffer, 0, size, 0);
  57459. fs.closeSync(fd);
  57460. } catch (e) { /* Empty */ }
  57461. // Attempt to extract shebang (null is returned if not a shebang)
  57462. return shebangCommand(buffer.toString());
  57463. }
  57464. var readShebang_1 = readShebang$1;
  57465. const path = require$$0$4;
  57466. const resolveCommand = resolveCommand_1;
  57467. const escape$1 = _escape;
  57468. const readShebang = readShebang_1;
  57469. const isWin$1 = process.platform === 'win32';
  57470. const isExecutableRegExp = /\.(?:com|exe)$/i;
  57471. const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
  57472. function detectShebang(parsed) {
  57473. parsed.file = resolveCommand(parsed);
  57474. const shebang = parsed.file && readShebang(parsed.file);
  57475. if (shebang) {
  57476. parsed.args.unshift(parsed.file);
  57477. parsed.command = shebang;
  57478. return resolveCommand(parsed);
  57479. }
  57480. return parsed.file;
  57481. }
  57482. function parseNonShell(parsed) {
  57483. if (!isWin$1) {
  57484. return parsed;
  57485. }
  57486. // Detect & add support for shebangs
  57487. const commandFile = detectShebang(parsed);
  57488. // We don't need a shell if the command filename is an executable
  57489. const needsShell = !isExecutableRegExp.test(commandFile);
  57490. // If a shell is required, use cmd.exe and take care of escaping everything correctly
  57491. // Note that `forceShell` is an hidden option used only in tests
  57492. if (parsed.options.forceShell || needsShell) {
  57493. // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
  57494. // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
  57495. // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
  57496. // we need to double escape them
  57497. const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
  57498. // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
  57499. // This is necessary otherwise it will always fail with ENOENT in those cases
  57500. parsed.command = path.normalize(parsed.command);
  57501. // Escape command & arguments
  57502. parsed.command = escape$1.command(parsed.command);
  57503. parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars));
  57504. const shellCommand = [parsed.command].concat(parsed.args).join(' ');
  57505. parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
  57506. parsed.command = process.env.comspec || 'cmd.exe';
  57507. parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
  57508. }
  57509. return parsed;
  57510. }
  57511. function parse$1(command, args, options) {
  57512. // Normalize arguments, similar to nodejs
  57513. if (args && !Array.isArray(args)) {
  57514. options = args;
  57515. args = null;
  57516. }
  57517. args = args ? args.slice(0) : []; // Clone array to avoid changing the original
  57518. options = Object.assign({}, options); // Clone object to avoid changing the original
  57519. // Build our parsed object
  57520. const parsed = {
  57521. command,
  57522. args,
  57523. options,
  57524. file: undefined,
  57525. original: {
  57526. command,
  57527. args,
  57528. },
  57529. };
  57530. // Delegate further parsing to shell or non-shell
  57531. return options.shell ? parsed : parseNonShell(parsed);
  57532. }
  57533. var parse_1 = parse$1;
  57534. const isWin = process.platform === 'win32';
  57535. function notFoundError(original, syscall) {
  57536. return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
  57537. code: 'ENOENT',
  57538. errno: 'ENOENT',
  57539. syscall: `${syscall} ${original.command}`,
  57540. path: original.command,
  57541. spawnargs: original.args,
  57542. });
  57543. }
  57544. function hookChildProcess(cp, parsed) {
  57545. if (!isWin) {
  57546. return;
  57547. }
  57548. const originalEmit = cp.emit;
  57549. cp.emit = function (name, arg1) {
  57550. // If emitting "exit" event and exit code is 1, we need to check if
  57551. // the command exists and emit an "error" instead
  57552. // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
  57553. if (name === 'exit') {
  57554. const err = verifyENOENT(arg1, parsed);
  57555. if (err) {
  57556. return originalEmit.call(cp, 'error', err);
  57557. }
  57558. }
  57559. return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
  57560. };
  57561. }
  57562. function verifyENOENT(status, parsed) {
  57563. if (isWin && status === 1 && !parsed.file) {
  57564. return notFoundError(parsed.original, 'spawn');
  57565. }
  57566. return null;
  57567. }
  57568. function verifyENOENTSync(status, parsed) {
  57569. if (isWin && status === 1 && !parsed.file) {
  57570. return notFoundError(parsed.original, 'spawnSync');
  57571. }
  57572. return null;
  57573. }
  57574. var enoent$1 = {
  57575. hookChildProcess,
  57576. verifyENOENT,
  57577. verifyENOENTSync,
  57578. notFoundError,
  57579. };
  57580. const cp = require$$2$1;
  57581. const parse = parse_1;
  57582. const enoent = enoent$1;
  57583. function spawn(command, args, options) {
  57584. // Parse the arguments
  57585. const parsed = parse(command, args, options);
  57586. // Spawn the child process
  57587. const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
  57588. // Hook into child process "exit" event to emit an error if the command
  57589. // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  57590. enoent.hookChildProcess(spawned, parsed);
  57591. return spawned;
  57592. }
  57593. function spawnSync(command, args, options) {
  57594. // Parse the arguments
  57595. const parsed = parse(command, args, options);
  57596. // Spawn the child process
  57597. const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
  57598. // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  57599. result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
  57600. return result;
  57601. }
  57602. crossSpawn.exports = spawn;
  57603. crossSpawn.exports.spawn = spawn;
  57604. crossSpawn.exports.sync = spawnSync;
  57605. crossSpawn.exports._parse = parse;
  57606. crossSpawn.exports._enoent = enoent;
  57607. var crossSpawnExports = crossSpawn.exports;
  57608. var spawn$1 = /*@__PURE__*/getDefaultExportFromCjs(crossSpawnExports);
  57609. /**
  57610. * The following is modified based on source found in
  57611. * https://github.com/facebook/create-react-app
  57612. *
  57613. * MIT Licensed
  57614. * Copyright (c) 2015-present, Facebook, Inc.
  57615. * https://github.com/facebook/create-react-app/blob/master/LICENSE
  57616. *
  57617. */
  57618. /**
  57619. * Reads the BROWSER environment variable and decides what to do with it.
  57620. */
  57621. function openBrowser(url, opt, logger) {
  57622. // The browser executable to open.
  57623. // See https://github.com/sindresorhus/open#app for documentation.
  57624. const browser = typeof opt === 'string' ? opt : process.env.BROWSER || '';
  57625. if (browser.toLowerCase().endsWith('.js')) {
  57626. executeNodeScript(browser, url, logger);
  57627. }
  57628. else if (browser.toLowerCase() !== 'none') {
  57629. const browserArgs = process.env.BROWSER_ARGS
  57630. ? process.env.BROWSER_ARGS.split(' ')
  57631. : [];
  57632. startBrowserProcess(browser, browserArgs, url);
  57633. }
  57634. }
  57635. function executeNodeScript(scriptPath, url, logger) {
  57636. const extraArgs = process.argv.slice(2);
  57637. const child = spawn$1(process.execPath, [scriptPath, ...extraArgs, url], {
  57638. stdio: 'inherit',
  57639. });
  57640. child.on('close', (code) => {
  57641. if (code !== 0) {
  57642. logger.error(colors$1.red(`\nThe script specified as BROWSER environment variable failed.\n\n${colors$1.cyan(scriptPath)} exited with code ${code}.`), { error: null });
  57643. }
  57644. });
  57645. }
  57646. const supportedChromiumBrowsers = [
  57647. 'Google Chrome Canary',
  57648. 'Google Chrome Dev',
  57649. 'Google Chrome Beta',
  57650. 'Google Chrome',
  57651. 'Microsoft Edge',
  57652. 'Brave Browser',
  57653. 'Vivaldi',
  57654. 'Chromium',
  57655. ];
  57656. async function startBrowserProcess(browser, browserArgs, url) {
  57657. // If we're on OS X, the user hasn't specifically
  57658. // requested a different browser, we can try opening
  57659. // a Chromium browser with AppleScript. This lets us reuse an
  57660. // existing tab when possible instead of creating a new one.
  57661. const preferredOSXBrowser = browser === 'google chrome' ? 'Google Chrome' : browser;
  57662. const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' &&
  57663. (!preferredOSXBrowser ||
  57664. supportedChromiumBrowsers.includes(preferredOSXBrowser));
  57665. if (shouldTryOpenChromeWithAppleScript) {
  57666. try {
  57667. const ps = await execAsync('ps cax');
  57668. const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser)
  57669. ? preferredOSXBrowser
  57670. : supportedChromiumBrowsers.find((b) => ps.includes(b));
  57671. if (openedBrowser) {
  57672. // Try our best to reuse existing tab with AppleScript
  57673. await execAsync(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, {
  57674. cwd: join$2(VITE_PACKAGE_DIR, 'bin'),
  57675. });
  57676. return true;
  57677. }
  57678. }
  57679. catch (err) {
  57680. // Ignore errors
  57681. }
  57682. }
  57683. // Another special case: on OS X, check if BROWSER has been set to "open".
  57684. // In this case, instead of passing the string `open` to `open` function (which won't work),
  57685. // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
  57686. // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
  57687. if (process.platform === 'darwin' && browser === 'open') {
  57688. browser = undefined;
  57689. }
  57690. // Fallback to open
  57691. // (It will always open new tab)
  57692. try {
  57693. const options = browser
  57694. ? { app: { name: browser, arguments: browserArgs } }
  57695. : {};
  57696. open$1(url, options).catch(() => { }); // Prevent `unhandledRejection` error.
  57697. return true;
  57698. }
  57699. catch (err) {
  57700. return false;
  57701. }
  57702. }
  57703. function execAsync(command, options) {
  57704. return new Promise((resolve, reject) => {
  57705. exec(command, options, (error, stdout) => {
  57706. if (error) {
  57707. reject(error);
  57708. }
  57709. else {
  57710. resolve(stdout.toString());
  57711. }
  57712. });
  57713. });
  57714. }
  57715. async function createServer(inlineConfig = {}) {
  57716. return _createServer(inlineConfig, { ws: true });
  57717. }
  57718. async function _createServer(inlineConfig = {}, options) {
  57719. const config = await resolveConfig(inlineConfig, 'serve');
  57720. const { root, server: serverConfig } = config;
  57721. const httpsOptions = await resolveHttpsConfig(config.server.https);
  57722. const { middlewareMode } = serverConfig;
  57723. const resolvedWatchOptions = resolveChokidarOptions(config, {
  57724. disableGlobbing: true,
  57725. ...serverConfig.watch,
  57726. });
  57727. const middlewares = connect$1();
  57728. const httpServer = middlewareMode
  57729. ? null
  57730. : await resolveHttpServer(serverConfig, middlewares, httpsOptions);
  57731. const ws = createWebSocketServer(httpServer, config, httpsOptions);
  57732. if (httpServer) {
  57733. setClientErrorHandler(httpServer, config.logger);
  57734. }
  57735. const watcher = chokidar.watch(
  57736. // config file dependencies and env file might be outside of root
  57737. [root, ...config.configFileDependencies, path$o.join(config.envDir, '.env*')], resolvedWatchOptions);
  57738. const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr }));
  57739. const container = await createPluginContainer(config, moduleGraph, watcher);
  57740. const closeHttpServer = createServerCloseFn(httpServer);
  57741. let exitProcess;
  57742. const server = {
  57743. config,
  57744. middlewares,
  57745. httpServer,
  57746. watcher,
  57747. pluginContainer: container,
  57748. ws,
  57749. moduleGraph,
  57750. resolvedUrls: null,
  57751. ssrTransform(code, inMap, url, originalCode = code) {
  57752. return ssrTransform(code, inMap, url, originalCode, server.config);
  57753. },
  57754. transformRequest(url, options) {
  57755. return transformRequest(url, server, options);
  57756. },
  57757. transformIndexHtml: null,
  57758. async ssrLoadModule(url, opts) {
  57759. if (isDepsOptimizerEnabled(config, true)) {
  57760. await initDevSsrDepsOptimizer(config, server);
  57761. }
  57762. await updateCjsSsrExternals(server);
  57763. return ssrLoadModule(url, server, undefined, undefined, opts?.fixStacktrace);
  57764. },
  57765. ssrFixStacktrace(e) {
  57766. ssrFixStacktrace(e, moduleGraph);
  57767. },
  57768. ssrRewriteStacktrace(stack) {
  57769. return ssrRewriteStacktrace(stack, moduleGraph);
  57770. },
  57771. async reloadModule(module) {
  57772. if (serverConfig.hmr !== false && module.file) {
  57773. updateModules(module.file, [module], Date.now(), server);
  57774. }
  57775. },
  57776. async listen(port, isRestart) {
  57777. await startServer(server, port);
  57778. if (httpServer) {
  57779. server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config);
  57780. if (!isRestart && config.server.open)
  57781. server.openBrowser();
  57782. }
  57783. return server;
  57784. },
  57785. openBrowser() {
  57786. const options = server.config.server;
  57787. const url = server.resolvedUrls?.local[0];
  57788. if (url) {
  57789. const path = typeof options.open === 'string'
  57790. ? new URL(options.open, url).href
  57791. : url;
  57792. openBrowser(path, true, server.config.logger);
  57793. }
  57794. else {
  57795. server.config.logger.warn('No URL available to open in browser');
  57796. }
  57797. },
  57798. async close() {
  57799. if (!middlewareMode) {
  57800. process.off('SIGTERM', exitProcess);
  57801. if (process.env.CI !== 'true') {
  57802. process.stdin.off('end', exitProcess);
  57803. }
  57804. }
  57805. await Promise.allSettled([
  57806. watcher.close(),
  57807. ws.close(),
  57808. container.close(),
  57809. getDepsOptimizer(server.config)?.close(),
  57810. getDepsOptimizer(server.config, true)?.close(),
  57811. closeHttpServer(),
  57812. ]);
  57813. server.resolvedUrls = null;
  57814. },
  57815. printUrls() {
  57816. if (server.resolvedUrls) {
  57817. printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info);
  57818. }
  57819. else if (middlewareMode) {
  57820. throw new Error('cannot print server URLs in middleware mode.');
  57821. }
  57822. else {
  57823. throw new Error('cannot print server URLs before server.listen is called.');
  57824. }
  57825. },
  57826. async restart(forceOptimize) {
  57827. if (!server._restartPromise) {
  57828. server._forceOptimizeOnRestart = !!forceOptimize;
  57829. server._restartPromise = restartServer(server).finally(() => {
  57830. server._restartPromise = null;
  57831. server._forceOptimizeOnRestart = false;
  57832. });
  57833. }
  57834. return server._restartPromise;
  57835. },
  57836. _ssrExternals: null,
  57837. _restartPromise: null,
  57838. _importGlobMap: new Map(),
  57839. _forceOptimizeOnRestart: false,
  57840. _pendingRequests: new Map(),
  57841. _fsDenyGlob: picomatch$4(config.server.fs.deny, { matchBase: true }),
  57842. _shortcutsOptions: undefined,
  57843. };
  57844. server.transformIndexHtml = createDevHtmlTransformFn(server);
  57845. if (!middlewareMode) {
  57846. exitProcess = async () => {
  57847. try {
  57848. await server.close();
  57849. }
  57850. finally {
  57851. process.exit();
  57852. }
  57853. };
  57854. process.once('SIGTERM', exitProcess);
  57855. if (process.env.CI !== 'true') {
  57856. process.stdin.on('end', exitProcess);
  57857. }
  57858. }
  57859. const onHMRUpdate = async (file, configOnly) => {
  57860. if (serverConfig.hmr !== false) {
  57861. try {
  57862. await handleHMRUpdate(file, server, configOnly);
  57863. }
  57864. catch (err) {
  57865. ws.send({
  57866. type: 'error',
  57867. err: prepareError(err),
  57868. });
  57869. }
  57870. }
  57871. };
  57872. const onFileAddUnlink = async (file) => {
  57873. file = normalizePath$3(file);
  57874. await handleFileAddUnlink(file, server);
  57875. await onHMRUpdate(file, true);
  57876. };
  57877. watcher.on('change', async (file) => {
  57878. file = normalizePath$3(file);
  57879. // invalidate module graph cache on file change
  57880. moduleGraph.onFileChange(file);
  57881. await onHMRUpdate(file, false);
  57882. });
  57883. watcher.on('add', onFileAddUnlink);
  57884. watcher.on('unlink', onFileAddUnlink);
  57885. ws.on('vite:invalidate', async ({ path, message }) => {
  57886. const mod = moduleGraph.urlToModuleMap.get(path);
  57887. if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
  57888. config.logger.info(colors$1.yellow(`hmr invalidate `) +
  57889. colors$1.dim(path) +
  57890. (message ? ` ${message}` : ''), { timestamp: true });
  57891. const file = getShortName(mod.file, config.root);
  57892. updateModules(file, [...mod.importers], mod.lastHMRTimestamp, server, true);
  57893. }
  57894. });
  57895. if (!middlewareMode && httpServer) {
  57896. httpServer.once('listening', () => {
  57897. // update actual port since this may be different from initial value
  57898. serverConfig.port = httpServer.address().port;
  57899. });
  57900. }
  57901. // apply server configuration hooks from plugins
  57902. const postHooks = [];
  57903. for (const hook of config.getSortedPluginHooks('configureServer')) {
  57904. postHooks.push(await hook(server));
  57905. }
  57906. // Internal middlewares ------------------------------------------------------
  57907. // request timer
  57908. if (process.env.DEBUG) {
  57909. middlewares.use(timeMiddleware(root));
  57910. }
  57911. // cors (enabled by default)
  57912. const { cors } = serverConfig;
  57913. if (cors !== false) {
  57914. middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors));
  57915. }
  57916. // proxy
  57917. const { proxy } = serverConfig;
  57918. if (proxy) {
  57919. middlewares.use(proxyMiddleware(httpServer, proxy, config));
  57920. }
  57921. // base
  57922. if (config.base !== '/') {
  57923. middlewares.use(baseMiddleware(server));
  57924. }
  57925. // open in editor support
  57926. middlewares.use('/__open-in-editor', launchEditorMiddleware$1());
  57927. // serve static files under /public
  57928. // this applies before the transform middleware so that these files are served
  57929. // as-is without transforms.
  57930. if (config.publicDir) {
  57931. middlewares.use(servePublicMiddleware(config.publicDir, config.server.headers));
  57932. }
  57933. // main transform middleware
  57934. middlewares.use(transformMiddleware(server));
  57935. // serve static files
  57936. middlewares.use(serveRawFsMiddleware(server));
  57937. middlewares.use(serveStaticMiddleware(root, server));
  57938. // html fallback
  57939. if (config.appType === 'spa' || config.appType === 'mpa') {
  57940. middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa'));
  57941. }
  57942. // run post config hooks
  57943. // This is applied before the html middleware so that user middleware can
  57944. // serve custom content instead of index.html.
  57945. postHooks.forEach((fn) => fn && fn());
  57946. if (config.appType === 'spa' || config.appType === 'mpa') {
  57947. // transform index.html
  57948. middlewares.use(indexHtmlMiddleware(server));
  57949. // handle 404s
  57950. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  57951. middlewares.use(function vite404Middleware(_, res) {
  57952. res.statusCode = 404;
  57953. res.end();
  57954. });
  57955. }
  57956. // error handler
  57957. middlewares.use(errorMiddleware(server, middlewareMode));
  57958. // httpServer.listen can be called multiple times
  57959. // when port when using next port number
  57960. // this code is to avoid calling buildStart multiple times
  57961. let initingServer;
  57962. let serverInited = false;
  57963. const initServer = async () => {
  57964. if (serverInited)
  57965. return;
  57966. if (initingServer)
  57967. return initingServer;
  57968. initingServer = (async function () {
  57969. await container.buildStart({});
  57970. // start deps optimizer after all container plugins are ready
  57971. if (isDepsOptimizerEnabled(config, false)) {
  57972. await initDepsOptimizer(config, server);
  57973. }
  57974. initingServer = undefined;
  57975. serverInited = true;
  57976. })();
  57977. return initingServer;
  57978. };
  57979. if (!middlewareMode && httpServer) {
  57980. // overwrite listen to init optimizer before server start
  57981. const listen = httpServer.listen.bind(httpServer);
  57982. httpServer.listen = (async (port, ...args) => {
  57983. try {
  57984. // ensure ws server started
  57985. ws.listen();
  57986. await initServer();
  57987. }
  57988. catch (e) {
  57989. httpServer.emit('error', e);
  57990. return;
  57991. }
  57992. return listen(port, ...args);
  57993. });
  57994. }
  57995. else {
  57996. if (options.ws) {
  57997. ws.listen();
  57998. }
  57999. await initServer();
  58000. }
  58001. return server;
  58002. }
  58003. async function startServer(server, inlinePort) {
  58004. const httpServer = server.httpServer;
  58005. if (!httpServer) {
  58006. throw new Error('Cannot call server.listen in middleware mode.');
  58007. }
  58008. const options = server.config.server;
  58009. const port = inlinePort ?? options.port ?? DEFAULT_DEV_PORT;
  58010. const hostname = await resolveHostname(options.host);
  58011. await httpServerStart(httpServer, {
  58012. port,
  58013. strictPort: options.strictPort,
  58014. host: hostname.host,
  58015. logger: server.config.logger,
  58016. });
  58017. }
  58018. function createServerCloseFn(server) {
  58019. if (!server) {
  58020. return () => { };
  58021. }
  58022. let hasListened = false;
  58023. const openSockets = new Set();
  58024. server.on('connection', (socket) => {
  58025. openSockets.add(socket);
  58026. socket.on('close', () => {
  58027. openSockets.delete(socket);
  58028. });
  58029. });
  58030. server.once('listening', () => {
  58031. hasListened = true;
  58032. });
  58033. return () => new Promise((resolve, reject) => {
  58034. openSockets.forEach((s) => s.destroy());
  58035. if (hasListened) {
  58036. server.close((err) => {
  58037. if (err) {
  58038. reject(err);
  58039. }
  58040. else {
  58041. resolve();
  58042. }
  58043. });
  58044. }
  58045. else {
  58046. resolve();
  58047. }
  58048. });
  58049. }
  58050. function resolvedAllowDir(root, dir) {
  58051. return normalizePath$3(path$o.resolve(root, dir));
  58052. }
  58053. function resolveServerOptions(root, raw, logger) {
  58054. const server = {
  58055. preTransformRequests: true,
  58056. ...raw,
  58057. sourcemapIgnoreList: raw?.sourcemapIgnoreList === false
  58058. ? () => false
  58059. : raw?.sourcemapIgnoreList || isInNodeModules,
  58060. middlewareMode: !!raw?.middlewareMode,
  58061. };
  58062. let allowDirs = server.fs?.allow;
  58063. const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}'];
  58064. if (!allowDirs) {
  58065. allowDirs = [searchForWorkspaceRoot(root)];
  58066. }
  58067. allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
  58068. // only push client dir when vite itself is outside-of-root
  58069. const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
  58070. if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) {
  58071. allowDirs.push(resolvedClientDir);
  58072. }
  58073. server.fs = {
  58074. strict: server.fs?.strict ?? true,
  58075. allow: allowDirs,
  58076. deny,
  58077. };
  58078. if (server.origin?.endsWith('/')) {
  58079. server.origin = server.origin.slice(0, -1);
  58080. logger.warn(colors$1.yellow(`${colors$1.bold('(!)')} server.origin should not end with "/". Using "${server.origin}" instead.`));
  58081. }
  58082. return server;
  58083. }
  58084. async function restartServer(server) {
  58085. global.__vite_start_time = performance$1.now();
  58086. const { port: prevPort, host: prevHost } = server.config.server;
  58087. const shortcutsOptions = server._shortcutsOptions;
  58088. const oldUrls = server.resolvedUrls;
  58089. let inlineConfig = server.config.inlineConfig;
  58090. if (server._forceOptimizeOnRestart) {
  58091. inlineConfig = mergeConfig(inlineConfig, {
  58092. optimizeDeps: {
  58093. force: true,
  58094. },
  58095. });
  58096. }
  58097. let newServer = null;
  58098. try {
  58099. // delay ws server listen
  58100. newServer = await _createServer(inlineConfig, { ws: false });
  58101. }
  58102. catch (err) {
  58103. server.config.logger.error(err.message, {
  58104. timestamp: true,
  58105. });
  58106. server.config.logger.error('server restart failed', { timestamp: true });
  58107. return;
  58108. }
  58109. await server.close();
  58110. // prevent new server `restart` function from calling
  58111. newServer._restartPromise = server._restartPromise;
  58112. Object.assign(server, newServer);
  58113. const { logger, server: { port, host, middlewareMode }, } = server.config;
  58114. if (!middlewareMode) {
  58115. await server.listen(port, true);
  58116. logger.info('server restarted.', { timestamp: true });
  58117. if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) ||
  58118. host !== prevHost ||
  58119. diffDnsOrderChange(oldUrls, newServer.resolvedUrls)) {
  58120. logger.info('');
  58121. server.printUrls();
  58122. }
  58123. }
  58124. else {
  58125. server.ws.listen();
  58126. logger.info('server restarted.', { timestamp: true });
  58127. }
  58128. if (shortcutsOptions) {
  58129. shortcutsOptions.print = false;
  58130. bindShortcuts(newServer, shortcutsOptions);
  58131. }
  58132. // new server (the current server) can restart now
  58133. newServer._restartPromise = null;
  58134. }
  58135. async function updateCjsSsrExternals(server) {
  58136. if (!server._ssrExternals) {
  58137. let knownImports = [];
  58138. // Important! We use the non-ssr optimized deps to find known imports
  58139. // Only the explicitly defined deps are optimized during dev SSR, so
  58140. // we use the generated list from the scanned deps in regular dev.
  58141. // This is part of the v2 externalization heuristics and it is kept
  58142. // for backwards compatibility in case user needs to fallback to the
  58143. // legacy scheme. It may be removed in a future v3 minor.
  58144. const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr
  58145. if (depsOptimizer) {
  58146. await depsOptimizer.scanProcessing;
  58147. knownImports = [
  58148. ...Object.keys(depsOptimizer.metadata.optimized),
  58149. ...Object.keys(depsOptimizer.metadata.discovered),
  58150. ];
  58151. }
  58152. server._ssrExternals = cjsSsrResolveExternals(server.config, knownImports);
  58153. }
  58154. }
  58155. var index = {
  58156. __proto__: null,
  58157. _createServer: _createServer,
  58158. createServer: createServer,
  58159. resolveServerOptions: resolveServerOptions
  58160. };
  58161. /* eslint-disable */
  58162. /* global Buffer */
  58163. const noop = () => { };
  58164. const mimes = /text|javascript|\/json|xml/i;
  58165. const threshold = 1024;
  58166. const level = -1;
  58167. let brotli = false;
  58168. const getChunkSize = (chunk, enc) => (chunk ? Buffer.byteLength(chunk, enc) : 0);
  58169. function compression() {
  58170. const brotliOpts = (typeof brotli === 'object' && brotli) || {};
  58171. const gzipOpts = {};
  58172. // disable Brotli on Node<12.7 where it is unsupported:
  58173. if (!zlib$1.createBrotliCompress)
  58174. brotli = false;
  58175. return function viteCompressionMiddleware(req, res, next = noop) {
  58176. const accept = req.headers['accept-encoding'] + '';
  58177. const encoding = ((brotli && accept.match(/\bbr\b/)) ||
  58178. (accept.match(/\bgzip\b/)) ||
  58179. [])[0];
  58180. // skip if no response body or no supported encoding:
  58181. if (req.method === 'HEAD' || !encoding)
  58182. return next();
  58183. /** @type {zlib.Gzip | zlib.BrotliCompress} */
  58184. let compress;
  58185. let pendingStatus;
  58186. /** @type {[string, function][]?} */
  58187. let pendingListeners = [];
  58188. let started = false;
  58189. let size = 0;
  58190. function start() {
  58191. started = true;
  58192. size = res.getHeader('Content-Length') | 0 || size;
  58193. const compressible = mimes.test(String(res.getHeader('Content-Type') || 'text/plain'));
  58194. const cleartext = !res.getHeader('Content-Encoding');
  58195. const listeners = pendingListeners || [];
  58196. if (compressible && cleartext && size >= threshold) {
  58197. res.setHeader('Content-Encoding', encoding);
  58198. res.removeHeader('Content-Length');
  58199. if (encoding === 'br') {
  58200. const params = {
  58201. [zlib$1.constants.BROTLI_PARAM_QUALITY]: level,
  58202. [zlib$1.constants.BROTLI_PARAM_SIZE_HINT]: size,
  58203. };
  58204. compress = zlib$1.createBrotliCompress({
  58205. params: Object.assign(params, brotliOpts),
  58206. });
  58207. }
  58208. else {
  58209. compress = zlib$1.createGzip(Object.assign({ level }, gzipOpts));
  58210. }
  58211. // backpressure
  58212. compress.on('data', (chunk) => write.call(res, chunk) === false && compress.pause());
  58213. on.call(res, 'drain', () => compress.resume());
  58214. compress.on('end', () => end.call(res));
  58215. listeners.forEach((p) => compress.on.apply(compress, p));
  58216. }
  58217. else {
  58218. pendingListeners = null;
  58219. listeners.forEach((p) => on.apply(res, p));
  58220. }
  58221. writeHead.call(res, pendingStatus || res.statusCode);
  58222. }
  58223. const { end, write, on, writeHead } = res;
  58224. res.writeHead = function (status, reason, headers) {
  58225. if (typeof reason !== 'string')
  58226. [headers, reason] = [reason, headers];
  58227. if (headers)
  58228. for (let i in headers)
  58229. res.setHeader(i, headers[i]);
  58230. pendingStatus = status;
  58231. return this;
  58232. };
  58233. res.write = function (chunk, enc, cb) {
  58234. size += getChunkSize(chunk, enc);
  58235. if (!started)
  58236. start();
  58237. if (!compress)
  58238. return write.apply(this, arguments);
  58239. return compress.write.apply(compress, arguments);
  58240. };
  58241. res.end = function (chunk, enc, cb) {
  58242. if (arguments.length > 0 && typeof chunk !== 'function') {
  58243. size += getChunkSize(chunk, enc);
  58244. }
  58245. if (!started)
  58246. start();
  58247. if (!compress)
  58248. return end.apply(this, arguments);
  58249. return compress.end.apply(compress, arguments);
  58250. };
  58251. res.on = function (type, listener) {
  58252. if (!pendingListeners || type !== 'drain')
  58253. on.call(this, type, listener);
  58254. else if (compress)
  58255. compress.on(type, listener);
  58256. else
  58257. pendingListeners.push([type, listener]);
  58258. return this;
  58259. };
  58260. next();
  58261. };
  58262. }
  58263. function resolvePreviewOptions(preview, server) {
  58264. // The preview server inherits every CommonServerOption from the `server` config
  58265. // except for the port to enable having both the dev and preview servers running
  58266. // at the same time without extra configuration
  58267. return {
  58268. port: preview?.port,
  58269. strictPort: preview?.strictPort ?? server.strictPort,
  58270. host: preview?.host ?? server.host,
  58271. https: preview?.https ?? server.https,
  58272. open: preview?.open ?? server.open,
  58273. proxy: preview?.proxy ?? server.proxy,
  58274. cors: preview?.cors ?? server.cors,
  58275. headers: preview?.headers ?? server.headers,
  58276. };
  58277. }
  58278. /**
  58279. * Starts the Vite server in preview mode, to simulate a production deployment
  58280. */
  58281. async function preview(inlineConfig = {}) {
  58282. const config = await resolveConfig(inlineConfig, 'serve', 'production', 'production');
  58283. const distDir = path$o.resolve(config.root, config.build.outDir);
  58284. if (!fs$l.existsSync(distDir) &&
  58285. // error if no plugins implement `configurePreviewServer`
  58286. config.plugins.every((plugin) => !plugin.configurePreviewServer) &&
  58287. // error if called in CLI only. programmatic usage could access `httpServer`
  58288. // and affect file serving
  58289. process.argv[1]?.endsWith(path$o.normalize('bin/vite.js')) &&
  58290. process.argv[2] === 'preview') {
  58291. throw new Error(`The directory "${config.build.outDir}" does not exist. Did you build your project?`);
  58292. }
  58293. const app = connect$1();
  58294. const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig(config.preview?.https));
  58295. setClientErrorHandler(httpServer, config.logger);
  58296. const options = config.preview;
  58297. const logger = config.logger;
  58298. const server = {
  58299. config,
  58300. middlewares: app,
  58301. httpServer,
  58302. resolvedUrls: null,
  58303. printUrls() {
  58304. if (server.resolvedUrls) {
  58305. printServerUrls(server.resolvedUrls, options.host, logger.info);
  58306. }
  58307. else {
  58308. throw new Error('cannot print server URLs before server is listening.');
  58309. }
  58310. },
  58311. };
  58312. // apply server hooks from plugins
  58313. const postHooks = [];
  58314. for (const hook of config.getSortedPluginHooks('configurePreviewServer')) {
  58315. postHooks.push(await hook(server));
  58316. }
  58317. // cors
  58318. const { cors } = config.preview;
  58319. if (cors !== false) {
  58320. app.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors));
  58321. }
  58322. // proxy
  58323. const { proxy } = config.preview;
  58324. if (proxy) {
  58325. app.use(proxyMiddleware(httpServer, proxy, config));
  58326. }
  58327. app.use(compression());
  58328. const previewBase = config.base === './' || config.base === '' ? '/' : config.base;
  58329. // static assets
  58330. const headers = config.preview.headers;
  58331. const viteAssetMiddleware = (...args) => sirv(distDir, {
  58332. etag: true,
  58333. dev: true,
  58334. single: config.appType === 'spa',
  58335. setHeaders(res) {
  58336. if (headers) {
  58337. for (const name in headers) {
  58338. res.setHeader(name, headers[name]);
  58339. }
  58340. }
  58341. },
  58342. shouldServe(filePath) {
  58343. return shouldServeFile(filePath, distDir);
  58344. },
  58345. })(...args);
  58346. app.use(previewBase, viteAssetMiddleware);
  58347. // apply post server hooks from plugins
  58348. postHooks.forEach((fn) => fn && fn());
  58349. const hostname = await resolveHostname(options.host);
  58350. const port = options.port ?? DEFAULT_PREVIEW_PORT;
  58351. const protocol = options.https ? 'https' : 'http';
  58352. const serverPort = await httpServerStart(httpServer, {
  58353. port,
  58354. strictPort: options.strictPort,
  58355. host: hostname.host,
  58356. logger,
  58357. });
  58358. server.resolvedUrls = await resolveServerUrls(httpServer, config.preview, config);
  58359. if (options.open) {
  58360. const path = typeof options.open === 'string' ? options.open : previewBase;
  58361. openBrowser(path.startsWith('http')
  58362. ? path
  58363. : new URL(path, `${protocol}://${hostname.name}:${serverPort}`).href, true, logger);
  58364. }
  58365. return server;
  58366. }
  58367. var preview$1 = {
  58368. __proto__: null,
  58369. preview: preview,
  58370. resolvePreviewOptions: resolvePreviewOptions
  58371. };
  58372. function resolveSSROptions(ssr, preserveSymlinks, buildSsrCjsExternalHeuristics) {
  58373. ssr ?? (ssr = {});
  58374. const optimizeDeps = ssr.optimizeDeps ?? {};
  58375. let format = 'esm';
  58376. let target = 'node';
  58377. if (buildSsrCjsExternalHeuristics) {
  58378. if (ssr) {
  58379. format = 'cjs';
  58380. }
  58381. else {
  58382. target = 'node';
  58383. format = 'cjs';
  58384. }
  58385. }
  58386. return {
  58387. format,
  58388. target,
  58389. ...ssr,
  58390. optimizeDeps: {
  58391. disabled: true,
  58392. ...optimizeDeps,
  58393. esbuildOptions: {
  58394. preserveSymlinks,
  58395. ...optimizeDeps.esbuildOptions,
  58396. },
  58397. },
  58398. };
  58399. }
  58400. const debug = createDebugger('vite:config');
  58401. const promisifiedRealpath = promisify$4(fs$l.realpath);
  58402. /**
  58403. * Type helper to make it easier to use vite.config.ts
  58404. * accepts a direct {@link UserConfig} object, or a function that returns it.
  58405. * The function receives a {@link ConfigEnv} object that exposes two properties:
  58406. * `command` (either `'build'` or `'serve'`), and `mode`.
  58407. */
  58408. function defineConfig(config) {
  58409. return config;
  58410. }
  58411. async function resolveConfig(inlineConfig, command, defaultMode = 'development', defaultNodeEnv = 'development') {
  58412. let config = inlineConfig;
  58413. let configFileDependencies = [];
  58414. let mode = inlineConfig.mode || defaultMode;
  58415. const isNodeEnvSet = !!process.env.NODE_ENV;
  58416. const packageCache = new Map();
  58417. // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting
  58418. // production-specific behavior, so set it early on
  58419. if (!isNodeEnvSet) {
  58420. process.env.NODE_ENV = defaultNodeEnv;
  58421. }
  58422. const configEnv = {
  58423. mode,
  58424. command,
  58425. ssrBuild: !!config.build?.ssr,
  58426. };
  58427. let { configFile } = config;
  58428. if (configFile !== false) {
  58429. const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel);
  58430. if (loadResult) {
  58431. config = mergeConfig(loadResult.config, config);
  58432. configFile = loadResult.path;
  58433. configFileDependencies = loadResult.dependencies;
  58434. }
  58435. }
  58436. // user config may provide an alternative mode. But --mode has a higher priority
  58437. mode = inlineConfig.mode || config.mode || mode;
  58438. configEnv.mode = mode;
  58439. const filterPlugin = (p) => {
  58440. if (!p) {
  58441. return false;
  58442. }
  58443. else if (!p.apply) {
  58444. return true;
  58445. }
  58446. else if (typeof p.apply === 'function') {
  58447. return p.apply({ ...config, mode }, configEnv);
  58448. }
  58449. else {
  58450. return p.apply === command;
  58451. }
  58452. };
  58453. // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example).
  58454. // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
  58455. // So we need to separate the worker plugin from the plugin that vite needs to run.
  58456. const rawWorkerUserPlugins = (await asyncFlatten(config.worker?.plugins || [])).filter(filterPlugin);
  58457. // resolve plugins
  58458. const rawUserPlugins = (await asyncFlatten(config.plugins || [])).filter(filterPlugin);
  58459. const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins);
  58460. // run config hooks
  58461. const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
  58462. config = await runConfigHook(config, userPlugins, configEnv);
  58463. if (process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) {
  58464. config = mergeConfig(config, {
  58465. optimizeDeps: { disabled: false },
  58466. ssr: { optimizeDeps: { disabled: false } },
  58467. });
  58468. config.build ?? (config.build = {});
  58469. config.build.commonjsOptions = { include: [] };
  58470. }
  58471. // Define logger
  58472. const logger = createLogger(config.logLevel, {
  58473. allowClearScreen: config.clearScreen,
  58474. customLogger: config.customLogger,
  58475. });
  58476. // resolve root
  58477. const resolvedRoot = normalizePath$3(config.root ? path$o.resolve(config.root) : process.cwd());
  58478. const clientAlias = [
  58479. {
  58480. find: /^\/?@vite\/env/,
  58481. replacement: path$o.posix.join(FS_PREFIX, normalizePath$3(ENV_ENTRY)),
  58482. },
  58483. {
  58484. find: /^\/?@vite\/client/,
  58485. replacement: path$o.posix.join(FS_PREFIX, normalizePath$3(CLIENT_ENTRY)),
  58486. },
  58487. ];
  58488. // resolve alias with internal client alias
  58489. const resolvedAlias = normalizeAlias(mergeAlias(clientAlias, config.resolve?.alias || []));
  58490. const resolveOptions = {
  58491. mainFields: config.resolve?.mainFields ?? DEFAULT_MAIN_FIELDS,
  58492. browserField: config.resolve?.browserField ?? true,
  58493. conditions: config.resolve?.conditions ?? [],
  58494. extensions: config.resolve?.extensions ?? DEFAULT_EXTENSIONS$1,
  58495. dedupe: config.resolve?.dedupe ?? [],
  58496. preserveSymlinks: config.resolve?.preserveSymlinks ?? false,
  58497. alias: resolvedAlias,
  58498. };
  58499. // load .env files
  58500. const envDir = config.envDir
  58501. ? normalizePath$3(path$o.resolve(resolvedRoot, config.envDir))
  58502. : resolvedRoot;
  58503. const userEnv = inlineConfig.envFile !== false &&
  58504. loadEnv(mode, envDir, resolveEnvPrefix(config));
  58505. // Note it is possible for user to have a custom mode, e.g. `staging` where
  58506. // development-like behavior is expected. This is indicated by NODE_ENV=development
  58507. // loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV
  58508. const userNodeEnv = process.env.VITE_USER_NODE_ENV;
  58509. if (!isNodeEnvSet && userNodeEnv) {
  58510. if (userNodeEnv === 'development') {
  58511. process.env.NODE_ENV = 'development';
  58512. }
  58513. else {
  58514. // NODE_ENV=production is not supported as it could break HMR in dev for frameworks like Vue
  58515. logger.warn(`NODE_ENV=${userNodeEnv} is not supported in the .env file. ` +
  58516. `Only NODE_ENV=development is supported to create a development build of your project. ` +
  58517. `If you need to set process.env.NODE_ENV, you can set it in the Vite config instead.`);
  58518. }
  58519. }
  58520. const isProduction = process.env.NODE_ENV === 'production';
  58521. // resolve public base url
  58522. const isBuild = command === 'build';
  58523. const relativeBaseShortcut = config.base === '' || config.base === './';
  58524. // During dev, we ignore relative base and fallback to '/'
  58525. // For the SSR build, relative base isn't possible by means
  58526. // of import.meta.url.
  58527. const resolvedBase = relativeBaseShortcut
  58528. ? !isBuild || config.build?.ssr
  58529. ? '/'
  58530. : './'
  58531. : resolveBaseUrl(config.base, isBuild, logger) ?? '/';
  58532. const resolvedBuildOptions = resolveBuildOptions(config.build, logger, resolvedRoot);
  58533. // resolve cache directory
  58534. const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir;
  58535. const cacheDir = normalizePath$3(config.cacheDir
  58536. ? path$o.resolve(resolvedRoot, config.cacheDir)
  58537. : pkgDir
  58538. ? path$o.join(pkgDir, `node_modules/.vite`)
  58539. : path$o.join(resolvedRoot, `.vite`));
  58540. const assetsFilter = config.assetsInclude &&
  58541. (!Array.isArray(config.assetsInclude) || config.assetsInclude.length)
  58542. ? createFilter(config.assetsInclude)
  58543. : () => false;
  58544. // create an internal resolver to be used in special scenarios, e.g.
  58545. // optimizer & handling css @imports
  58546. const createResolver = (options) => {
  58547. let aliasContainer;
  58548. let resolverContainer;
  58549. return async (id, importer, aliasOnly, ssr) => {
  58550. let container;
  58551. if (aliasOnly) {
  58552. container =
  58553. aliasContainer ||
  58554. (aliasContainer = await createPluginContainer({
  58555. ...resolved,
  58556. plugins: [alias$1({ entries: resolved.resolve.alias })],
  58557. }));
  58558. }
  58559. else {
  58560. container =
  58561. resolverContainer ||
  58562. (resolverContainer = await createPluginContainer({
  58563. ...resolved,
  58564. plugins: [
  58565. alias$1({ entries: resolved.resolve.alias }),
  58566. resolvePlugin({
  58567. ...resolved.resolve,
  58568. root: resolvedRoot,
  58569. isProduction,
  58570. isBuild: command === 'build',
  58571. ssrConfig: resolved.ssr,
  58572. asSrc: true,
  58573. preferRelative: false,
  58574. tryIndex: true,
  58575. ...options,
  58576. idOnly: true,
  58577. }),
  58578. ],
  58579. }));
  58580. }
  58581. return (await container.resolveId(id, importer, {
  58582. ssr,
  58583. scan: options?.scan,
  58584. }))?.id;
  58585. };
  58586. };
  58587. const { publicDir } = config;
  58588. const resolvedPublicDir = publicDir !== false && publicDir !== ''
  58589. ? path$o.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public')
  58590. : '';
  58591. const server = resolveServerOptions(resolvedRoot, config.server, logger);
  58592. const ssr = resolveSSROptions(config.ssr, resolveOptions.preserveSymlinks, config.legacy?.buildSsrCjsExternalHeuristics);
  58593. const middlewareMode = config?.server?.middlewareMode;
  58594. const optimizeDeps = config.optimizeDeps || {};
  58595. const BASE_URL = resolvedBase;
  58596. // resolve worker
  58597. let workerConfig = mergeConfig({}, config);
  58598. const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
  58599. // run config hooks
  58600. const workerUserPlugins = [
  58601. ...workerPrePlugins,
  58602. ...workerNormalPlugins,
  58603. ...workerPostPlugins,
  58604. ];
  58605. workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv);
  58606. const resolvedWorkerOptions = {
  58607. format: workerConfig.worker?.format || 'iife',
  58608. plugins: [],
  58609. rollupOptions: workerConfig.worker?.rollupOptions || {},
  58610. getSortedPlugins: undefined,
  58611. getSortedPluginHooks: undefined,
  58612. };
  58613. const resolvedConfig = {
  58614. configFile: configFile ? normalizePath$3(configFile) : undefined,
  58615. configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))),
  58616. inlineConfig,
  58617. root: resolvedRoot,
  58618. base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/',
  58619. rawBase: resolvedBase,
  58620. resolve: resolveOptions,
  58621. publicDir: resolvedPublicDir,
  58622. cacheDir,
  58623. command,
  58624. mode,
  58625. ssr,
  58626. isWorker: false,
  58627. mainConfig: null,
  58628. isProduction,
  58629. plugins: userPlugins,
  58630. esbuild: config.esbuild === false
  58631. ? false
  58632. : {
  58633. jsxDev: !isProduction,
  58634. ...config.esbuild,
  58635. },
  58636. server,
  58637. build: resolvedBuildOptions,
  58638. preview: resolvePreviewOptions(config.preview, server),
  58639. envDir,
  58640. env: {
  58641. ...userEnv,
  58642. BASE_URL,
  58643. MODE: mode,
  58644. DEV: !isProduction,
  58645. PROD: isProduction,
  58646. },
  58647. assetsInclude(file) {
  58648. return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
  58649. },
  58650. logger,
  58651. packageCache,
  58652. createResolver,
  58653. optimizeDeps: {
  58654. disabled: 'build',
  58655. ...optimizeDeps,
  58656. esbuildOptions: {
  58657. preserveSymlinks: resolveOptions.preserveSymlinks,
  58658. ...optimizeDeps.esbuildOptions,
  58659. },
  58660. },
  58661. worker: resolvedWorkerOptions,
  58662. appType: config.appType ?? (middlewareMode === 'ssr' ? 'custom' : 'spa'),
  58663. experimental: {
  58664. importGlobRestoreExtension: false,
  58665. hmrPartialAccept: false,
  58666. ...config.experimental,
  58667. },
  58668. getSortedPlugins: undefined,
  58669. getSortedPluginHooks: undefined,
  58670. };
  58671. const resolved = {
  58672. ...config,
  58673. ...resolvedConfig,
  58674. };
  58675. resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
  58676. Object.assign(resolved, createPluginHookUtils(resolved.plugins));
  58677. const workerResolved = {
  58678. ...workerConfig,
  58679. ...resolvedConfig,
  58680. isWorker: true,
  58681. mainConfig: resolved,
  58682. };
  58683. resolvedConfig.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
  58684. Object.assign(resolvedConfig.worker, createPluginHookUtils(resolvedConfig.worker.plugins));
  58685. // call configResolved hooks
  58686. await Promise.all([
  58687. ...resolved
  58688. .getSortedPluginHooks('configResolved')
  58689. .map((hook) => hook(resolved)),
  58690. ...resolvedConfig.worker
  58691. .getSortedPluginHooks('configResolved')
  58692. .map((hook) => hook(workerResolved)),
  58693. ]);
  58694. // validate config
  58695. if (middlewareMode === 'ssr') {
  58696. logger.warn(colors$1.yellow(`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${config.appType === 'custom' ? '' : ` and appType to 'custom'`} instead`));
  58697. }
  58698. if (middlewareMode === 'html') {
  58699. logger.warn(colors$1.yellow(`Setting server.middlewareMode to 'html' is deprecated, set server.middlewareMode to \`true\` instead`));
  58700. }
  58701. if (config.server?.force &&
  58702. !isBuild &&
  58703. config.optimizeDeps?.force === undefined) {
  58704. resolved.optimizeDeps.force = true;
  58705. logger.warn(colors$1.yellow(`server.force is deprecated, use optimizeDeps.force instead`));
  58706. }
  58707. debug?.(`using resolved config: %O`, {
  58708. ...resolved,
  58709. plugins: resolved.plugins.map((p) => p.name),
  58710. worker: {
  58711. ...resolved.worker,
  58712. plugins: resolved.worker.plugins.map((p) => p.name),
  58713. },
  58714. });
  58715. if (config.build?.terserOptions && config.build.minify !== 'terser') {
  58716. logger.warn(colors$1.yellow(`build.terserOptions is specified but build.minify is not set to use Terser. ` +
  58717. `Note Vite now defaults to use esbuild for minification. If you still ` +
  58718. `prefer Terser, set build.minify to "terser".`));
  58719. }
  58720. // Check if all assetFileNames have the same reference.
  58721. // If not, display a warn for user.
  58722. const outputOption = config.build?.rollupOptions?.output ?? [];
  58723. // Use isArray to narrow its type to array
  58724. if (Array.isArray(outputOption)) {
  58725. const assetFileNamesList = outputOption.map((output) => output.assetFileNames);
  58726. if (assetFileNamesList.length > 1) {
  58727. const firstAssetFileNames = assetFileNamesList[0];
  58728. const hasDifferentReference = assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames);
  58729. if (hasDifferentReference) {
  58730. resolved.logger.warn(colors$1.yellow(`
  58731. assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite.
  58732. `));
  58733. }
  58734. }
  58735. }
  58736. return resolved;
  58737. }
  58738. /**
  58739. * Resolve base url. Note that some users use Vite to build for non-web targets like
  58740. * electron or expects to deploy
  58741. */
  58742. function resolveBaseUrl(base = '/', isBuild, logger) {
  58743. if (base[0] === '.') {
  58744. logger.warn(colors$1.yellow(colors$1.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
  58745. `URL, ./, or an empty string.`)));
  58746. return '/';
  58747. }
  58748. // external URL flag
  58749. const isExternal = isExternalUrl(base);
  58750. // no leading slash warn
  58751. if (!isExternal && base[0] !== '/') {
  58752. logger.warn(colors$1.yellow(colors$1.bold(`(!) "base" option should start with a slash.`)));
  58753. }
  58754. // parse base when command is serve or base is not External URL
  58755. if (!isBuild || !isExternal) {
  58756. base = new URL(base, 'http://vitejs.dev').pathname;
  58757. // ensure leading slash
  58758. if (base[0] !== '/') {
  58759. base = '/' + base;
  58760. }
  58761. }
  58762. return base;
  58763. }
  58764. function sortUserPlugins(plugins) {
  58765. const prePlugins = [];
  58766. const postPlugins = [];
  58767. const normalPlugins = [];
  58768. if (plugins) {
  58769. plugins.flat().forEach((p) => {
  58770. if (p.enforce === 'pre')
  58771. prePlugins.push(p);
  58772. else if (p.enforce === 'post')
  58773. postPlugins.push(p);
  58774. else
  58775. normalPlugins.push(p);
  58776. });
  58777. }
  58778. return [prePlugins, normalPlugins, postPlugins];
  58779. }
  58780. async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) {
  58781. const start = performance$1.now();
  58782. const getTime = () => `${(performance$1.now() - start).toFixed(2)}ms`;
  58783. let resolvedPath;
  58784. if (configFile) {
  58785. // explicit config path is always resolved from cwd
  58786. resolvedPath = path$o.resolve(configFile);
  58787. }
  58788. else {
  58789. // implicit config file loaded from inline root (if present)
  58790. // otherwise from cwd
  58791. for (const filename of DEFAULT_CONFIG_FILES) {
  58792. const filePath = path$o.resolve(configRoot, filename);
  58793. if (!fs$l.existsSync(filePath))
  58794. continue;
  58795. resolvedPath = filePath;
  58796. break;
  58797. }
  58798. }
  58799. if (!resolvedPath) {
  58800. debug?.('no config file found.');
  58801. return null;
  58802. }
  58803. let isESM = false;
  58804. if (/\.m[jt]s$/.test(resolvedPath)) {
  58805. isESM = true;
  58806. }
  58807. else if (/\.c[jt]s$/.test(resolvedPath)) {
  58808. isESM = false;
  58809. }
  58810. else {
  58811. // check package.json for type: "module" and set `isESM` to true
  58812. try {
  58813. const pkg = lookupFile(configRoot, ['package.json']);
  58814. isESM =
  58815. !!pkg && JSON.parse(fs$l.readFileSync(pkg, 'utf-8')).type === 'module';
  58816. }
  58817. catch (e) { }
  58818. }
  58819. try {
  58820. const bundled = await bundleConfigFile(resolvedPath, isESM);
  58821. const userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM);
  58822. debug?.(`bundled config file loaded in ${getTime()}`);
  58823. const config = await (typeof userConfig === 'function'
  58824. ? userConfig(configEnv)
  58825. : userConfig);
  58826. if (!isObject$2(config)) {
  58827. throw new Error(`config must export or return an object.`);
  58828. }
  58829. return {
  58830. path: normalizePath$3(resolvedPath),
  58831. config,
  58832. dependencies: bundled.dependencies,
  58833. };
  58834. }
  58835. catch (e) {
  58836. createLogger(logLevel).error(colors$1.red(`failed to load config from ${resolvedPath}`), { error: e });
  58837. throw e;
  58838. }
  58839. }
  58840. async function bundleConfigFile(fileName, isESM) {
  58841. const dirnameVarName = '__vite_injected_original_dirname';
  58842. const filenameVarName = '__vite_injected_original_filename';
  58843. const importMetaUrlVarName = '__vite_injected_original_import_meta_url';
  58844. const result = await build$3({
  58845. absWorkingDir: process.cwd(),
  58846. entryPoints: [fileName],
  58847. outfile: 'out.js',
  58848. write: false,
  58849. target: ['node14.18', 'node16'],
  58850. platform: 'node',
  58851. bundle: true,
  58852. format: isESM ? 'esm' : 'cjs',
  58853. mainFields: ['main'],
  58854. sourcemap: 'inline',
  58855. metafile: true,
  58856. define: {
  58857. __dirname: dirnameVarName,
  58858. __filename: filenameVarName,
  58859. 'import.meta.url': importMetaUrlVarName,
  58860. },
  58861. plugins: [
  58862. {
  58863. name: 'externalize-deps',
  58864. setup(build) {
  58865. const options = {
  58866. root: path$o.dirname(fileName),
  58867. isBuild: true,
  58868. isProduction: true,
  58869. preferRelative: false,
  58870. tryIndex: true,
  58871. mainFields: [],
  58872. browserField: false,
  58873. conditions: [],
  58874. overrideConditions: ['node'],
  58875. dedupe: [],
  58876. extensions: DEFAULT_EXTENSIONS$1,
  58877. preserveSymlinks: false,
  58878. packageCache: new Map(),
  58879. };
  58880. // externalize bare imports
  58881. build.onResolve({ filter: /^[^.].*/ }, async ({ path: id, importer, kind }) => {
  58882. if (kind === 'entry-point' ||
  58883. path$o.isAbsolute(id) ||
  58884. isBuiltin(id)) {
  58885. return;
  58886. }
  58887. // partial deno support as `npm:` does not work with esbuild
  58888. if (id.startsWith('npm:')) {
  58889. return { external: true };
  58890. }
  58891. const isIdESM = isESM || kind === 'dynamic-import';
  58892. let idFsPath = tryNodeResolve(id, importer, { ...options, isRequire: !isIdESM }, false)?.id;
  58893. if (idFsPath && isIdESM) {
  58894. idFsPath = pathToFileURL(idFsPath).href;
  58895. }
  58896. return {
  58897. path: idFsPath,
  58898. external: true,
  58899. };
  58900. });
  58901. },
  58902. },
  58903. {
  58904. name: 'inject-file-scope-variables',
  58905. setup(build) {
  58906. build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
  58907. const contents = await fs$l.promises.readFile(args.path, 'utf8');
  58908. const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path$o.dirname(args.path))};` +
  58909. `const ${filenameVarName} = ${JSON.stringify(args.path)};` +
  58910. `const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(args.path).href)};`;
  58911. return {
  58912. loader: args.path.endsWith('ts') ? 'ts' : 'js',
  58913. contents: injectValues + contents,
  58914. };
  58915. });
  58916. },
  58917. },
  58918. ],
  58919. });
  58920. const { text } = result.outputFiles[0];
  58921. return {
  58922. code: text,
  58923. dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [],
  58924. };
  58925. }
  58926. const _require = createRequire$1(import.meta.url);
  58927. async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
  58928. // for esm, before we can register loaders without requiring users to run node
  58929. // with --experimental-loader themselves, we have to do a hack here:
  58930. // write it to disk, load it with native Node ESM, then delete the file.
  58931. if (isESM) {
  58932. const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random()
  58933. .toString(16)
  58934. .slice(2)}`;
  58935. const fileNameTmp = `${fileBase}.mjs`;
  58936. const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
  58937. await fsp.writeFile(fileNameTmp, bundledCode);
  58938. try {
  58939. return (await dynamicImport(fileUrl)).default;
  58940. }
  58941. finally {
  58942. fs$l.unlink(fileNameTmp, () => { }); // Ignore errors
  58943. }
  58944. }
  58945. // for cjs, we can register a custom loader via `_require.extensions`
  58946. else {
  58947. const extension = path$o.extname(fileName);
  58948. // We don't use fsp.realpath() here because it has the same behaviour as
  58949. // fs.realpath.native. On some Windows systems, it returns uppercase volume
  58950. // letters (e.g. "C:\") while the Node.js loader uses lowercase volume letters.
  58951. // See https://github.com/vitejs/vite/issues/12923
  58952. const realFileName = await promisifiedRealpath(fileName);
  58953. const loaderExt = extension in _require.extensions ? extension : '.js';
  58954. const defaultLoader = _require.extensions[loaderExt];
  58955. _require.extensions[loaderExt] = (module, filename) => {
  58956. if (filename === realFileName) {
  58957. module._compile(bundledCode, filename);
  58958. }
  58959. else {
  58960. defaultLoader(module, filename);
  58961. }
  58962. };
  58963. // clear cache in case of server restart
  58964. delete _require.cache[_require.resolve(fileName)];
  58965. const raw = _require(fileName);
  58966. _require.extensions[loaderExt] = defaultLoader;
  58967. return raw.__esModule ? raw.default : raw;
  58968. }
  58969. }
  58970. async function runConfigHook(config, plugins, configEnv) {
  58971. let conf = config;
  58972. for (const p of getSortedPluginsByHook('config', plugins)) {
  58973. const hook = p.config;
  58974. const handler = hook && 'handler' in hook ? hook.handler : hook;
  58975. if (handler) {
  58976. const res = await handler(conf, configEnv);
  58977. if (res) {
  58978. conf = mergeConfig(conf, res);
  58979. }
  58980. }
  58981. }
  58982. return conf;
  58983. }
  58984. function getDepOptimizationConfig(config, ssr) {
  58985. return ssr ? config.ssr.optimizeDeps : config.optimizeDeps;
  58986. }
  58987. function isDepsOptimizerEnabled(config, ssr) {
  58988. const { command } = config;
  58989. const { disabled } = getDepOptimizationConfig(config, ssr);
  58990. return !(disabled === true ||
  58991. (command === 'build' && disabled === 'build') ||
  58992. (command === 'serve' && disabled === 'dev'));
  58993. }
  58994. export { loadEnv as A, resolveEnvPrefix as B, colors$1 as C, bindShortcuts as D, getDefaultExportFromCjs as E, commonjsGlobal as F, index$1 as G, build$1 as H, index as I, preview$1 as J, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, isInNodeModules as i, resolveBaseUrl as j, getDepOptimizationConfig as k, loadConfigFromFile as l, isDepsOptimizerEnabled as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeConfig as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, mergeAlias as u, createFilter as v, send$2 as w, createLogger as x, searchForWorkspaceRoot as y, isFileServingAllowed as z };