mapperTab.js 668 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310
  1. var mapperTab = (function () {
  2. 'use strict';
  3. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  4. function getAugmentedNamespace(n) {
  5. if (n.__esModule) return n;
  6. var f = n.default;
  7. if (typeof f == "function") {
  8. var a = function a () {
  9. if (this instanceof a) {
  10. return Reflect.construct(f, arguments, this.constructor);
  11. }
  12. return f.apply(this, arguments);
  13. };
  14. a.prototype = f.prototype;
  15. } else a = {};
  16. Object.defineProperty(a, '__esModule', {value: true});
  17. Object.keys(n).forEach(function (k) {
  18. var d = Object.getOwnPropertyDescriptor(n, k);
  19. Object.defineProperty(a, k, d.get ? d : {
  20. enumerable: true,
  21. get: function () {
  22. return n[k];
  23. }
  24. });
  25. });
  26. return a;
  27. }
  28. var bidiTab = {};
  29. var BidiMapper = {};
  30. var BidiServer$1 = {};
  31. var EventEmitter$1 = {};
  32. function mitt(n){return {all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e]);},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]));},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e);}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e);});}}}
  33. var mitt$1 = /*#__PURE__*/Object.freeze({
  34. __proto__: null,
  35. default: mitt
  36. });
  37. var require$$0 = /*@__PURE__*/getAugmentedNamespace(mitt$1);
  38. var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  39. return (mod && mod.__esModule) ? mod : { "default": mod };
  40. };
  41. Object.defineProperty(EventEmitter$1, "__esModule", { value: true });
  42. EventEmitter$1.EventEmitter = void 0;
  43. /**
  44. * Copyright 2022 Google LLC.
  45. * Copyright (c) Microsoft Corporation.
  46. *
  47. * Licensed under the Apache License, Version 2.0 (the "License");
  48. * you may not use this file except in compliance with the License.
  49. * You may obtain a copy of the License at
  50. *
  51. * http://www.apache.org/licenses/LICENSE-2.0
  52. *
  53. * Unless required by applicable law or agreed to in writing, software
  54. * distributed under the License is distributed on an "AS IS" BASIS,
  55. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56. * See the License for the specific language governing permissions and
  57. * limitations under the License.
  58. */
  59. const mitt_1 = __importDefault$2(require$$0);
  60. class EventEmitter {
  61. #emitter = (0, mitt_1.default)();
  62. on(type, handler) {
  63. this.#emitter.on(type, handler);
  64. return this;
  65. }
  66. /**
  67. * Like `on` but the listener will only be fired once and then it will be removed.
  68. * @param event The event you'd like to listen to
  69. * @param handler The handler function to run when the event occurs
  70. * @return `this` to enable chaining method calls.
  71. */
  72. once(event, handler) {
  73. const onceHandler = (eventData) => {
  74. handler(eventData);
  75. this.off(event, onceHandler);
  76. };
  77. return this.on(event, onceHandler);
  78. }
  79. off(type, handler) {
  80. this.#emitter.off(type, handler);
  81. return this;
  82. }
  83. /**
  84. * Emits an event and call any associated listeners.
  85. *
  86. * @param event The event to emit.
  87. * @param eventData Any data to emit with the event.
  88. * @return `true` if there are any listeners, `false` otherwise.
  89. */
  90. emit(event, eventData) {
  91. this.#emitter.emit(event, eventData);
  92. }
  93. /**
  94. * Removes all listeners. If given an event argument, it will remove only
  95. * listeners for that event.
  96. * @param event - the event to remove listeners for.
  97. * @returns `this` to enable you to chain method calls.
  98. */
  99. removeAllListeners(event) {
  100. if (event) {
  101. this.#emitter.all.delete(event);
  102. }
  103. else {
  104. this.#emitter.all.clear();
  105. }
  106. return this;
  107. }
  108. }
  109. EventEmitter$1.EventEmitter = EventEmitter;
  110. var log$1 = {};
  111. /**
  112. * Copyright 2021 Google LLC.
  113. * Copyright (c) Microsoft Corporation.
  114. *
  115. * Licensed under the Apache License, Version 2.0 (the "License");
  116. * you may not use this file except in compliance with the License.
  117. * You may obtain a copy of the License at
  118. *
  119. * http://www.apache.org/licenses/LICENSE-2.0
  120. *
  121. * Unless required by applicable law or agreed to in writing, software
  122. * distributed under the License is distributed on an "AS IS" BASIS,
  123. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  124. * See the License for the specific language governing permissions and
  125. * limitations under the License.
  126. */
  127. Object.defineProperty(log$1, "__esModule", { value: true });
  128. log$1.LogType = void 0;
  129. var LogType;
  130. (function (LogType) {
  131. // keep-sorted start
  132. LogType["bidi"] = "bidi";
  133. LogType["cdp"] = "cdp";
  134. LogType["debug"] = "debug";
  135. LogType["debugError"] = "debug:error";
  136. LogType["debugInfo"] = "debug:info";
  137. // keep-sorted end
  138. })(LogType || (log$1.LogType = LogType = {}));
  139. var ProcessingQueue$1 = {};
  140. /**
  141. * Copyright 2022 Google LLC.
  142. * Copyright (c) Microsoft Corporation.
  143. *
  144. * Licensed under the Apache License, Version 2.0 (the "License");
  145. * you may not use this file except in compliance with the License.
  146. * You may obtain a copy of the License at
  147. *
  148. * http://www.apache.org/licenses/LICENSE-2.0
  149. *
  150. * Unless required by applicable law or agreed to in writing, software
  151. * distributed under the License is distributed on an "AS IS" BASIS,
  152. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  153. * See the License for the specific language governing permissions and
  154. * limitations under the License.
  155. */
  156. Object.defineProperty(ProcessingQueue$1, "__esModule", { value: true });
  157. ProcessingQueue$1.ProcessingQueue = void 0;
  158. const log_js_1$d = log$1;
  159. class ProcessingQueue {
  160. static LOGGER_PREFIX = `${log_js_1$d.LogType.debug}:queue`;
  161. #logger;
  162. #processor;
  163. #queue = [];
  164. // Flag to keep only 1 active processor.
  165. #isProcessing = false;
  166. constructor(processor, logger) {
  167. this.#processor = processor;
  168. this.#logger = logger;
  169. }
  170. add(entry, name) {
  171. this.#queue.push([entry, name]);
  172. // No need in waiting. Just initialize processor if needed.
  173. void this.#processIfNeeded();
  174. }
  175. async #processIfNeeded() {
  176. if (this.#isProcessing) {
  177. return;
  178. }
  179. this.#isProcessing = true;
  180. while (this.#queue.length > 0) {
  181. const arrayEntry = this.#queue.shift();
  182. if (!arrayEntry) {
  183. continue;
  184. }
  185. const [entryPromise, name] = arrayEntry;
  186. this.#logger?.(ProcessingQueue.LOGGER_PREFIX, 'Processing event:', name);
  187. await entryPromise
  188. .then((entry) => {
  189. if (entry.kind === 'error') {
  190. this.#logger?.(log_js_1$d.LogType.debugError, 'Event threw before sending:', entry.error.message, entry.error.stack);
  191. return;
  192. }
  193. return this.#processor(entry.value);
  194. })
  195. .catch((error) => {
  196. this.#logger?.(log_js_1$d.LogType.debugError, 'Event was not processed:', error?.message);
  197. });
  198. }
  199. this.#isProcessing = false;
  200. }
  201. }
  202. ProcessingQueue$1.ProcessingQueue = ProcessingQueue;
  203. var CommandProcessor$1 = {};
  204. var protocol = {};
  205. var cdp = {};
  206. Object.defineProperty(cdp, "__esModule", { value: true });
  207. var chromiumBidi = {};
  208. /**
  209. * Copyright 2023 Google LLC.
  210. * Copyright (c) Microsoft Corporation.
  211. *
  212. * Licensed under the Apache License, Version 2.0 (the "License");
  213. * you may not use this file except in compliance with the License.
  214. * You may obtain a copy of the License at
  215. *
  216. * http://www.apache.org/licenses/LICENSE-2.0
  217. *
  218. * Unless required by applicable law or agreed to in writing, software
  219. * distributed under the License is distributed on an "AS IS" BASIS,
  220. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  221. * See the License for the specific language governing permissions and
  222. * limitations under the License.
  223. */
  224. Object.defineProperty(chromiumBidi, "__esModule", { value: true });
  225. chromiumBidi.EVENT_NAMES = chromiumBidi.Network = chromiumBidi.BrowsingContext = chromiumBidi.Log = chromiumBidi.Script = chromiumBidi.BiDiModule = void 0;
  226. // keep-sorted end
  227. var BiDiModule;
  228. (function (BiDiModule) {
  229. // keep-sorted start
  230. BiDiModule["Browser"] = "browser";
  231. BiDiModule["BrowsingContext"] = "browsingContext";
  232. BiDiModule["Cdp"] = "cdp";
  233. BiDiModule["Input"] = "input";
  234. BiDiModule["Log"] = "log";
  235. BiDiModule["Network"] = "network";
  236. BiDiModule["Script"] = "script";
  237. BiDiModule["Session"] = "session";
  238. // keep-sorted end
  239. })(BiDiModule || (chromiumBidi.BiDiModule = BiDiModule = {}));
  240. var Script$1;
  241. (function (Script) {
  242. (function (EventNames) {
  243. // keep-sorted start
  244. EventNames["Message"] = "script.message";
  245. EventNames["RealmCreated"] = "script.realmCreated";
  246. EventNames["RealmDestroyed"] = "script.realmDestroyed";
  247. // keep-sorted end
  248. })(Script.EventNames || (Script.EventNames = {}));
  249. })(Script$1 || (chromiumBidi.Script = Script$1 = {}));
  250. var Log;
  251. (function (Log) {
  252. (function (EventNames) {
  253. EventNames["LogEntryAdded"] = "log.entryAdded";
  254. })(Log.EventNames || (Log.EventNames = {}));
  255. })(Log || (chromiumBidi.Log = Log = {}));
  256. var BrowsingContext$1;
  257. (function (BrowsingContext) {
  258. (function (EventNames) {
  259. // keep-sorted start
  260. EventNames["ContextCreated"] = "browsingContext.contextCreated";
  261. EventNames["ContextDestroyed"] = "browsingContext.contextDestroyed";
  262. EventNames["DomContentLoaded"] = "browsingContext.domContentLoaded";
  263. EventNames["DownloadWillBegin"] = "browsingContext.downloadWillBegin";
  264. EventNames["FragmentNavigated"] = "browsingContext.fragmentNavigated";
  265. EventNames["Load"] = "browsingContext.load";
  266. EventNames["NavigationAborted"] = "browsingContext.navigationAborted";
  267. EventNames["NavigationFailed"] = "browsingContext.navigationFailed";
  268. EventNames["NavigationStarted"] = "browsingContext.navigationStarted";
  269. EventNames["UserPromptClosed"] = "browsingContext.userPromptClosed";
  270. EventNames["UserPromptOpened"] = "browsingContext.userPromptOpened";
  271. // keep-sorted end
  272. })(BrowsingContext.EventNames || (BrowsingContext.EventNames = {}));
  273. })(BrowsingContext$1 || (chromiumBidi.BrowsingContext = BrowsingContext$1 = {}));
  274. var Network$1;
  275. (function (Network) {
  276. (function (EventNames) {
  277. // keep-sorted start
  278. EventNames["AuthRequired"] = "network.authRequired";
  279. EventNames["BeforeRequestSent"] = "network.beforeRequestSent";
  280. EventNames["FetchError"] = "network.fetchError";
  281. EventNames["ResponseCompleted"] = "network.responseCompleted";
  282. EventNames["ResponseStarted"] = "network.responseStarted";
  283. // keep-sorted end
  284. })(Network.EventNames || (Network.EventNames = {}));
  285. })(Network$1 || (chromiumBidi.Network = Network$1 = {}));
  286. chromiumBidi.EVENT_NAMES = new Set([
  287. // keep-sorted start
  288. ...Object.values(BiDiModule),
  289. ...Object.values(BrowsingContext$1.EventNames),
  290. ...Object.values(Log.EventNames),
  291. ...Object.values(Network$1.EventNames),
  292. ...Object.values(Script$1.EventNames),
  293. // keep-sorted end
  294. ]);
  295. var webdriverBidi$1 = {};
  296. /**
  297. * Copyright 2024 Google LLC.
  298. * Copyright (c) Microsoft Corporation.
  299. *
  300. * Licensed under the Apache License, Version 2.0 (the "License");
  301. * you may not use this file except in compliance with the License.
  302. * You may obtain a copy of the License at
  303. *
  304. * http://www.apache.org/licenses/LICENSE-2.0
  305. *
  306. * Unless required by applicable law or agreed to in writing, software
  307. * distributed under the License is distributed on an "AS IS" BASIS,
  308. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  309. * See the License for the specific language governing permissions and
  310. * limitations under the License.
  311. */
  312. Object.defineProperty(webdriverBidi$1, "__esModule", { value: true });
  313. var ErrorResponse = {};
  314. Object.defineProperty(ErrorResponse, "__esModule", { value: true });
  315. ErrorResponse.UnderspecifiedStoragePartitionException = ErrorResponse.UnableToSetFileInputException = ErrorResponse.UnableToSetCookieException = ErrorResponse.NoSuchStoragePartitionException = ErrorResponse.UnsupportedOperationException = ErrorResponse.UnableToCloseBrowserException = ErrorResponse.UnableToCaptureScreenException = ErrorResponse.UnknownErrorException = ErrorResponse.UnknownCommandException = ErrorResponse.SessionNotCreatedException = ErrorResponse.NoSuchUserContextException = ErrorResponse.NoSuchScriptException = ErrorResponse.NoSuchRequestException = ErrorResponse.NoSuchNodeException = ErrorResponse.NoSuchInterceptException = ErrorResponse.NoSuchHistoryEntryException = ErrorResponse.NoSuchHandleException = ErrorResponse.NoSuchFrameException = ErrorResponse.NoSuchElementException = ErrorResponse.NoSuchAlertException = ErrorResponse.MoveTargetOutOfBoundsException = ErrorResponse.InvalidSessionIdException = ErrorResponse.InvalidSelectorException = ErrorResponse.InvalidArgumentException = ErrorResponse.Exception = void 0;
  316. class Exception {
  317. error;
  318. message;
  319. stacktrace;
  320. constructor(error, message, stacktrace) {
  321. this.error = error;
  322. this.message = message;
  323. this.stacktrace = stacktrace;
  324. }
  325. toErrorResponse(commandId) {
  326. return {
  327. type: 'error',
  328. id: commandId,
  329. error: this.error,
  330. message: this.message,
  331. stacktrace: this.stacktrace,
  332. };
  333. }
  334. }
  335. ErrorResponse.Exception = Exception;
  336. class InvalidArgumentException extends Exception {
  337. constructor(message, stacktrace) {
  338. super("invalid argument" /* ErrorCode.InvalidArgument */, message, stacktrace);
  339. }
  340. }
  341. ErrorResponse.InvalidArgumentException = InvalidArgumentException;
  342. class InvalidSelectorException extends Exception {
  343. constructor(message, stacktrace) {
  344. super("invalid selector" /* ErrorCode.InvalidSelector */, message, stacktrace);
  345. }
  346. }
  347. ErrorResponse.InvalidSelectorException = InvalidSelectorException;
  348. class InvalidSessionIdException extends Exception {
  349. constructor(message, stacktrace) {
  350. super("invalid session id" /* ErrorCode.InvalidSessionId */, message, stacktrace);
  351. }
  352. }
  353. ErrorResponse.InvalidSessionIdException = InvalidSessionIdException;
  354. class MoveTargetOutOfBoundsException extends Exception {
  355. constructor(message, stacktrace) {
  356. super("move target out of bounds" /* ErrorCode.MoveTargetOutOfBounds */, message, stacktrace);
  357. }
  358. }
  359. ErrorResponse.MoveTargetOutOfBoundsException = MoveTargetOutOfBoundsException;
  360. class NoSuchAlertException extends Exception {
  361. constructor(message, stacktrace) {
  362. super("no such alert" /* ErrorCode.NoSuchAlert */, message, stacktrace);
  363. }
  364. }
  365. ErrorResponse.NoSuchAlertException = NoSuchAlertException;
  366. class NoSuchElementException extends Exception {
  367. constructor(message, stacktrace) {
  368. super("no such element" /* ErrorCode.NoSuchElement */, message, stacktrace);
  369. }
  370. }
  371. ErrorResponse.NoSuchElementException = NoSuchElementException;
  372. class NoSuchFrameException extends Exception {
  373. constructor(message, stacktrace) {
  374. super("no such frame" /* ErrorCode.NoSuchFrame */, message, stacktrace);
  375. }
  376. }
  377. ErrorResponse.NoSuchFrameException = NoSuchFrameException;
  378. class NoSuchHandleException extends Exception {
  379. constructor(message, stacktrace) {
  380. super("no such handle" /* ErrorCode.NoSuchHandle */, message, stacktrace);
  381. }
  382. }
  383. ErrorResponse.NoSuchHandleException = NoSuchHandleException;
  384. class NoSuchHistoryEntryException extends Exception {
  385. constructor(message, stacktrace) {
  386. super("no such history entry" /* ErrorCode.NoSuchHistoryEntry */, message, stacktrace);
  387. }
  388. }
  389. ErrorResponse.NoSuchHistoryEntryException = NoSuchHistoryEntryException;
  390. class NoSuchInterceptException extends Exception {
  391. constructor(message, stacktrace) {
  392. super("no such intercept" /* ErrorCode.NoSuchIntercept */, message, stacktrace);
  393. }
  394. }
  395. ErrorResponse.NoSuchInterceptException = NoSuchInterceptException;
  396. class NoSuchNodeException extends Exception {
  397. constructor(message, stacktrace) {
  398. super("no such node" /* ErrorCode.NoSuchNode */, message, stacktrace);
  399. }
  400. }
  401. ErrorResponse.NoSuchNodeException = NoSuchNodeException;
  402. class NoSuchRequestException extends Exception {
  403. constructor(message, stacktrace) {
  404. super("no such request" /* ErrorCode.NoSuchRequest */, message, stacktrace);
  405. }
  406. }
  407. ErrorResponse.NoSuchRequestException = NoSuchRequestException;
  408. class NoSuchScriptException extends Exception {
  409. constructor(message, stacktrace) {
  410. super("no such script" /* ErrorCode.NoSuchScript */, message, stacktrace);
  411. }
  412. }
  413. ErrorResponse.NoSuchScriptException = NoSuchScriptException;
  414. class NoSuchUserContextException extends Exception {
  415. constructor(message, stacktrace) {
  416. super("no such user context" /* ErrorCode.NoSuchUserContext */, message, stacktrace);
  417. }
  418. }
  419. ErrorResponse.NoSuchUserContextException = NoSuchUserContextException;
  420. class SessionNotCreatedException extends Exception {
  421. constructor(message, stacktrace) {
  422. super("session not created" /* ErrorCode.SessionNotCreated */, message, stacktrace);
  423. }
  424. }
  425. ErrorResponse.SessionNotCreatedException = SessionNotCreatedException;
  426. class UnknownCommandException extends Exception {
  427. constructor(message, stacktrace) {
  428. super("unknown command" /* ErrorCode.UnknownCommand */, message, stacktrace);
  429. }
  430. }
  431. ErrorResponse.UnknownCommandException = UnknownCommandException;
  432. class UnknownErrorException extends Exception {
  433. constructor(message, stacktrace = new Error().stack) {
  434. super("unknown error" /* ErrorCode.UnknownError */, message, stacktrace);
  435. }
  436. }
  437. ErrorResponse.UnknownErrorException = UnknownErrorException;
  438. class UnableToCaptureScreenException extends Exception {
  439. constructor(message, stacktrace) {
  440. super("unable to capture screen" /* ErrorCode.UnableToCaptureScreen */, message, stacktrace);
  441. }
  442. }
  443. ErrorResponse.UnableToCaptureScreenException = UnableToCaptureScreenException;
  444. class UnableToCloseBrowserException extends Exception {
  445. constructor(message, stacktrace) {
  446. super("unable to close browser" /* ErrorCode.UnableToCloseBrowser */, message, stacktrace);
  447. }
  448. }
  449. ErrorResponse.UnableToCloseBrowserException = UnableToCloseBrowserException;
  450. class UnsupportedOperationException extends Exception {
  451. constructor(message, stacktrace) {
  452. super("unsupported operation" /* ErrorCode.UnsupportedOperation */, message, stacktrace);
  453. }
  454. }
  455. ErrorResponse.UnsupportedOperationException = UnsupportedOperationException;
  456. class NoSuchStoragePartitionException extends Exception {
  457. constructor(message, stacktrace) {
  458. super("no such storage partition" /* ErrorCode.NoSuchStoragePartition */, message, stacktrace);
  459. }
  460. }
  461. ErrorResponse.NoSuchStoragePartitionException = NoSuchStoragePartitionException;
  462. class UnableToSetCookieException extends Exception {
  463. constructor(message, stacktrace) {
  464. super("unable to set cookie" /* ErrorCode.UnableToSetCookie */, message, stacktrace);
  465. }
  466. }
  467. ErrorResponse.UnableToSetCookieException = UnableToSetCookieException;
  468. class UnableToSetFileInputException extends Exception {
  469. constructor(message, stacktrace) {
  470. super("unable to set file input" /* ErrorCode.UnableToSetFileInput */, message, stacktrace);
  471. }
  472. }
  473. ErrorResponse.UnableToSetFileInputException = UnableToSetFileInputException;
  474. class UnderspecifiedStoragePartitionException extends Exception {
  475. constructor(message, stacktrace) {
  476. super("underspecified storage partition" /* ErrorCode.UnderspecifiedStoragePartition */, message, stacktrace);
  477. }
  478. }
  479. ErrorResponse.UnderspecifiedStoragePartitionException = UnderspecifiedStoragePartitionException;
  480. var webdriverBidiPermissions$1 = {};
  481. /**
  482. * Copyright 2024 Google LLC.
  483. * Copyright (c) Microsoft Corporation.
  484. *
  485. * Licensed under the Apache License, Version 2.0 (the "License");
  486. * you may not use this file except in compliance with the License.
  487. * You may obtain a copy of the License at
  488. *
  489. * http://www.apache.org/licenses/LICENSE-2.0
  490. *
  491. * Unless required by applicable law or agreed to in writing, software
  492. * distributed under the License is distributed on an "AS IS" BASIS,
  493. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  494. * See the License for the specific language governing permissions and
  495. * limitations under the License.
  496. */
  497. Object.defineProperty(webdriverBidiPermissions$1, "__esModule", { value: true });
  498. (function (exports) {
  499. var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  500. if (k2 === undefined) k2 = k;
  501. var desc = Object.getOwnPropertyDescriptor(m, k);
  502. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  503. desc = { enumerable: true, get: function() { return m[k]; } };
  504. }
  505. Object.defineProperty(o, k2, desc);
  506. }) : (function(o, m, k, k2) {
  507. if (k2 === undefined) k2 = k;
  508. o[k2] = m[k];
  509. }));
  510. var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
  511. Object.defineProperty(o, "default", { enumerable: true, value: v });
  512. }) : function(o, v) {
  513. o["default"] = v;
  514. });
  515. var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
  516. if (mod && mod.__esModule) return mod;
  517. var result = {};
  518. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  519. __setModuleDefault(result, mod);
  520. return result;
  521. };
  522. var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
  523. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  524. };
  525. Object.defineProperty(exports, "__esModule", { value: true });
  526. exports.ChromiumBidi = exports.Cdp = void 0;
  527. /**
  528. * Copyright 2023 Google LLC.
  529. * Copyright (c) Microsoft Corporation.
  530. *
  531. * Licensed under the Apache License, Version 2.0 (the "License");
  532. * you may not use this file except in compliance with the License.
  533. * You may obtain a copy of the License at
  534. *
  535. * http://www.apache.org/licenses/LICENSE-2.0
  536. *
  537. * Unless required by applicable law or agreed to in writing, software
  538. * distributed under the License is distributed on an "AS IS" BASIS,
  539. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  540. * See the License for the specific language governing permissions and
  541. * limitations under the License.
  542. */
  543. exports.Cdp = __importStar(cdp);
  544. exports.ChromiumBidi = __importStar(chromiumBidi);
  545. __exportStar(webdriverBidi$1, exports);
  546. __exportStar(ErrorResponse, exports);
  547. __exportStar(webdriverBidiPermissions$1, exports);
  548. } (protocol));
  549. var BidiNoOpParser$1 = {};
  550. /**
  551. * Copyright 2023 Google LLC.
  552. * Copyright (c) Microsoft Corporation.
  553. *
  554. * Licensed under the Apache License, Version 2.0 (the "License");
  555. * you may not use this file except in compliance with the License.
  556. * You may obtain a copy of the License at
  557. *
  558. * http://www.apache.org/licenses/LICENSE-2.0
  559. *
  560. * Unless required by applicable law or agreed to in writing, software
  561. * distributed under the License is distributed on an "AS IS" BASIS,
  562. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  563. * See the License for the specific language governing permissions and
  564. * limitations under the License.
  565. */
  566. Object.defineProperty(BidiNoOpParser$1, "__esModule", { value: true });
  567. BidiNoOpParser$1.BidiNoOpParser = void 0;
  568. class BidiNoOpParser {
  569. // Browser domain
  570. // keep-sorted start block=yes
  571. parseRemoveUserContextParams(params) {
  572. return params;
  573. }
  574. // keep-sorted end
  575. // Browsing Context domain
  576. // keep-sorted start block=yes
  577. parseActivateParams(params) {
  578. return params;
  579. }
  580. parseCaptureScreenshotParams(params) {
  581. return params;
  582. }
  583. parseCloseParams(params) {
  584. return params;
  585. }
  586. parseCreateParams(params) {
  587. return params;
  588. }
  589. parseGetTreeParams(params) {
  590. return params;
  591. }
  592. parseHandleUserPromptParams(params) {
  593. return params;
  594. }
  595. parseLocateNodesParams(params) {
  596. return params;
  597. }
  598. parseNavigateParams(params) {
  599. return params;
  600. }
  601. parsePrintParams(params) {
  602. return params;
  603. }
  604. parseReloadParams(params) {
  605. return params;
  606. }
  607. parseSetViewportParams(params) {
  608. return params;
  609. }
  610. parseTraverseHistoryParams(params) {
  611. return params;
  612. }
  613. // keep-sorted end
  614. // CDP domain
  615. // keep-sorted start block=yes
  616. parseGetSessionParams(params) {
  617. return params;
  618. }
  619. parseResolveRealmParams(params) {
  620. return params;
  621. }
  622. parseSendCommandParams(params) {
  623. return params;
  624. }
  625. // keep-sorted end
  626. // Script domain
  627. // keep-sorted start block=yes
  628. parseAddPreloadScriptParams(params) {
  629. return params;
  630. }
  631. parseCallFunctionParams(params) {
  632. return params;
  633. }
  634. parseDisownParams(params) {
  635. return params;
  636. }
  637. parseEvaluateParams(params) {
  638. return params;
  639. }
  640. parseGetRealmsParams(params) {
  641. return params;
  642. }
  643. parseRemovePreloadScriptParams(params) {
  644. return params;
  645. }
  646. // keep-sorted end
  647. // Input domain
  648. // keep-sorted start block=yes
  649. parsePerformActionsParams(params) {
  650. return params;
  651. }
  652. parseReleaseActionsParams(params) {
  653. return params;
  654. }
  655. parseSetFilesParams(params) {
  656. return params;
  657. }
  658. // keep-sorted end
  659. // Network domain
  660. // keep-sorted start block=yes
  661. parseAddInterceptParams(params) {
  662. return params;
  663. }
  664. parseContinueRequestParams(params) {
  665. return params;
  666. }
  667. parseContinueResponseParams(params) {
  668. return params;
  669. }
  670. parseContinueWithAuthParams(params) {
  671. return params;
  672. }
  673. parseFailRequestParams(params) {
  674. return params;
  675. }
  676. parseProvideResponseParams(params) {
  677. return params;
  678. }
  679. parseRemoveInterceptParams(params) {
  680. return params;
  681. }
  682. // keep-sorted end
  683. // Permissions domain
  684. // keep-sorted start block=yes
  685. parseSetPermissionsParams(params) {
  686. return params;
  687. }
  688. // keep-sorted end
  689. // Session domain
  690. // keep-sorted start block=yes
  691. parseSubscribeParams(params) {
  692. return params;
  693. }
  694. // keep-sorted end
  695. // Storage domain
  696. // keep-sorted start block=yes
  697. parseDeleteCookiesParams(params) {
  698. return params;
  699. }
  700. parseGetCookiesParams(params) {
  701. return params;
  702. }
  703. parseSetCookieParams(params) {
  704. return params;
  705. }
  706. }
  707. BidiNoOpParser$1.BidiNoOpParser = BidiNoOpParser;
  708. var BrowserProcessor$1 = {};
  709. /**
  710. * Copyright 2023 Google LLC.
  711. * Copyright (c) Microsoft Corporation.
  712. *
  713. * Licensed under the Apache License, Version 2.0 (the "License");
  714. * you may not use this file except in compliance with the License.
  715. * You may obtain a copy of the License at
  716. *
  717. * http://www.apache.org/licenses/LICENSE-2.0
  718. *
  719. * Unless required by applicable law or agreed to in writing, software
  720. * distributed under the License is distributed on an "AS IS" BASIS,
  721. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  722. * See the License for the specific language governing permissions and
  723. * limitations under the License.
  724. */
  725. Object.defineProperty(BrowserProcessor$1, "__esModule", { value: true });
  726. BrowserProcessor$1.BrowserProcessor = void 0;
  727. const protocol_js_1$n = protocol;
  728. class BrowserProcessor {
  729. #browserCdpClient;
  730. constructor(browserCdpClient) {
  731. this.#browserCdpClient = browserCdpClient;
  732. }
  733. close() {
  734. // Ensure that it is put at the end of the event loop.
  735. // This way we send back the response before closing the tab.
  736. setTimeout(() => this.#browserCdpClient.sendCommand('Browser.close'), 0);
  737. return {};
  738. }
  739. async createUserContext(params) {
  740. const request = {
  741. proxyServer: params['goog:proxyServer'] ?? undefined,
  742. };
  743. const proxyBypassList = params['goog:proxyBypassList'] ?? undefined;
  744. if (proxyBypassList) {
  745. request.proxyBypassList = proxyBypassList.join(',');
  746. }
  747. const context = await this.#browserCdpClient.sendCommand('Target.createBrowserContext', request);
  748. return {
  749. userContext: context.browserContextId,
  750. };
  751. }
  752. async removeUserContext(params) {
  753. const userContext = params.userContext;
  754. if (userContext === 'default') {
  755. throw new protocol_js_1$n.InvalidArgumentException('`default` user context cannot be removed');
  756. }
  757. try {
  758. await this.#browserCdpClient.sendCommand('Target.disposeBrowserContext', {
  759. browserContextId: userContext,
  760. });
  761. }
  762. catch (err) {
  763. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/devtools/protocol/target_handler.cc;l=1424;drc=c686e8f4fd379312469fe018f5c390e9c8f20d0d
  764. if (err.message.startsWith('Failed to find context with id')) {
  765. throw new protocol_js_1$n.NoSuchUserContextException(err.message);
  766. }
  767. throw err;
  768. }
  769. return {};
  770. }
  771. async getUserContexts() {
  772. const result = await this.#browserCdpClient.sendCommand('Target.getBrowserContexts');
  773. return {
  774. userContexts: [
  775. {
  776. userContext: 'default',
  777. },
  778. ...result.browserContextIds.map((id) => {
  779. return {
  780. userContext: id,
  781. };
  782. }),
  783. ],
  784. };
  785. }
  786. }
  787. BrowserProcessor$1.BrowserProcessor = BrowserProcessor;
  788. var CdpProcessor$1 = {};
  789. /**
  790. * Copyright 2023 Google LLC.
  791. * Copyright (c) Microsoft Corporation.
  792. *
  793. * Licensed under the Apache License, Version 2.0 (the "License");
  794. * you may not use this file except in compliance with the License.
  795. * You may obtain a copy of the License at
  796. *
  797. * http://www.apache.org/licenses/LICENSE-2.0
  798. *
  799. * Unless required by applicable law or agreed to in writing, software
  800. * distributed under the License is distributed on an "AS IS" BASIS,
  801. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  802. * See the License for the specific language governing permissions and
  803. * limitations under the License.
  804. */
  805. Object.defineProperty(CdpProcessor$1, "__esModule", { value: true });
  806. CdpProcessor$1.CdpProcessor = void 0;
  807. const protocol_js_1$m = protocol;
  808. class CdpProcessor {
  809. #browsingContextStorage;
  810. #realmStorage;
  811. #cdpConnection;
  812. #browserCdpClient;
  813. constructor(browsingContextStorage, realmStorage, cdpConnection, browserCdpClient) {
  814. this.#browsingContextStorage = browsingContextStorage;
  815. this.#realmStorage = realmStorage;
  816. this.#cdpConnection = cdpConnection;
  817. this.#browserCdpClient = browserCdpClient;
  818. }
  819. getSession(params) {
  820. const context = params.context;
  821. const sessionId = this.#browsingContextStorage.getContext(context).cdpTarget.cdpSessionId;
  822. if (sessionId === undefined) {
  823. return {};
  824. }
  825. return { session: sessionId };
  826. }
  827. resolveRealm(params) {
  828. const context = params.realm;
  829. const realm = this.#realmStorage.getRealm({ realmId: context });
  830. if (realm === undefined) {
  831. throw new protocol_js_1$m.UnknownErrorException(`Could not find realm ${params.realm}`);
  832. }
  833. return { executionContextId: realm.executionContextId };
  834. }
  835. async sendCommand(params) {
  836. const client = params.session
  837. ? this.#cdpConnection.getCdpClient(params.session)
  838. : this.#browserCdpClient;
  839. const result = await client.sendCommand(params.method, params.params);
  840. return {
  841. result,
  842. session: params.session,
  843. };
  844. }
  845. }
  846. CdpProcessor$1.CdpProcessor = CdpProcessor;
  847. var BrowsingContextProcessor$1 = {};
  848. Object.defineProperty(BrowsingContextProcessor$1, "__esModule", { value: true });
  849. BrowsingContextProcessor$1.BrowsingContextProcessor = void 0;
  850. const protocol_js_1$l = protocol;
  851. class BrowsingContextProcessor {
  852. #browserCdpClient;
  853. #browsingContextStorage;
  854. constructor(browserCdpClient, browsingContextStorage) {
  855. this.#browserCdpClient = browserCdpClient;
  856. this.#browsingContextStorage = browsingContextStorage;
  857. }
  858. getTree(params) {
  859. const resultContexts = params.root === undefined
  860. ? this.#browsingContextStorage.getTopLevelContexts()
  861. : [this.#browsingContextStorage.getContext(params.root)];
  862. return {
  863. contexts: resultContexts.map((c) => c.serializeToBidiValue(params.maxDepth ?? Number.MAX_VALUE)),
  864. };
  865. }
  866. async create(params) {
  867. let referenceContext;
  868. let userContext = 'default';
  869. if (params.referenceContext !== undefined) {
  870. referenceContext = this.#browsingContextStorage.getContext(params.referenceContext);
  871. if (!referenceContext.isTopLevelContext()) {
  872. throw new protocol_js_1$l.InvalidArgumentException(`referenceContext should be a top-level context`);
  873. }
  874. userContext = referenceContext.userContext;
  875. }
  876. if (params.userContext !== undefined) {
  877. userContext = params.userContext;
  878. }
  879. let newWindow = false;
  880. switch (params.type) {
  881. case "tab" /* BrowsingContext.CreateType.Tab */:
  882. newWindow = false;
  883. break;
  884. case "window" /* BrowsingContext.CreateType.Window */:
  885. newWindow = true;
  886. break;
  887. }
  888. if (userContext !== 'default') {
  889. const existingContexts = this.#browsingContextStorage
  890. .getAllContexts()
  891. .filter((context) => context.userContext === userContext);
  892. if (!existingContexts.length) {
  893. // If there are no contexts in the given user context, we need to set
  894. // newWindow to true as newWindow=false will be rejected.
  895. newWindow = true;
  896. }
  897. }
  898. let result;
  899. try {
  900. result = await this.#browserCdpClient.sendCommand('Target.createTarget', {
  901. url: 'about:blank',
  902. newWindow,
  903. browserContextId: userContext === 'default' ? undefined : userContext,
  904. });
  905. }
  906. catch (err) {
  907. if (
  908. // See https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/devtools/protocol/target_handler.cc;l=90;drc=e80392ac11e48a691f4309964cab83a3a59e01c8
  909. err.message.startsWith('Failed to find browser context with id') ||
  910. // See https://source.chromium.org/chromium/chromium/src/+/main:headless/lib/browser/protocol/target_handler.cc;l=49;drc=e80392ac11e48a691f4309964cab83a3a59e01c8
  911. err.message === 'browserContextId') {
  912. throw new protocol_js_1$l.NoSuchUserContextException(`The context ${userContext} was not found`);
  913. }
  914. throw err;
  915. }
  916. // Wait for the new tab to be loaded to avoid race conditions in the
  917. // `browsingContext` events, when the `browsingContext.domContentLoaded` and
  918. // `browsingContext.load` events from the initial `about:blank` navigation
  919. // are emitted after the next navigation is started.
  920. // Details: https://github.com/web-platform-tests/wpt/issues/35846
  921. const contextId = result.targetId;
  922. const context = this.#browsingContextStorage.getContext(contextId);
  923. await context.lifecycleLoaded();
  924. return { context: context.id };
  925. }
  926. navigate(params) {
  927. const context = this.#browsingContextStorage.getContext(params.context);
  928. return context.navigate(params.url, params.wait ?? "none" /* BrowsingContext.ReadinessState.None */);
  929. }
  930. reload(params) {
  931. const context = this.#browsingContextStorage.getContext(params.context);
  932. return context.reload(params.ignoreCache ?? false, params.wait ?? "none" /* BrowsingContext.ReadinessState.None */);
  933. }
  934. async activate(params) {
  935. const context = this.#browsingContextStorage.getContext(params.context);
  936. if (!context.isTopLevelContext()) {
  937. throw new protocol_js_1$l.InvalidArgumentException('Activation is only supported on the top-level context');
  938. }
  939. await context.activate();
  940. return {};
  941. }
  942. async captureScreenshot(params) {
  943. const context = this.#browsingContextStorage.getContext(params.context);
  944. return await context.captureScreenshot(params);
  945. }
  946. async print(params) {
  947. const context = this.#browsingContextStorage.getContext(params.context);
  948. return await context.print(params);
  949. }
  950. async setViewport(params) {
  951. const context = this.#browsingContextStorage.getContext(params.context);
  952. if (!context.isTopLevelContext()) {
  953. throw new protocol_js_1$l.InvalidArgumentException('Emulating viewport is only supported on the top-level context');
  954. }
  955. await context.setViewport(params.viewport, params.devicePixelRatio);
  956. return {};
  957. }
  958. async traverseHistory(params) {
  959. const context = this.#browsingContextStorage.getContext(params.context);
  960. if (!context) {
  961. throw new protocol_js_1$l.InvalidArgumentException(`No browsing context with id ${params.context}`);
  962. }
  963. await context.traverseHistory(params.delta);
  964. return {};
  965. }
  966. async handleUserPrompt(params) {
  967. const context = this.#browsingContextStorage.getContext(params.context);
  968. try {
  969. await context.handleUserPrompt(params);
  970. }
  971. catch (error) {
  972. // Heuristically determine the error
  973. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/devtools/protocol/page_handler.cc;l=1085?q=%22No%20dialog%20is%20showing%22&ss=chromium
  974. if (error.message?.includes('No dialog is showing')) {
  975. throw new protocol_js_1$l.NoSuchAlertException('No dialog is showing');
  976. }
  977. throw error;
  978. }
  979. return {};
  980. }
  981. async close(params) {
  982. const context = this.#browsingContextStorage.getContext(params.context);
  983. if (!context.isTopLevelContext()) {
  984. throw new protocol_js_1$l.InvalidArgumentException(`Non top-level browsing context ${context.id} cannot be closed.`);
  985. }
  986. try {
  987. const detachedFromTargetPromise = new Promise((resolve) => {
  988. const onContextDestroyed = (event) => {
  989. if (event.targetId === params.context) {
  990. this.#browserCdpClient.off('Target.detachedFromTarget', onContextDestroyed);
  991. resolve();
  992. }
  993. };
  994. this.#browserCdpClient.on('Target.detachedFromTarget', onContextDestroyed);
  995. });
  996. if (params.promptUnload) {
  997. await context.close();
  998. }
  999. else {
  1000. await this.#browserCdpClient.sendCommand('Target.closeTarget', {
  1001. targetId: params.context,
  1002. });
  1003. }
  1004. // Sometimes CDP command finishes before `detachedFromTarget` event,
  1005. // sometimes after. Wait for the CDP command to be finished, and then wait
  1006. // for `detachedFromTarget` if it hasn't emitted.
  1007. await detachedFromTargetPromise;
  1008. }
  1009. catch (error) {
  1010. // Swallow error that arise from the page being destroyed
  1011. // Example is navigating to faulty SSL certificate
  1012. if (!(error.code === -32000 /* CdpErrorConstants.GENERIC_ERROR */ &&
  1013. error.message === 'Not attached to an active page')) {
  1014. throw error;
  1015. }
  1016. }
  1017. return {};
  1018. }
  1019. async locateNodes(params) {
  1020. const context = this.#browsingContextStorage.getContext(params.context);
  1021. return await context.locateNodes(params);
  1022. }
  1023. }
  1024. BrowsingContextProcessor$1.BrowsingContextProcessor = BrowsingContextProcessor;
  1025. var InputProcessor$1 = {};
  1026. var assert$1 = {};
  1027. Object.defineProperty(assert$1, "__esModule", { value: true });
  1028. assert$1.assert = void 0;
  1029. /**
  1030. * Copyright 2023 Google LLC.
  1031. * Copyright (c) Microsoft Corporation.
  1032. *
  1033. * Licensed under the Apache License, Version 2.0 (the "License");
  1034. * you may not use this file except in compliance with the License.
  1035. * You may obtain a copy of the License at
  1036. *
  1037. * http://www.apache.org/licenses/LICENSE-2.0
  1038. *
  1039. * Unless required by applicable law or agreed to in writing, software
  1040. * distributed under the License is distributed on an "AS IS" BASIS,
  1041. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1042. * See the License for the specific language governing permissions and
  1043. * limitations under the License.
  1044. */
  1045. function assert(predicate, message) {
  1046. if (!predicate) {
  1047. throw new Error(message ?? 'Internal assertion failed.');
  1048. }
  1049. }
  1050. assert$1.assert = assert;
  1051. var ActionDispatcher$1 = {};
  1052. var InputSource = {};
  1053. /**
  1054. * Copyright 2023 Google LLC.
  1055. * Copyright (c) Microsoft Corporation.
  1056. *
  1057. * Licensed under the Apache License, Version 2.0 (the "License");
  1058. * you may not use this file except in compliance with the License.
  1059. * You may obtain a copy of the License at
  1060. *
  1061. * http://www.apache.org/licenses/LICENSE-2.0
  1062. *
  1063. * Unless required by applicable law or agreed to in writing, software
  1064. * distributed under the License is distributed on an "AS IS" BASIS,
  1065. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1066. * See the License for the specific language governing permissions and
  1067. * limitations under the License.
  1068. */
  1069. Object.defineProperty(InputSource, "__esModule", { value: true });
  1070. InputSource.WheelSource = InputSource.PointerSource = InputSource.KeySource = InputSource.NoneSource = void 0;
  1071. class NoneSource {
  1072. type = "none" /* SourceType.None */;
  1073. }
  1074. InputSource.NoneSource = NoneSource;
  1075. class KeySource {
  1076. type = "key" /* SourceType.Key */;
  1077. pressed = new Set();
  1078. // This is a bitfield that matches the modifiers parameter of
  1079. // https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchKeyEvent
  1080. #modifiers = 0;
  1081. get modifiers() {
  1082. return this.#modifiers;
  1083. }
  1084. get alt() {
  1085. return (this.#modifiers & 1) === 1;
  1086. }
  1087. set alt(value) {
  1088. this.#setModifier(value, 1);
  1089. }
  1090. get ctrl() {
  1091. return (this.#modifiers & 2) === 2;
  1092. }
  1093. set ctrl(value) {
  1094. this.#setModifier(value, 2);
  1095. }
  1096. get meta() {
  1097. return (this.#modifiers & 4) === 4;
  1098. }
  1099. set meta(value) {
  1100. this.#setModifier(value, 4);
  1101. }
  1102. get shift() {
  1103. return (this.#modifiers & 8) === 8;
  1104. }
  1105. set shift(value) {
  1106. this.#setModifier(value, 8);
  1107. }
  1108. #setModifier(value, bit) {
  1109. if (value) {
  1110. this.#modifiers |= bit;
  1111. }
  1112. else {
  1113. this.#modifiers &= ~bit;
  1114. }
  1115. }
  1116. }
  1117. InputSource.KeySource = KeySource;
  1118. class PointerSource {
  1119. type = "pointer" /* SourceType.Pointer */;
  1120. subtype;
  1121. pointerId;
  1122. pressed = new Set();
  1123. x = 0;
  1124. y = 0;
  1125. constructor(id, subtype) {
  1126. this.pointerId = id;
  1127. this.subtype = subtype;
  1128. }
  1129. // This is a bitfield that matches the buttons parameter of
  1130. // https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchMouseEvent
  1131. get buttons() {
  1132. let buttons = 0;
  1133. for (const button of this.pressed) {
  1134. switch (button) {
  1135. case 0:
  1136. buttons |= 1;
  1137. break;
  1138. case 1:
  1139. buttons |= 4;
  1140. break;
  1141. case 2:
  1142. buttons |= 2;
  1143. break;
  1144. case 3:
  1145. buttons |= 8;
  1146. break;
  1147. case 4:
  1148. buttons |= 16;
  1149. break;
  1150. }
  1151. }
  1152. return buttons;
  1153. }
  1154. // --- Platform-specific code starts here ---
  1155. // Input.dispatchMouseEvent doesn't know the concept of double click, so we
  1156. // need to create the logic, similar to how it's done for OSes:
  1157. // https://source.chromium.org/chromium/chromium/src/+/refs/heads/main:ui/events/event.cc;l=479
  1158. static ClickContext = class ClickContext {
  1159. static #DOUBLE_CLICK_TIME_MS = 500;
  1160. static #MAX_DOUBLE_CLICK_RADIUS = 2;
  1161. count = 0;
  1162. #x;
  1163. #y;
  1164. #time;
  1165. constructor(x, y, time) {
  1166. this.#x = x;
  1167. this.#y = y;
  1168. this.#time = time;
  1169. }
  1170. compare(context) {
  1171. return (
  1172. // The click needs to be within a certain amount of ms.
  1173. context.#time - this.#time > ClickContext.#DOUBLE_CLICK_TIME_MS ||
  1174. // The click needs to be within a certain square radius.
  1175. Math.abs(context.#x - this.#x) >
  1176. ClickContext.#MAX_DOUBLE_CLICK_RADIUS ||
  1177. Math.abs(context.#y - this.#y) > ClickContext.#MAX_DOUBLE_CLICK_RADIUS);
  1178. }
  1179. };
  1180. #clickContexts = new Map();
  1181. setClickCount(button, context) {
  1182. let storedContext = this.#clickContexts.get(button);
  1183. if (!storedContext || storedContext.compare(context)) {
  1184. storedContext = context;
  1185. }
  1186. ++storedContext.count;
  1187. this.#clickContexts.set(button, storedContext);
  1188. return storedContext.count;
  1189. }
  1190. getClickCount(button) {
  1191. return this.#clickContexts.get(button)?.count ?? 0;
  1192. }
  1193. }
  1194. InputSource.PointerSource = PointerSource;
  1195. class WheelSource {
  1196. type = "wheel" /* SourceType.Wheel */;
  1197. }
  1198. InputSource.WheelSource = WheelSource;
  1199. var keyUtils = {};
  1200. /**
  1201. * Copyright 2023 Google LLC.
  1202. * Copyright (c) Microsoft Corporation.
  1203. *
  1204. * Licensed under the Apache License, Version 2.0 (the "License");
  1205. * you may not use this file except in compliance with the License.
  1206. * You may obtain a copy of the License at
  1207. *
  1208. * http://www.apache.org/licenses/LICENSE-2.0
  1209. *
  1210. * Unless required by applicable law or agreed to in writing, software
  1211. * distributed under the License is distributed on an "AS IS" BASIS,
  1212. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1213. * See the License for the specific language governing permissions and
  1214. * limitations under the License.
  1215. */
  1216. Object.defineProperty(keyUtils, "__esModule", { value: true });
  1217. keyUtils.getKeyLocation = keyUtils.getKeyCode = keyUtils.getNormalizedKey = void 0;
  1218. function getNormalizedKey(value) {
  1219. switch (value) {
  1220. case '\uE000':
  1221. return 'Unidentified';
  1222. case '\uE001':
  1223. return 'Cancel';
  1224. case '\uE002':
  1225. return 'Help';
  1226. case '\uE003':
  1227. return 'Backspace';
  1228. case '\uE004':
  1229. return 'Tab';
  1230. case '\uE005':
  1231. return 'Clear';
  1232. case '\uE006':
  1233. return 'Return';
  1234. case '\uE007':
  1235. return 'Enter';
  1236. case '\uE008':
  1237. return 'Shift';
  1238. case '\uE009':
  1239. return 'Control';
  1240. case '\uE00A':
  1241. return 'Alt';
  1242. case '\uE00B':
  1243. return 'Pause';
  1244. case '\uE00C':
  1245. return 'Escape';
  1246. case '\uE00D':
  1247. return ' ';
  1248. case '\uE00E':
  1249. return 'PageUp';
  1250. case '\uE00F':
  1251. return 'PageDown';
  1252. case '\uE010':
  1253. return 'End';
  1254. case '\uE011':
  1255. return 'Home';
  1256. case '\uE012':
  1257. return 'ArrowLeft';
  1258. case '\uE013':
  1259. return 'ArrowUp';
  1260. case '\uE014':
  1261. return 'ArrowRight';
  1262. case '\uE015':
  1263. return 'ArrowDown';
  1264. case '\uE016':
  1265. return 'Insert';
  1266. case '\uE017':
  1267. return 'Delete';
  1268. case '\uE018':
  1269. return ';';
  1270. case '\uE019':
  1271. return '=';
  1272. case '\uE01A':
  1273. return '0';
  1274. case '\uE01B':
  1275. return '1';
  1276. case '\uE01C':
  1277. return '2';
  1278. case '\uE01D':
  1279. return '3';
  1280. case '\uE01E':
  1281. return '4';
  1282. case '\uE01F':
  1283. return '5';
  1284. case '\uE020':
  1285. return '6';
  1286. case '\uE021':
  1287. return '7';
  1288. case '\uE022':
  1289. return '8';
  1290. case '\uE023':
  1291. return '9';
  1292. case '\uE024':
  1293. return '*';
  1294. case '\uE025':
  1295. return '+';
  1296. case '\uE026':
  1297. return ',';
  1298. case '\uE027':
  1299. return '-';
  1300. case '\uE028':
  1301. return '.';
  1302. case '\uE029':
  1303. return '/';
  1304. case '\uE031':
  1305. return 'F1';
  1306. case '\uE032':
  1307. return 'F2';
  1308. case '\uE033':
  1309. return 'F3';
  1310. case '\uE034':
  1311. return 'F4';
  1312. case '\uE035':
  1313. return 'F5';
  1314. case '\uE036':
  1315. return 'F6';
  1316. case '\uE037':
  1317. return 'F7';
  1318. case '\uE038':
  1319. return 'F8';
  1320. case '\uE039':
  1321. return 'F9';
  1322. case '\uE03A':
  1323. return 'F10';
  1324. case '\uE03B':
  1325. return 'F11';
  1326. case '\uE03C':
  1327. return 'F12';
  1328. case '\uE03D':
  1329. return 'Meta';
  1330. case '\uE040':
  1331. return 'ZenkakuHankaku';
  1332. case '\uE050':
  1333. return 'Shift';
  1334. case '\uE051':
  1335. return 'Control';
  1336. case '\uE052':
  1337. return 'Alt';
  1338. case '\uE053':
  1339. return 'Meta';
  1340. case '\uE054':
  1341. return 'PageUp';
  1342. case '\uE055':
  1343. return 'PageDown';
  1344. case '\uE056':
  1345. return 'End';
  1346. case '\uE057':
  1347. return 'Home';
  1348. case '\uE058':
  1349. return 'ArrowLeft';
  1350. case '\uE059':
  1351. return 'ArrowUp';
  1352. case '\uE05A':
  1353. return 'ArrowRight';
  1354. case '\uE05B':
  1355. return 'ArrowDown';
  1356. case '\uE05C':
  1357. return 'Insert';
  1358. case '\uE05D':
  1359. return 'Delete';
  1360. default:
  1361. return value;
  1362. }
  1363. }
  1364. keyUtils.getNormalizedKey = getNormalizedKey;
  1365. function getKeyCode(key) {
  1366. switch (key) {
  1367. case '`':
  1368. case '~':
  1369. return 'Backquote';
  1370. case '\\':
  1371. case '|':
  1372. return 'Backslash';
  1373. case '\uE003':
  1374. return 'Backspace';
  1375. case '[':
  1376. case '{':
  1377. return 'BracketLeft';
  1378. case ']':
  1379. case '}':
  1380. return 'BracketRight';
  1381. case ',':
  1382. case '<':
  1383. return 'Comma';
  1384. case '0':
  1385. case ')':
  1386. return 'Digit0';
  1387. case '1':
  1388. case '!':
  1389. return 'Digit1';
  1390. case '2':
  1391. case '@':
  1392. return 'Digit2';
  1393. case '3':
  1394. case '#':
  1395. return 'Digit3';
  1396. case '4':
  1397. case '$':
  1398. return 'Digit4';
  1399. case '5':
  1400. case '%':
  1401. return 'Digit5';
  1402. case '6':
  1403. case '^':
  1404. return 'Digit6';
  1405. case '7':
  1406. case '&':
  1407. return 'Digit7';
  1408. case '8':
  1409. case '*':
  1410. return 'Digit8';
  1411. case '9':
  1412. case '(':
  1413. return 'Digit9';
  1414. case '=':
  1415. case '+':
  1416. return 'Equal';
  1417. case 'a':
  1418. case 'A':
  1419. return 'KeyA';
  1420. case 'b':
  1421. case 'B':
  1422. return 'KeyB';
  1423. case 'c':
  1424. case 'C':
  1425. return 'KeyC';
  1426. case 'd':
  1427. case 'D':
  1428. return 'KeyD';
  1429. case 'e':
  1430. case 'E':
  1431. return 'KeyE';
  1432. case 'f':
  1433. case 'F':
  1434. return 'KeyF';
  1435. case 'g':
  1436. case 'G':
  1437. return 'KeyG';
  1438. case 'h':
  1439. case 'H':
  1440. return 'KeyH';
  1441. case 'i':
  1442. case 'I':
  1443. return 'KeyI';
  1444. case 'j':
  1445. case 'J':
  1446. return 'KeyJ';
  1447. case 'k':
  1448. case 'K':
  1449. return 'KeyK';
  1450. case 'l':
  1451. case 'L':
  1452. return 'KeyL';
  1453. case 'm':
  1454. case 'M':
  1455. return 'KeyM';
  1456. case 'n':
  1457. case 'N':
  1458. return 'KeyN';
  1459. case 'o':
  1460. case 'O':
  1461. return 'KeyO';
  1462. case 'p':
  1463. case 'P':
  1464. return 'KeyP';
  1465. case 'q':
  1466. case 'Q':
  1467. return 'KeyQ';
  1468. case 'r':
  1469. case 'R':
  1470. return 'KeyR';
  1471. case 's':
  1472. case 'S':
  1473. return 'KeyS';
  1474. case 't':
  1475. case 'T':
  1476. return 'KeyT';
  1477. case 'u':
  1478. case 'U':
  1479. return 'KeyU';
  1480. case 'v':
  1481. case 'V':
  1482. return 'KeyV';
  1483. case 'w':
  1484. case 'W':
  1485. return 'KeyW';
  1486. case 'x':
  1487. case 'X':
  1488. return 'KeyX';
  1489. case 'y':
  1490. case 'Y':
  1491. return 'KeyY';
  1492. case 'z':
  1493. case 'Z':
  1494. return 'KeyZ';
  1495. case '-':
  1496. case '_':
  1497. return 'Minus';
  1498. case '.':
  1499. return 'Period';
  1500. case "'":
  1501. case '"':
  1502. return 'Quote';
  1503. case ';':
  1504. case ':':
  1505. return 'Semicolon';
  1506. case '/':
  1507. case '?':
  1508. return 'Slash';
  1509. case '\uE00A':
  1510. return 'AltLeft';
  1511. case '\uE052':
  1512. return 'AltRight';
  1513. case '\uE009':
  1514. return 'ControlLeft';
  1515. case '\uE051':
  1516. return 'ControlRight';
  1517. case '\uE006':
  1518. return 'Enter';
  1519. case '\uE03D':
  1520. return 'MetaLeft';
  1521. case '\uE053':
  1522. return 'MetaRight';
  1523. case '\uE008':
  1524. return 'ShiftLeft';
  1525. case '\uE050':
  1526. return 'ShiftRight';
  1527. case ' ':
  1528. case '\uE00D':
  1529. return 'Space';
  1530. case '\uE004':
  1531. return 'Tab';
  1532. case '\uE017':
  1533. return 'Delete';
  1534. case '\uE010':
  1535. return 'End';
  1536. case '\uE002':
  1537. return 'Help';
  1538. case '\uE011':
  1539. return 'Home';
  1540. case '\uE016':
  1541. return 'Insert';
  1542. case '\uE00F':
  1543. return 'PageDown';
  1544. case '\uE00E':
  1545. return 'PageUp';
  1546. case '\uE015':
  1547. return 'ArrowDown';
  1548. case '\uE012':
  1549. return 'ArrowLeft';
  1550. case '\uE014':
  1551. return 'ArrowRight';
  1552. case '\uE013':
  1553. return 'ArrowUp';
  1554. case '\uE00C':
  1555. return 'Escape';
  1556. case '\uE031':
  1557. return 'F1';
  1558. case '\uE032':
  1559. return 'F2';
  1560. case '\uE033':
  1561. return 'F3';
  1562. case '\uE034':
  1563. return 'F4';
  1564. case '\uE035':
  1565. return 'F5';
  1566. case '\uE036':
  1567. return 'F6';
  1568. case '\uE037':
  1569. return 'F7';
  1570. case '\uE038':
  1571. return 'F8';
  1572. case '\uE039':
  1573. return 'F9';
  1574. case '\uE03A':
  1575. return 'F10';
  1576. case '\uE03B':
  1577. return 'F11';
  1578. case '\uE03C':
  1579. return 'F12';
  1580. case '\uE01A':
  1581. case '\uE05C':
  1582. return 'Numpad0';
  1583. case '\uE01B':
  1584. case '\uE056':
  1585. return 'Numpad1';
  1586. case '\uE01C':
  1587. case '\uE05B':
  1588. return 'Numpad2';
  1589. case '\uE01D':
  1590. case '\uE055':
  1591. return 'Numpad3';
  1592. case '\uE01E':
  1593. case '\uE058':
  1594. return 'Numpad4';
  1595. case '\uE01F':
  1596. return 'Numpad5';
  1597. case '\uE020':
  1598. case '\uE05A':
  1599. return 'Numpad6';
  1600. case '\uE021':
  1601. case '\uE057':
  1602. return 'Numpad7';
  1603. case '\uE022':
  1604. case '\uE059':
  1605. return 'Numpad8';
  1606. case '\uE023':
  1607. case '\uE054':
  1608. return 'Numpad9';
  1609. case '\uE025':
  1610. return 'NumpadAdd';
  1611. case '\uE026':
  1612. return 'NumpadComma';
  1613. case '\uE028':
  1614. case '\uE05D':
  1615. return 'NumpadDecimal';
  1616. case '\uE029':
  1617. return 'NumpadDivide';
  1618. case '\uE007':
  1619. return 'NumpadEnter';
  1620. case '\uE024':
  1621. return 'NumpadMultiply';
  1622. case '\uE027':
  1623. return 'NumpadSubtract';
  1624. default:
  1625. return;
  1626. }
  1627. }
  1628. keyUtils.getKeyCode = getKeyCode;
  1629. function getKeyLocation(key) {
  1630. switch (key) {
  1631. case '\uE007':
  1632. case '\uE008':
  1633. case '\uE009':
  1634. case '\uE00A':
  1635. case '\uE03D':
  1636. return 1;
  1637. case '\uE01A':
  1638. case '\uE01B':
  1639. case '\uE01C':
  1640. case '\uE01D':
  1641. case '\uE01E':
  1642. case '\uE01F':
  1643. case '\uE020':
  1644. case '\uE021':
  1645. case '\uE022':
  1646. case '\uE023':
  1647. case '\uE024':
  1648. case '\uE025':
  1649. case '\uE026':
  1650. case '\uE027':
  1651. case '\uE028':
  1652. case '\uE029':
  1653. case '\uE054':
  1654. case '\uE055':
  1655. case '\uE056':
  1656. case '\uE057':
  1657. case '\uE058':
  1658. case '\uE059':
  1659. case '\uE05A':
  1660. case '\uE05B':
  1661. case '\uE05C':
  1662. case '\uE05D':
  1663. return 3;
  1664. case '\uE050':
  1665. case '\uE051':
  1666. case '\uE052':
  1667. case '\uE053':
  1668. return 2;
  1669. default:
  1670. return 0;
  1671. }
  1672. }
  1673. keyUtils.getKeyLocation = getKeyLocation;
  1674. var USKeyboardLayout = {};
  1675. /**
  1676. * Copyright 2023 Google LLC.
  1677. * Copyright (c) Microsoft Corporation.
  1678. *
  1679. * Licensed under the Apache License, Version 2.0 (the "License");
  1680. * you may not use this file except in compliance with the License.
  1681. * You may obtain a copy of the License at
  1682. *
  1683. * http://www.apache.org/licenses/LICENSE-2.0
  1684. *
  1685. * Unless required by applicable law or agreed to in writing, software
  1686. * distributed under the License is distributed on an "AS IS" BASIS,
  1687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1688. * See the License for the specific language governing permissions and
  1689. * limitations under the License.
  1690. */
  1691. Object.defineProperty(USKeyboardLayout, "__esModule", { value: true });
  1692. USKeyboardLayout.KeyToKeyCode = void 0;
  1693. // TODO: Remove this once https://crrev.com/c/4548290 is stably in Chromium.
  1694. // `Input.dispatchKeyboardEvent` will automatically handle these conversions.
  1695. USKeyboardLayout.KeyToKeyCode = {
  1696. '0': 48,
  1697. '1': 49,
  1698. '2': 50,
  1699. '3': 51,
  1700. '4': 52,
  1701. '5': 53,
  1702. '6': 54,
  1703. '7': 55,
  1704. '8': 56,
  1705. '9': 57,
  1706. Abort: 3,
  1707. Help: 6,
  1708. Backspace: 8,
  1709. Tab: 9,
  1710. Numpad5: 12,
  1711. NumpadEnter: 13,
  1712. Enter: 13,
  1713. '\\r': 13,
  1714. '\\n': 13,
  1715. ShiftLeft: 16,
  1716. ShiftRight: 16,
  1717. ControlLeft: 17,
  1718. ControlRight: 17,
  1719. AltLeft: 18,
  1720. AltRight: 18,
  1721. Pause: 19,
  1722. CapsLock: 20,
  1723. Escape: 27,
  1724. Convert: 28,
  1725. NonConvert: 29,
  1726. Space: 32,
  1727. Numpad9: 33,
  1728. PageUp: 33,
  1729. Numpad3: 34,
  1730. PageDown: 34,
  1731. End: 35,
  1732. Numpad1: 35,
  1733. Home: 36,
  1734. Numpad7: 36,
  1735. ArrowLeft: 37,
  1736. Numpad4: 37,
  1737. Numpad8: 38,
  1738. ArrowUp: 38,
  1739. ArrowRight: 39,
  1740. Numpad6: 39,
  1741. Numpad2: 40,
  1742. ArrowDown: 40,
  1743. Select: 41,
  1744. Open: 43,
  1745. PrintScreen: 44,
  1746. Insert: 45,
  1747. Numpad0: 45,
  1748. Delete: 46,
  1749. NumpadDecimal: 46,
  1750. Digit0: 48,
  1751. Digit1: 49,
  1752. Digit2: 50,
  1753. Digit3: 51,
  1754. Digit4: 52,
  1755. Digit5: 53,
  1756. Digit6: 54,
  1757. Digit7: 55,
  1758. Digit8: 56,
  1759. Digit9: 57,
  1760. KeyA: 65,
  1761. KeyB: 66,
  1762. KeyC: 67,
  1763. KeyD: 68,
  1764. KeyE: 69,
  1765. KeyF: 70,
  1766. KeyG: 71,
  1767. KeyH: 72,
  1768. KeyI: 73,
  1769. KeyJ: 74,
  1770. KeyK: 75,
  1771. KeyL: 76,
  1772. KeyM: 77,
  1773. KeyN: 78,
  1774. KeyO: 79,
  1775. KeyP: 80,
  1776. KeyQ: 81,
  1777. KeyR: 82,
  1778. KeyS: 83,
  1779. KeyT: 84,
  1780. KeyU: 85,
  1781. KeyV: 86,
  1782. KeyW: 87,
  1783. KeyX: 88,
  1784. KeyY: 89,
  1785. KeyZ: 90,
  1786. MetaLeft: 91,
  1787. MetaRight: 92,
  1788. ContextMenu: 93,
  1789. NumpadMultiply: 106,
  1790. NumpadAdd: 107,
  1791. NumpadSubtract: 109,
  1792. NumpadDivide: 111,
  1793. F1: 112,
  1794. F2: 113,
  1795. F3: 114,
  1796. F4: 115,
  1797. F5: 116,
  1798. F6: 117,
  1799. F7: 118,
  1800. F8: 119,
  1801. F9: 120,
  1802. F10: 121,
  1803. F11: 122,
  1804. F12: 123,
  1805. F13: 124,
  1806. F14: 125,
  1807. F15: 126,
  1808. F16: 127,
  1809. F17: 128,
  1810. F18: 129,
  1811. F19: 130,
  1812. F20: 131,
  1813. F21: 132,
  1814. F22: 133,
  1815. F23: 134,
  1816. F24: 135,
  1817. NumLock: 144,
  1818. ScrollLock: 145,
  1819. AudioVolumeMute: 173,
  1820. AudioVolumeDown: 174,
  1821. AudioVolumeUp: 175,
  1822. MediaTrackNext: 176,
  1823. MediaTrackPrevious: 177,
  1824. MediaStop: 178,
  1825. MediaPlayPause: 179,
  1826. Semicolon: 186,
  1827. Equal: 187,
  1828. NumpadEqual: 187,
  1829. Comma: 188,
  1830. Minus: 189,
  1831. Period: 190,
  1832. Slash: 191,
  1833. Backquote: 192,
  1834. BracketLeft: 219,
  1835. Backslash: 220,
  1836. BracketRight: 221,
  1837. Quote: 222,
  1838. AltGraph: 225,
  1839. Props: 247,
  1840. Cancel: 3,
  1841. Clear: 12,
  1842. Shift: 16,
  1843. Control: 17,
  1844. Alt: 18,
  1845. Accept: 30,
  1846. ModeChange: 31,
  1847. ' ': 32,
  1848. Print: 42,
  1849. Execute: 43,
  1850. '\\u0000': 46,
  1851. a: 65,
  1852. b: 66,
  1853. c: 67,
  1854. d: 68,
  1855. e: 69,
  1856. f: 70,
  1857. g: 71,
  1858. h: 72,
  1859. i: 73,
  1860. j: 74,
  1861. k: 75,
  1862. l: 76,
  1863. m: 77,
  1864. n: 78,
  1865. o: 79,
  1866. p: 80,
  1867. q: 81,
  1868. r: 82,
  1869. s: 83,
  1870. t: 84,
  1871. u: 85,
  1872. v: 86,
  1873. w: 87,
  1874. x: 88,
  1875. y: 89,
  1876. z: 90,
  1877. Meta: 91,
  1878. '*': 106,
  1879. '+': 107,
  1880. '-': 109,
  1881. '/': 111,
  1882. ';': 186,
  1883. '=': 187,
  1884. ',': 188,
  1885. '.': 190,
  1886. '`': 192,
  1887. '[': 219,
  1888. '\\\\': 220,
  1889. ']': 221,
  1890. "'": 222,
  1891. Attn: 246,
  1892. CrSel: 247,
  1893. ExSel: 248,
  1894. EraseEof: 249,
  1895. Play: 250,
  1896. ZoomOut: 251,
  1897. ')': 48,
  1898. '!': 49,
  1899. '@': 50,
  1900. '#': 51,
  1901. $: 52,
  1902. '%': 53,
  1903. '^': 54,
  1904. '&': 55,
  1905. '(': 57,
  1906. A: 65,
  1907. B: 66,
  1908. C: 67,
  1909. D: 68,
  1910. E: 69,
  1911. F: 70,
  1912. G: 71,
  1913. H: 72,
  1914. I: 73,
  1915. J: 74,
  1916. K: 75,
  1917. L: 76,
  1918. M: 77,
  1919. N: 78,
  1920. O: 79,
  1921. P: 80,
  1922. Q: 81,
  1923. R: 82,
  1924. S: 83,
  1925. T: 84,
  1926. U: 85,
  1927. V: 86,
  1928. W: 87,
  1929. X: 88,
  1930. Y: 89,
  1931. Z: 90,
  1932. ':': 186,
  1933. '<': 188,
  1934. _: 189,
  1935. '>': 190,
  1936. '?': 191,
  1937. '~': 192,
  1938. '{': 219,
  1939. '|': 220,
  1940. '}': 221,
  1941. '"': 222,
  1942. Camera: 44,
  1943. EndCall: 95,
  1944. VolumeDown: 182,
  1945. VolumeUp: 183,
  1946. };
  1947. /**
  1948. * Copyright 2023 Google LLC.
  1949. * Copyright (c) Microsoft Corporation.
  1950. *
  1951. * Licensed under the Apache License, Version 2.0 (the "License");
  1952. * you may not use this file except in compliance with the License.
  1953. * You may obtain a copy of the License at
  1954. *
  1955. * http://www.apache.org/licenses/LICENSE-2.0
  1956. *
  1957. * Unless required by applicable law or agreed to in writing, software
  1958. * distributed under the License is distributed on an "AS IS" BASIS,
  1959. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1960. * See the License for the specific language governing permissions and
  1961. * limitations under the License.
  1962. */
  1963. Object.defineProperty(ActionDispatcher$1, "__esModule", { value: true });
  1964. ActionDispatcher$1.ActionDispatcher = void 0;
  1965. const protocol_js_1$k = protocol;
  1966. const assert_js_1$6 = assert$1;
  1967. const InputSource_js_1$1 = InputSource;
  1968. const keyUtils_js_1 = keyUtils;
  1969. const USKeyboardLayout_js_1 = USKeyboardLayout;
  1970. /** https://w3c.github.io/webdriver/#dfn-center-point */
  1971. const CALCULATE_IN_VIEW_CENTER_PT_DECL = ((i) => {
  1972. const t = i.getClientRects()[0], e = Math.max(0, Math.min(t.x, t.x + t.width)), n = Math.min(window.innerWidth, Math.max(t.x, t.x + t.width)), h = Math.max(0, Math.min(t.y, t.y + t.height)), m = Math.min(window.innerHeight, Math.max(t.y, t.y + t.height));
  1973. return [e + ((n - e) >> 1), h + ((m - h) >> 1)];
  1974. }).toString();
  1975. const IS_MAC_DECL = (() => {
  1976. return navigator.platform.toLowerCase().includes('mac');
  1977. }).toString();
  1978. async function getElementCenter(context, element) {
  1979. const sandbox = await context.getOrCreateSandbox(undefined);
  1980. const result = await sandbox.callFunction(CALCULATE_IN_VIEW_CENTER_PT_DECL, false, { type: 'undefined' }, [element]);
  1981. if (result.type === 'exception') {
  1982. throw new protocol_js_1$k.NoSuchElementException(`Origin element ${element.sharedId} was not found`);
  1983. }
  1984. (0, assert_js_1$6.assert)(result.result.type === 'array');
  1985. (0, assert_js_1$6.assert)(result.result.value?.[0]?.type === 'number');
  1986. (0, assert_js_1$6.assert)(result.result.value?.[1]?.type === 'number');
  1987. const { result: { value: [{ value: x }, { value: y }], }, } = result;
  1988. return { x: x, y: y };
  1989. }
  1990. class ActionDispatcher {
  1991. static isMacOS = async (context) => {
  1992. const result = await (await context.getOrCreateSandbox(undefined)).callFunction(IS_MAC_DECL, false);
  1993. (0, assert_js_1$6.assert)(result.type !== 'exception');
  1994. (0, assert_js_1$6.assert)(result.result.type === 'boolean');
  1995. return result.result.value;
  1996. };
  1997. #tickStart = 0;
  1998. #tickDuration = 0;
  1999. #inputState;
  2000. #context;
  2001. #isMacOS;
  2002. constructor(inputState, context, isMacOS) {
  2003. this.#inputState = inputState;
  2004. this.#context = context;
  2005. this.#isMacOS = isMacOS;
  2006. }
  2007. async dispatchActions(optionsByTick) {
  2008. await this.#inputState.queue.run(async () => {
  2009. for (const options of optionsByTick) {
  2010. await this.dispatchTickActions(options);
  2011. }
  2012. });
  2013. }
  2014. async dispatchTickActions(options) {
  2015. this.#tickStart = performance.now();
  2016. this.#tickDuration = 0;
  2017. for (const { action } of options) {
  2018. if ('duration' in action && action.duration !== undefined) {
  2019. this.#tickDuration = Math.max(this.#tickDuration, action.duration);
  2020. }
  2021. }
  2022. const promises = [
  2023. new Promise((resolve) => setTimeout(resolve, this.#tickDuration)),
  2024. ];
  2025. for (const option of options) {
  2026. // In theory we have to wait for each action to happen, but CDP is serial,
  2027. // so as an optimization, we queue all CDP commands at once and await all
  2028. // of them.
  2029. promises.push(this.#dispatchAction(option));
  2030. }
  2031. await Promise.all(promises);
  2032. }
  2033. async #dispatchAction({ id, action }) {
  2034. const source = this.#inputState.get(id);
  2035. const keyState = this.#inputState.getGlobalKeyState();
  2036. switch (action.type) {
  2037. case 'keyDown': {
  2038. // SAFETY: The source is validated before.
  2039. await this.#dispatchKeyDownAction(source, action);
  2040. this.#inputState.cancelList.push({
  2041. id,
  2042. action: {
  2043. ...action,
  2044. type: 'keyUp',
  2045. },
  2046. });
  2047. break;
  2048. }
  2049. case 'keyUp': {
  2050. // SAFETY: The source is validated before.
  2051. await this.#dispatchKeyUpAction(source, action);
  2052. break;
  2053. }
  2054. case 'pause': {
  2055. // TODO: Implement waiting on the input source.
  2056. break;
  2057. }
  2058. case 'pointerDown': {
  2059. // SAFETY: The source is validated before.
  2060. await this.#dispatchPointerDownAction(source, keyState, action);
  2061. this.#inputState.cancelList.push({
  2062. id,
  2063. action: {
  2064. ...action,
  2065. type: 'pointerUp',
  2066. },
  2067. });
  2068. break;
  2069. }
  2070. case 'pointerMove': {
  2071. // SAFETY: The source is validated before.
  2072. await this.#dispatchPointerMoveAction(source, keyState, action);
  2073. break;
  2074. }
  2075. case 'pointerUp': {
  2076. // SAFETY: The source is validated before.
  2077. await this.#dispatchPointerUpAction(source, keyState, action);
  2078. break;
  2079. }
  2080. case 'scroll': {
  2081. // SAFETY: The source is validated before.
  2082. await this.#dispatchScrollAction(source, keyState, action);
  2083. break;
  2084. }
  2085. }
  2086. }
  2087. #dispatchPointerDownAction(source, keyState, action) {
  2088. const { button } = action;
  2089. if (source.pressed.has(button)) {
  2090. return;
  2091. }
  2092. source.pressed.add(button);
  2093. const { x, y, subtype: pointerType } = source;
  2094. const { width, height, pressure, twist, tangentialPressure } = action;
  2095. const { tiltX, tiltY } = getTilt(action);
  2096. // --- Platform-specific code begins here ---
  2097. const { modifiers } = keyState;
  2098. switch (pointerType) {
  2099. case "mouse" /* Input.PointerType.Mouse */:
  2100. case "pen" /* Input.PointerType.Pen */:
  2101. // TODO: Implement width and height when available.
  2102. return this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchMouseEvent', {
  2103. type: 'mousePressed',
  2104. x,
  2105. y,
  2106. modifiers,
  2107. button: getCdpButton(button),
  2108. buttons: source.buttons,
  2109. clickCount: source.setClickCount(button, new InputSource_js_1$1.PointerSource.ClickContext(x, y, performance.now())),
  2110. pointerType,
  2111. tangentialPressure,
  2112. tiltX,
  2113. tiltY,
  2114. twist,
  2115. force: pressure,
  2116. });
  2117. case "touch" /* Input.PointerType.Touch */:
  2118. return this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchTouchEvent', {
  2119. type: 'touchStart',
  2120. touchPoints: [
  2121. {
  2122. x,
  2123. y,
  2124. ...getRadii(width ?? 1, height ?? 1),
  2125. tangentialPressure,
  2126. tiltX,
  2127. tiltY,
  2128. twist,
  2129. force: pressure,
  2130. id: source.pointerId,
  2131. },
  2132. ],
  2133. modifiers,
  2134. });
  2135. }
  2136. // --- Platform-specific code ends here ---
  2137. }
  2138. #dispatchPointerUpAction(source, keyState, action) {
  2139. const { button } = action;
  2140. if (!source.pressed.has(button)) {
  2141. return;
  2142. }
  2143. source.pressed.delete(button);
  2144. const { x, y, subtype: pointerType } = source;
  2145. // --- Platform-specific code begins here ---
  2146. const { modifiers } = keyState;
  2147. switch (pointerType) {
  2148. case "mouse" /* Input.PointerType.Mouse */:
  2149. case "pen" /* Input.PointerType.Pen */:
  2150. // TODO: Implement width and height when available.
  2151. return this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchMouseEvent', {
  2152. type: 'mouseReleased',
  2153. x,
  2154. y,
  2155. modifiers,
  2156. button: getCdpButton(button),
  2157. buttons: source.buttons,
  2158. clickCount: source.getClickCount(button),
  2159. pointerType,
  2160. });
  2161. case "touch" /* Input.PointerType.Touch */:
  2162. return this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchTouchEvent', {
  2163. type: 'touchEnd',
  2164. touchPoints: [
  2165. {
  2166. x,
  2167. y,
  2168. id: source.pointerId,
  2169. },
  2170. ],
  2171. modifiers,
  2172. });
  2173. }
  2174. // --- Platform-specific code ends here ---
  2175. }
  2176. async #dispatchPointerMoveAction(source, keyState, action) {
  2177. const { x: startX, y: startY, subtype: pointerType } = source;
  2178. const { width, height, pressure, twist, tangentialPressure, x: offsetX, y: offsetY, origin = 'viewport', duration = this.#tickDuration, } = action;
  2179. const { tiltX, tiltY } = getTilt(action);
  2180. const { targetX, targetY } = await this.#getCoordinateFromOrigin(origin, offsetX, offsetY, startX, startY);
  2181. if (targetX < 0 || targetY < 0) {
  2182. throw new protocol_js_1$k.MoveTargetOutOfBoundsException(`Cannot move beyond viewport (x: ${targetX}, y: ${targetY})`);
  2183. }
  2184. let last;
  2185. do {
  2186. const ratio = duration > 0 ? (performance.now() - this.#tickStart) / duration : 1;
  2187. last = ratio >= 1;
  2188. let x;
  2189. let y;
  2190. if (last) {
  2191. x = targetX;
  2192. y = targetY;
  2193. }
  2194. else {
  2195. x = Math.round(ratio * (targetX - startX) + startX);
  2196. y = Math.round(ratio * (targetY - startY) + startY);
  2197. }
  2198. if (source.x !== x || source.y !== y) {
  2199. // --- Platform-specific code begins here ---
  2200. const { modifiers } = keyState;
  2201. switch (pointerType) {
  2202. case "mouse" /* Input.PointerType.Mouse */:
  2203. // TODO: Implement width and height when available.
  2204. await this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchMouseEvent', {
  2205. type: 'mouseMoved',
  2206. x,
  2207. y,
  2208. modifiers,
  2209. clickCount: 0,
  2210. button: getCdpButton(source.pressed.values().next().value ?? 5),
  2211. buttons: source.buttons,
  2212. pointerType,
  2213. tangentialPressure,
  2214. tiltX,
  2215. tiltY,
  2216. twist,
  2217. force: pressure,
  2218. });
  2219. break;
  2220. case "pen" /* Input.PointerType.Pen */:
  2221. if (source.pressed.size !== 0) {
  2222. // TODO: Implement width and height when available.
  2223. await this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchMouseEvent', {
  2224. type: 'mouseMoved',
  2225. x,
  2226. y,
  2227. modifiers,
  2228. clickCount: 0,
  2229. button: getCdpButton(source.pressed.values().next().value ?? 5),
  2230. buttons: source.buttons,
  2231. pointerType,
  2232. tangentialPressure,
  2233. tiltX,
  2234. tiltY,
  2235. twist,
  2236. force: pressure,
  2237. });
  2238. }
  2239. break;
  2240. case "touch" /* Input.PointerType.Touch */:
  2241. if (source.pressed.size !== 0) {
  2242. await this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchTouchEvent', {
  2243. type: 'touchMove',
  2244. touchPoints: [
  2245. {
  2246. x,
  2247. y,
  2248. ...getRadii(width ?? 1, height ?? 1),
  2249. tangentialPressure,
  2250. tiltX,
  2251. tiltY,
  2252. twist,
  2253. force: pressure,
  2254. id: source.pointerId,
  2255. },
  2256. ],
  2257. modifiers,
  2258. });
  2259. }
  2260. break;
  2261. }
  2262. // --- Platform-specific code ends here ---
  2263. source.x = x;
  2264. source.y = y;
  2265. }
  2266. } while (!last);
  2267. }
  2268. async #getCoordinateFromOrigin(origin, offsetX, offsetY, startX, startY) {
  2269. let targetX;
  2270. let targetY;
  2271. switch (origin) {
  2272. case 'viewport':
  2273. targetX = offsetX;
  2274. targetY = offsetY;
  2275. break;
  2276. case 'pointer':
  2277. targetX = startX + offsetX;
  2278. targetY = startY + offsetY;
  2279. break;
  2280. default: {
  2281. const { x: posX, y: posY } = await getElementCenter(this.#context, origin.element);
  2282. // SAFETY: These can never be special numbers.
  2283. targetX = posX + offsetX;
  2284. targetY = posY + offsetY;
  2285. break;
  2286. }
  2287. }
  2288. return { targetX, targetY };
  2289. }
  2290. async #dispatchScrollAction(_source, keyState, action) {
  2291. const { deltaX: targetDeltaX, deltaY: targetDeltaY, x: offsetX, y: offsetY, origin = 'viewport', duration = this.#tickDuration, } = action;
  2292. if (origin === 'pointer') {
  2293. throw new protocol_js_1$k.InvalidArgumentException('"pointer" origin is invalid for scrolling.');
  2294. }
  2295. const { targetX, targetY } = await this.#getCoordinateFromOrigin(origin, offsetX, offsetY, 0, 0);
  2296. if (targetX < 0 || targetY < 0) {
  2297. throw new protocol_js_1$k.MoveTargetOutOfBoundsException(`Cannot move beyond viewport (x: ${targetX}, y: ${targetY})`);
  2298. }
  2299. let currentDeltaX = 0;
  2300. let currentDeltaY = 0;
  2301. let last;
  2302. do {
  2303. const ratio = duration > 0 ? (performance.now() - this.#tickStart) / duration : 1;
  2304. last = ratio >= 1;
  2305. let deltaX;
  2306. let deltaY;
  2307. if (last) {
  2308. deltaX = targetDeltaX - currentDeltaX;
  2309. deltaY = targetDeltaY - currentDeltaY;
  2310. }
  2311. else {
  2312. deltaX = Math.round(ratio * targetDeltaX - currentDeltaX);
  2313. deltaY = Math.round(ratio * targetDeltaY - currentDeltaY);
  2314. }
  2315. if (deltaX !== 0 || deltaY !== 0) {
  2316. // --- Platform-specific code begins here ---
  2317. const { modifiers } = keyState;
  2318. await this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchMouseEvent', {
  2319. type: 'mouseWheel',
  2320. deltaX,
  2321. deltaY,
  2322. x: targetX,
  2323. y: targetY,
  2324. modifiers,
  2325. });
  2326. // --- Platform-specific code ends here ---
  2327. currentDeltaX += deltaX;
  2328. currentDeltaY += deltaY;
  2329. }
  2330. } while (!last);
  2331. }
  2332. async #dispatchKeyDownAction(source, action) {
  2333. if ([...action.value].length > 1) {
  2334. throw new protocol_js_1$k.InvalidArgumentException(`Invalid key value: ${action.value}`);
  2335. }
  2336. const rawKey = action.value;
  2337. const key = (0, keyUtils_js_1.getNormalizedKey)(rawKey);
  2338. const repeat = source.pressed.has(key);
  2339. const code = (0, keyUtils_js_1.getKeyCode)(rawKey);
  2340. const location = (0, keyUtils_js_1.getKeyLocation)(rawKey);
  2341. switch (key) {
  2342. case 'Alt':
  2343. source.alt = true;
  2344. break;
  2345. case 'Shift':
  2346. source.shift = true;
  2347. break;
  2348. case 'Control':
  2349. source.ctrl = true;
  2350. break;
  2351. case 'Meta':
  2352. source.meta = true;
  2353. break;
  2354. }
  2355. source.pressed.add(key);
  2356. const { modifiers } = source;
  2357. // --- Platform-specific code begins here ---
  2358. // The spread is a little hack so JS gives us an array of unicode characters
  2359. // to measure.
  2360. const unmodifiedText = getKeyEventUnmodifiedText(key, source);
  2361. const text = getKeyEventText(code ?? '', source) ?? unmodifiedText;
  2362. let command;
  2363. // The following commands need to be declared because Chromium doesn't
  2364. // handle them. See
  2365. // https://source.chromium.org/chromium/chromium/src/+/refs/heads/main:third_party/blink/renderer/core/editing/editing_behavior.cc;l=169;drc=b8143cf1dfd24842890fcd831c4f5d909bef4fc4;bpv=0;bpt=1.
  2366. if (this.#isMacOS && source.meta) {
  2367. switch (code) {
  2368. case 'KeyA':
  2369. command = 'SelectAll';
  2370. break;
  2371. case 'KeyC':
  2372. command = 'Copy';
  2373. break;
  2374. case 'KeyV':
  2375. command = source.shift ? 'PasteAndMatchStyle' : 'Paste';
  2376. break;
  2377. case 'KeyX':
  2378. command = 'Cut';
  2379. break;
  2380. case 'KeyZ':
  2381. command = source.shift ? 'Redo' : 'Undo';
  2382. break;
  2383. // Intentionally empty.
  2384. }
  2385. }
  2386. const promises = [
  2387. this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchKeyEvent', {
  2388. type: text ? 'keyDown' : 'rawKeyDown',
  2389. windowsVirtualKeyCode: USKeyboardLayout_js_1.KeyToKeyCode[key],
  2390. key,
  2391. code,
  2392. text,
  2393. unmodifiedText,
  2394. autoRepeat: repeat,
  2395. isSystemKey: source.alt || undefined,
  2396. location: location < 3 ? location : undefined,
  2397. isKeypad: location === 3,
  2398. modifiers,
  2399. commands: command ? [command] : undefined,
  2400. }),
  2401. ];
  2402. // Drag cancelling happens on escape.
  2403. if (key === 'Escape') {
  2404. if (!source.alt &&
  2405. ((this.#isMacOS && !source.ctrl && !source.meta) || !this.#isMacOS)) {
  2406. promises.push(this.#context.cdpTarget.cdpClient.sendCommand('Input.cancelDragging'));
  2407. }
  2408. }
  2409. await Promise.all(promises);
  2410. // --- Platform-specific code ends here ---
  2411. }
  2412. #dispatchKeyUpAction(source, action) {
  2413. if ([...action.value].length > 1) {
  2414. throw new protocol_js_1$k.InvalidArgumentException(`Invalid key value: ${action.value}`);
  2415. }
  2416. const rawKey = action.value;
  2417. const key = (0, keyUtils_js_1.getNormalizedKey)(rawKey);
  2418. if (!source.pressed.has(key)) {
  2419. return;
  2420. }
  2421. const code = (0, keyUtils_js_1.getKeyCode)(rawKey);
  2422. const location = (0, keyUtils_js_1.getKeyLocation)(rawKey);
  2423. switch (key) {
  2424. case 'Alt':
  2425. source.alt = false;
  2426. break;
  2427. case 'Shift':
  2428. source.shift = false;
  2429. break;
  2430. case 'Control':
  2431. source.ctrl = false;
  2432. break;
  2433. case 'Meta':
  2434. source.meta = false;
  2435. break;
  2436. }
  2437. source.pressed.delete(key);
  2438. const { modifiers } = source;
  2439. // --- Platform-specific code begins here ---
  2440. // The spread is a little hack so JS gives us an array of unicode characters
  2441. // to measure.
  2442. const unmodifiedText = getKeyEventUnmodifiedText(key, source);
  2443. const text = getKeyEventText(code ?? '', source) ?? unmodifiedText;
  2444. return this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchKeyEvent', {
  2445. type: 'keyUp',
  2446. windowsVirtualKeyCode: USKeyboardLayout_js_1.KeyToKeyCode[key],
  2447. key,
  2448. code,
  2449. text,
  2450. unmodifiedText,
  2451. location: location < 3 ? location : undefined,
  2452. isSystemKey: source.alt || undefined,
  2453. isKeypad: location === 3,
  2454. modifiers,
  2455. });
  2456. // --- Platform-specific code ends here ---
  2457. }
  2458. }
  2459. ActionDispatcher$1.ActionDispatcher = ActionDispatcher;
  2460. const getKeyEventUnmodifiedText = (key, source) => {
  2461. if (key === 'Enter') {
  2462. return '\r';
  2463. }
  2464. return [...key].length === 1
  2465. ? source.shift
  2466. ? key.toLocaleUpperCase('en-US')
  2467. : key
  2468. : undefined;
  2469. };
  2470. const getKeyEventText = (code, source) => {
  2471. if (source.ctrl) {
  2472. switch (code) {
  2473. case 'Digit2':
  2474. if (source.shift) {
  2475. return '\x00';
  2476. }
  2477. break;
  2478. case 'KeyA':
  2479. return '\x01';
  2480. case 'KeyB':
  2481. return '\x02';
  2482. case 'KeyC':
  2483. return '\x03';
  2484. case 'KeyD':
  2485. return '\x04';
  2486. case 'KeyE':
  2487. return '\x05';
  2488. case 'KeyF':
  2489. return '\x06';
  2490. case 'KeyG':
  2491. return '\x07';
  2492. case 'KeyH':
  2493. return '\x08';
  2494. case 'KeyI':
  2495. return '\x09';
  2496. case 'KeyJ':
  2497. return '\x0A';
  2498. case 'KeyK':
  2499. return '\x0B';
  2500. case 'KeyL':
  2501. return '\x0C';
  2502. case 'KeyM':
  2503. return '\x0D';
  2504. case 'KeyN':
  2505. return '\x0E';
  2506. case 'KeyO':
  2507. return '\x0F';
  2508. case 'KeyP':
  2509. return '\x10';
  2510. case 'KeyQ':
  2511. return '\x11';
  2512. case 'KeyR':
  2513. return '\x12';
  2514. case 'KeyS':
  2515. return '\x13';
  2516. case 'KeyT':
  2517. return '\x14';
  2518. case 'KeyU':
  2519. return '\x15';
  2520. case 'KeyV':
  2521. return '\x16';
  2522. case 'KeyW':
  2523. return '\x17';
  2524. case 'KeyX':
  2525. return '\x18';
  2526. case 'KeyY':
  2527. return '\x19';
  2528. case 'KeyZ':
  2529. return '\x1A';
  2530. case 'BracketLeft':
  2531. return '\x1B';
  2532. case 'Backslash':
  2533. return '\x1C';
  2534. case 'BracketRight':
  2535. return '\x1D';
  2536. case 'Digit6':
  2537. if (source.shift) {
  2538. return '\x1E';
  2539. }
  2540. break;
  2541. case 'Minus':
  2542. return '\x1F';
  2543. }
  2544. return '';
  2545. }
  2546. if (source.alt) {
  2547. return '';
  2548. }
  2549. return;
  2550. };
  2551. function getCdpButton(button) {
  2552. switch (button) {
  2553. case 0:
  2554. return 'left';
  2555. case 1:
  2556. return 'middle';
  2557. case 2:
  2558. return 'right';
  2559. case 3:
  2560. return 'back';
  2561. case 4:
  2562. return 'forward';
  2563. default:
  2564. return 'none';
  2565. }
  2566. }
  2567. function getTilt(action) {
  2568. // https://w3c.github.io/pointerevents/#converting-between-tiltx-tilty-and-altitudeangle-azimuthangle
  2569. const altitudeAngle = action.altitudeAngle ?? 0;
  2570. const azimuthAngle = action.azimuthAngle ?? 0;
  2571. let tiltXRadians = 0;
  2572. let tiltYRadians = 0;
  2573. if (altitudeAngle === 0) {
  2574. // the pen is in the X-Y plane
  2575. if (azimuthAngle === 0 || azimuthAngle === 2 * Math.PI) {
  2576. // pen is on positive X axis
  2577. tiltXRadians = Math.PI / 2;
  2578. }
  2579. if (azimuthAngle === Math.PI / 2) {
  2580. // pen is on positive Y axis
  2581. tiltYRadians = Math.PI / 2;
  2582. }
  2583. if (azimuthAngle === Math.PI) {
  2584. // pen is on negative X axis
  2585. tiltXRadians = -Math.PI / 2;
  2586. }
  2587. if (azimuthAngle === (3 * Math.PI) / 2) {
  2588. // pen is on negative Y axis
  2589. tiltYRadians = -Math.PI / 2;
  2590. }
  2591. if (azimuthAngle > 0 && azimuthAngle < Math.PI / 2) {
  2592. tiltXRadians = Math.PI / 2;
  2593. tiltYRadians = Math.PI / 2;
  2594. }
  2595. if (azimuthAngle > Math.PI / 2 && azimuthAngle < Math.PI) {
  2596. tiltXRadians = -Math.PI / 2;
  2597. tiltYRadians = Math.PI / 2;
  2598. }
  2599. if (azimuthAngle > Math.PI && azimuthAngle < (3 * Math.PI) / 2) {
  2600. tiltXRadians = -Math.PI / 2;
  2601. tiltYRadians = -Math.PI / 2;
  2602. }
  2603. if (azimuthAngle > (3 * Math.PI) / 2 && azimuthAngle < 2 * Math.PI) {
  2604. tiltXRadians = Math.PI / 2;
  2605. tiltYRadians = -Math.PI / 2;
  2606. }
  2607. }
  2608. if (altitudeAngle !== 0) {
  2609. const tanAlt = Math.tan(altitudeAngle);
  2610. tiltXRadians = Math.atan(Math.cos(azimuthAngle) / tanAlt);
  2611. tiltYRadians = Math.atan(Math.sin(azimuthAngle) / tanAlt);
  2612. }
  2613. const factor = 180 / Math.PI;
  2614. return {
  2615. tiltX: Math.round(tiltXRadians * factor),
  2616. tiltY: Math.round(tiltYRadians * factor),
  2617. };
  2618. }
  2619. function getRadii(width, height) {
  2620. return {
  2621. radiusX: width ? width / 2 : 0.5,
  2622. radiusY: height ? height / 2 : 0.5,
  2623. };
  2624. }
  2625. var InputStateManager$1 = {};
  2626. var InputState$1 = {};
  2627. var Mutex$1 = {};
  2628. /**
  2629. * Copyright 2023 Google LLC.
  2630. * Copyright (c) Microsoft Corporation.
  2631. * Copyright 2022 The Chromium Authors.
  2632. *
  2633. * Licensed under the Apache License, Version 2.0 (the "License");
  2634. * you may not use this file except in compliance with the License.
  2635. * You may obtain a copy of the License at
  2636. *
  2637. * http://www.apache.org/licenses/LICENSE-2.0
  2638. *
  2639. * Unless required by applicable law or agreed to in writing, software
  2640. * distributed under the License is distributed on an "AS IS" BASIS,
  2641. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2642. * See the License for the specific language governing permissions and
  2643. * limitations under the License.
  2644. */
  2645. Object.defineProperty(Mutex$1, "__esModule", { value: true });
  2646. Mutex$1.Mutex = void 0;
  2647. /**
  2648. * Use Mutex class to coordinate local concurrent operations.
  2649. * Once `acquire` promise resolves, you hold the lock and must
  2650. * call `release` function returned by `acquire` to release the
  2651. * lock. Failing to `release` the lock may lead to deadlocks.
  2652. */
  2653. class Mutex {
  2654. #locked = false;
  2655. #acquirers = [];
  2656. // This is FIFO.
  2657. acquire() {
  2658. const state = { resolved: false };
  2659. if (this.#locked) {
  2660. return new Promise((resolve) => {
  2661. this.#acquirers.push(() => resolve(this.#release.bind(this, state)));
  2662. });
  2663. }
  2664. this.#locked = true;
  2665. return Promise.resolve(this.#release.bind(this, state));
  2666. }
  2667. #release(state) {
  2668. if (state.resolved) {
  2669. throw new Error('Cannot release more than once.');
  2670. }
  2671. state.resolved = true;
  2672. const resolve = this.#acquirers.shift();
  2673. if (!resolve) {
  2674. this.#locked = false;
  2675. return;
  2676. }
  2677. resolve();
  2678. }
  2679. async run(action) {
  2680. const release = await this.acquire();
  2681. try {
  2682. // Note we need to await here because we want the await to release AFTER
  2683. // that await happens. Returning action() will trigger the release
  2684. // immediately which is counter to what we want.
  2685. const result = await action();
  2686. return result;
  2687. }
  2688. finally {
  2689. release();
  2690. }
  2691. }
  2692. }
  2693. Mutex$1.Mutex = Mutex;
  2694. /**
  2695. * Copyright 2023 Google LLC.
  2696. * Copyright (c) Microsoft Corporation.
  2697. *
  2698. * Licensed under the Apache License, Version 2.0 (the "License");
  2699. * you may not use this file except in compliance with the License.
  2700. * You may obtain a copy of the License at
  2701. *
  2702. * http://www.apache.org/licenses/LICENSE-2.0
  2703. *
  2704. * Unless required by applicable law or agreed to in writing, software
  2705. * distributed under the License is distributed on an "AS IS" BASIS,
  2706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2707. * See the License for the specific language governing permissions and
  2708. * limitations under the License.
  2709. */
  2710. Object.defineProperty(InputState$1, "__esModule", { value: true });
  2711. InputState$1.InputState = void 0;
  2712. const protocol_js_1$j = protocol;
  2713. const Mutex_js_1 = Mutex$1;
  2714. const InputSource_js_1 = InputSource;
  2715. class InputState {
  2716. cancelList = [];
  2717. #sources = new Map();
  2718. #mutex = new Mutex_js_1.Mutex();
  2719. getOrCreate(id, type, subtype) {
  2720. let source = this.#sources.get(id);
  2721. if (!source) {
  2722. switch (type) {
  2723. case "none" /* SourceType.None */:
  2724. source = new InputSource_js_1.NoneSource();
  2725. break;
  2726. case "key" /* SourceType.Key */:
  2727. source = new InputSource_js_1.KeySource();
  2728. break;
  2729. case "pointer" /* SourceType.Pointer */: {
  2730. let pointerId = subtype === "mouse" /* Input.PointerType.Mouse */ ? 0 : 2;
  2731. const pointerIds = new Set();
  2732. for (const [, source] of this.#sources) {
  2733. if (source.type === "pointer" /* SourceType.Pointer */) {
  2734. pointerIds.add(source.pointerId);
  2735. }
  2736. }
  2737. while (pointerIds.has(pointerId)) {
  2738. ++pointerId;
  2739. }
  2740. source = new InputSource_js_1.PointerSource(pointerId, subtype);
  2741. break;
  2742. }
  2743. case "wheel" /* SourceType.Wheel */:
  2744. source = new InputSource_js_1.WheelSource();
  2745. break;
  2746. default:
  2747. throw new protocol_js_1$j.InvalidArgumentException(`Expected "${"none" /* SourceType.None */}", "${"key" /* SourceType.Key */}", "${"pointer" /* SourceType.Pointer */}", or "${"wheel" /* SourceType.Wheel */}". Found unknown source type ${type}.`);
  2748. }
  2749. this.#sources.set(id, source);
  2750. return source;
  2751. }
  2752. if (source.type !== type) {
  2753. throw new protocol_js_1$j.InvalidArgumentException(`Input source type of ${id} is ${source.type}, but received ${type}.`);
  2754. }
  2755. return source;
  2756. }
  2757. get(id) {
  2758. const source = this.#sources.get(id);
  2759. if (!source) {
  2760. throw new protocol_js_1$j.UnknownErrorException(`Internal error.`);
  2761. }
  2762. return source;
  2763. }
  2764. getGlobalKeyState() {
  2765. const state = new InputSource_js_1.KeySource();
  2766. for (const [, source] of this.#sources) {
  2767. if (source.type !== "key" /* SourceType.Key */) {
  2768. continue;
  2769. }
  2770. for (const pressed of source.pressed) {
  2771. state.pressed.add(pressed);
  2772. }
  2773. state.alt ||= source.alt;
  2774. state.ctrl ||= source.ctrl;
  2775. state.meta ||= source.meta;
  2776. state.shift ||= source.shift;
  2777. }
  2778. return state;
  2779. }
  2780. get queue() {
  2781. return this.#mutex;
  2782. }
  2783. }
  2784. InputState$1.InputState = InputState;
  2785. /**
  2786. * Copyright 2023 Google LLC.
  2787. * Copyright (c) Microsoft Corporation.
  2788. *
  2789. * Licensed under the Apache License, Version 2.0 (the "License");
  2790. * you may not use this file except in compliance with the License.
  2791. * You may obtain a copy of the License at
  2792. *
  2793. * http://www.apache.org/licenses/LICENSE-2.0
  2794. *
  2795. * Unless required by applicable law or agreed to in writing, software
  2796. * distributed under the License is distributed on an "AS IS" BASIS,
  2797. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2798. * See the License for the specific language governing permissions and
  2799. * limitations under the License.
  2800. */
  2801. Object.defineProperty(InputStateManager$1, "__esModule", { value: true });
  2802. InputStateManager$1.InputStateManager = void 0;
  2803. const assert_js_1$5 = assert$1;
  2804. const InputState_js_1 = InputState$1;
  2805. // We use a weak map here as specified here:
  2806. // https://www.w3.org/TR/webdriver/#dfn-browsing-context-input-state-map
  2807. class InputStateManager extends WeakMap {
  2808. get(context) {
  2809. (0, assert_js_1$5.assert)(context.isTopLevelContext());
  2810. if (!this.has(context)) {
  2811. this.set(context, new InputState_js_1.InputState());
  2812. }
  2813. return super.get(context);
  2814. }
  2815. }
  2816. InputStateManager$1.InputStateManager = InputStateManager;
  2817. Object.defineProperty(InputProcessor$1, "__esModule", { value: true });
  2818. InputProcessor$1.InputProcessor = void 0;
  2819. /*
  2820. * Copyright 2023 Google LLC.
  2821. * Copyright (c) Microsoft Corporation.
  2822. *
  2823. * Licensed under the Apache License, Version 2.0 (the "License");
  2824. * you may not use this file except in compliance with the License.
  2825. * You may obtain a copy of the License at
  2826. *
  2827. * http://www.apache.org/licenses/LICENSE-2.0
  2828. *
  2829. * Unless required by applicable law or agreed to in writing, software
  2830. * distributed under the License is distributed on an "AS IS" BASIS,
  2831. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2832. * See the License for the specific language governing permissions and
  2833. * limitations under the License.
  2834. */
  2835. const protocol_js_1$i = protocol;
  2836. const assert_js_1$4 = assert$1;
  2837. const ActionDispatcher_js_1 = ActionDispatcher$1;
  2838. const InputStateManager_js_1 = InputStateManager$1;
  2839. class InputProcessor {
  2840. #browsingContextStorage;
  2841. #realmStorage;
  2842. #inputStateManager = new InputStateManager_js_1.InputStateManager();
  2843. constructor(browsingContextStorage, realmStorage) {
  2844. this.#browsingContextStorage = browsingContextStorage;
  2845. this.#realmStorage = realmStorage;
  2846. }
  2847. async performActions(params) {
  2848. const context = this.#browsingContextStorage.getContext(params.context);
  2849. const inputState = this.#inputStateManager.get(context.top);
  2850. const actionsByTick = this.#getActionsByTick(params, inputState);
  2851. const dispatcher = new ActionDispatcher_js_1.ActionDispatcher(inputState, context, await ActionDispatcher_js_1.ActionDispatcher.isMacOS(context).catch(() => false));
  2852. await dispatcher.dispatchActions(actionsByTick);
  2853. return {};
  2854. }
  2855. async releaseActions(params) {
  2856. const context = this.#browsingContextStorage.getContext(params.context);
  2857. const topContext = context.top;
  2858. const inputState = this.#inputStateManager.get(topContext);
  2859. const dispatcher = new ActionDispatcher_js_1.ActionDispatcher(inputState, context, await ActionDispatcher_js_1.ActionDispatcher.isMacOS(context).catch(() => false));
  2860. await dispatcher.dispatchTickActions(inputState.cancelList.reverse());
  2861. this.#inputStateManager.delete(topContext);
  2862. return {};
  2863. }
  2864. async setFiles(params) {
  2865. const context = this.#browsingContextStorage.getContext(params.context);
  2866. const realm = await context.getOrCreateSandbox(undefined);
  2867. let result;
  2868. try {
  2869. result = await realm.callFunction(String(function getFiles(fileListLength) {
  2870. if (!(this instanceof HTMLInputElement)) {
  2871. return 0 /* ErrorCode.Object */;
  2872. }
  2873. if (this.type !== 'file') {
  2874. return 1 /* ErrorCode.Type */;
  2875. }
  2876. if (this.disabled) {
  2877. return 2 /* ErrorCode.Disabled */;
  2878. }
  2879. if (fileListLength > 1 && !this.multiple) {
  2880. return 3 /* ErrorCode.Multiple */;
  2881. }
  2882. return;
  2883. }), false, params.element, [{ type: 'number', value: params.files.length }]);
  2884. }
  2885. catch {
  2886. throw new protocol_js_1$i.NoSuchElementException(`Could not find element ${params.element.sharedId}`);
  2887. }
  2888. (0, assert_js_1$4.assert)(result.type === 'success');
  2889. if (result.result.type === 'number') {
  2890. switch (result.result.value) {
  2891. case 0 /* ErrorCode.Object */: {
  2892. throw new protocol_js_1$i.NoSuchElementException(`Could not find element ${params.element.sharedId}`);
  2893. }
  2894. case 1 /* ErrorCode.Type */: {
  2895. throw new protocol_js_1$i.UnableToSetFileInputException(`Element ${params.element.sharedId} is not a file input`);
  2896. }
  2897. case 2 /* ErrorCode.Disabled */: {
  2898. throw new protocol_js_1$i.UnableToSetFileInputException(`Input element ${params.element.sharedId} is disabled`);
  2899. }
  2900. case 3 /* ErrorCode.Multiple */: {
  2901. throw new protocol_js_1$i.UnableToSetFileInputException(`Cannot set multiple files on a non-multiple input element`);
  2902. }
  2903. }
  2904. }
  2905. /**
  2906. * The zero-length array is a special case, it seems that
  2907. * DOM.setFileInputFiles does not actually update the files in that case, so
  2908. * the solution is to eval the element value to a new FileList directly.
  2909. */
  2910. if (params.files.length === 0) {
  2911. // XXX: These events should converted to trusted events. Perhaps do this
  2912. // in `DOM.setFileInputFiles`?
  2913. await realm.callFunction(String(function dispatchEvent() {
  2914. if (this.files?.length === 0) {
  2915. this.dispatchEvent(new Event('cancel', {
  2916. bubbles: true,
  2917. }));
  2918. return;
  2919. }
  2920. this.files = new DataTransfer().files;
  2921. // Dispatch events for this case because it should behave akin to a user action.
  2922. this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
  2923. this.dispatchEvent(new Event('change', { bubbles: true }));
  2924. }), false, params.element);
  2925. return {};
  2926. }
  2927. // Our goal here is to iterate over the input element files and get their
  2928. // file paths.
  2929. const paths = [];
  2930. for (let i = 0; i < params.files.length; ++i) {
  2931. const result = await realm.callFunction(String(function getFiles(index) {
  2932. return this.files?.item(index);
  2933. }), false, params.element, [{ type: 'number', value: 0 }], "root" /* Script.ResultOwnership.Root */);
  2934. (0, assert_js_1$4.assert)(result.type === 'success');
  2935. if (result.result.type !== 'object') {
  2936. break;
  2937. }
  2938. const { handle } = result.result;
  2939. (0, assert_js_1$4.assert)(handle !== undefined);
  2940. const { path } = await realm.cdpClient.sendCommand('DOM.getFileInfo', {
  2941. objectId: handle,
  2942. });
  2943. paths.push(path);
  2944. // Cleanup the handle.
  2945. void realm.disown(handle).catch(undefined);
  2946. }
  2947. paths.sort();
  2948. // We create a new array so we preserve the order of the original files.
  2949. const sortedFiles = [...params.files].sort();
  2950. if (paths.length !== params.files.length ||
  2951. sortedFiles.some((path, index) => {
  2952. return paths[index] !== path;
  2953. })) {
  2954. const { objectId } = await realm.deserializeForCdp(params.element);
  2955. // This cannot throw since this was just used in `callFunction` above.
  2956. (0, assert_js_1$4.assert)(objectId !== undefined);
  2957. await realm.cdpClient.sendCommand('DOM.setFileInputFiles', {
  2958. files: params.files,
  2959. objectId,
  2960. });
  2961. }
  2962. else {
  2963. // XXX: We should dispatch a trusted event.
  2964. await realm.callFunction(String(function dispatchEvent() {
  2965. this.dispatchEvent(new Event('cancel', {
  2966. bubbles: true,
  2967. }));
  2968. }), false, params.element);
  2969. }
  2970. return {};
  2971. }
  2972. #getActionsByTick(params, inputState) {
  2973. const actionsByTick = [];
  2974. for (const action of params.actions) {
  2975. switch (action.type) {
  2976. case "pointer" /* SourceType.Pointer */: {
  2977. action.parameters ??= { pointerType: "mouse" /* Input.PointerType.Mouse */ };
  2978. action.parameters.pointerType ??= "mouse" /* Input.PointerType.Mouse */;
  2979. const source = inputState.getOrCreate(action.id, "pointer" /* SourceType.Pointer */, action.parameters.pointerType);
  2980. if (source.subtype !== action.parameters.pointerType) {
  2981. throw new protocol_js_1$i.InvalidArgumentException(`Expected input source ${action.id} to be ${source.subtype}; got ${action.parameters.pointerType}.`);
  2982. }
  2983. break;
  2984. }
  2985. default:
  2986. inputState.getOrCreate(action.id, action.type);
  2987. }
  2988. const actions = action.actions.map((item) => ({
  2989. id: action.id,
  2990. action: item,
  2991. }));
  2992. for (let i = 0; i < actions.length; i++) {
  2993. if (actionsByTick.length === i) {
  2994. actionsByTick.push([]);
  2995. }
  2996. actionsByTick[i].push(actions[i]);
  2997. }
  2998. }
  2999. return actionsByTick;
  3000. }
  3001. }
  3002. InputProcessor$1.InputProcessor = InputProcessor;
  3003. var NetworkProcessor$1 = {};
  3004. var NetworkUtils = {};
  3005. var Base64 = {};
  3006. /**
  3007. * Copyright 2024 Google LLC.
  3008. * Copyright (c) Microsoft Corporation.
  3009. *
  3010. * Licensed under the Apache License, Version 2.0 (the "License");
  3011. * you may not use this file except in compliance with the License.
  3012. * You may obtain a copy of the License at
  3013. *
  3014. * http://www.apache.org/licenses/LICENSE-2.0
  3015. *
  3016. * Unless required by applicable law or agreed to in writing, software
  3017. * distributed under the License is distributed on an "AS IS" BASIS,
  3018. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3019. * See the License for the specific language governing permissions and
  3020. * limitations under the License.
  3021. */
  3022. Object.defineProperty(Base64, "__esModule", { value: true });
  3023. Base64.base64ToString = void 0;
  3024. /**
  3025. * Encodes a string to base64.
  3026. *
  3027. * Uses the native Web API if available, otherwise falls back to a NodeJS Buffer.
  3028. * @param {string} base64Str
  3029. * @return {string}
  3030. */
  3031. function base64ToString(base64Str) {
  3032. // Available only if run in a browser context.
  3033. if ('atob' in globalThis) {
  3034. return globalThis.atob(base64Str);
  3035. }
  3036. // Available only if run in a NodeJS context.
  3037. return Buffer.from(base64Str, 'base64').toString('ascii');
  3038. }
  3039. Base64.base64ToString = base64ToString;
  3040. var UrlPattern = {};
  3041. var M=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Oe=(e,t)=>{for(var r in t)M(e,r,{get:t[r],enumerable:!0});},ke=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Re(t))!Ee.call(e,a)&&a!==r&&M(e,a,{get:()=>t[a],enumerable:!(n=Pe(t,a))||n.enumerable});return e};var Te=e=>ke(M({},"__esModule",{value:!0}),e);var Ne={};Oe(Ne,{URLPattern:()=>Y});var urlpattern=Te(Ne);var R=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,r,n,a,c,l){this.type=t,this.name=r,this.prefix=n,this.value=a,this.suffix=c,this.modifier=l;}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},Ae=/[$_\p{ID_Start}]/u,ye=/[$_\u200C\u200D\p{ID_Continue}]/u,v=".*";function we(e,t){return (t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function D(e,t=!1){let r=[],n=0;for(;n<e.length;){let a=e[n],c=function(l){if(!t)throw new TypeError(l);r.push({type:"INVALID_CHAR",index:n,value:e[n++]});};if(a==="*"){r.push({type:"ASTERISK",index:n,value:e[n++]});continue}if(a==="+"||a==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:e[n++]});continue}if(a==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});continue}if(a==="{"){r.push({type:"OPEN",index:n,value:e[n++]});continue}if(a==="}"){r.push({type:"CLOSE",index:n,value:e[n++]});continue}if(a===":"){let l="",s=n+1;for(;s<e.length;){let i=e.substr(s,1);if(s===n+1&&Ae.test(i)||s!==n+1&&ye.test(i)){l+=e[s++];continue}break}if(!l){c(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:l}),n=s;continue}if(a==="("){let l=1,s="",i=n+1,o=!1;if(e[i]==="?"){c(`Pattern cannot start with "?" at ${i}`);continue}for(;i<e.length;){if(!we(e[i],!1)){c(`Invalid character '${e[i]}' at ${i}.`),o=!0;break}if(e[i]==="\\"){s+=e[i++]+e[i++];continue}if(e[i]===")"){if(l--,l===0){i++;break}}else if(e[i]==="("&&(l++,e[i+1]!=="?")){c(`Capturing groups are not allowed at ${i}`),o=!0;break}s+=e[i++];}if(o)continue;if(l){c(`Unbalanced pattern at ${n}`);continue}if(!s){c(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:s}),n=i;continue}r.push({type:"CHAR",index:n,value:e[n++]});}return r.push({type:"END",index:n,value:""}),r}function F(e,t={}){let r=D(e);t.delimiter??="/#?",t.prefixes??="./";let n=`[^${S(t.delimiter)}]+?`,a=[],c=0,l=0,i=new Set,o=h=>{if(l<r.length&&r[l].type===h)return r[l++].value},f=()=>o("OTHER_MODIFIER")??o("ASTERISK"),d=h=>{let u=o(h);if(u!==void 0)return u;let{type:p,index:A}=r[l];throw new TypeError(`Unexpected ${p} at ${A}, expected ${h}`)},T=()=>{let h="",u;for(;u=o("CHAR")??o("ESCAPED_CHAR");)h+=u;return h},xe=h=>h,L=t.encodePart||xe,I="",U=h=>{I+=h;},$=()=>{I.length&&(a.push(new R(3,"","",L(I),"",3)),I="");},X=(h,u,p,A,Z)=>{let g=3;switch(Z){case"?":g=1;break;case"*":g=0;break;case"+":g=2;break}if(!u&&!p&&g===3){U(h);return}if($(),!u&&!p){if(!h)return;a.push(new R(3,"","",L(h),"",g));return}let m;p?p==="*"?m=v:m=p:m=n;let O=2;m===n?(O=1,m=""):m===v&&(O=0,m="");let P;if(u?P=u:p&&(P=c++),i.has(P))throw new TypeError(`Duplicate name '${P}'.`);i.add(P),a.push(new R(O,P,L(h),m,L(A),g));};for(;l<r.length;){let h=o("CHAR"),u=o("NAME"),p=o("REGEX");if(!u&&!p&&(p=o("ASTERISK")),u||p){let g=h??"";t.prefixes.indexOf(g)===-1&&(U(g),g=""),$();let m=f();X(g,u,p,"",m);continue}let A=h??o("ESCAPED_CHAR");if(A){U(A);continue}if(o("OPEN")){let g=T(),m=o("NAME"),O=o("REGEX");!m&&!O&&(O=o("ASTERISK"));let P=T();d("CLOSE");let be=f();X(g,m,O,P,be);continue}$(),d("END");}return a}function S(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function B(e){return e&&e.ignoreCase?"ui":"u"}function q(e,t,r){return W(F(e,r),t,r)}function k(e){switch(e){case 0:return "*";case 1:return "?";case 2:return "+";case 3:return ""}}function W(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let n=r.start?"^":"";for(let s of e){if(s.type===3){s.modifier===3?n+=S(s.value):n+=`(?:${S(s.value)})${k(s.modifier)}`;continue}t&&t.push(s.name);let i=`[^${S(r.delimiter)}]+?`,o=s.value;if(s.type===1?o=i:s.type===0&&(o=v),!s.prefix.length&&!s.suffix.length){s.modifier===3||s.modifier===1?n+=`(${o})${k(s.modifier)}`:n+=`((?:${o})${k(s.modifier)})`;continue}if(s.modifier===3||s.modifier===1){n+=`(?:${S(s.prefix)}(${o})${S(s.suffix)})`,n+=k(s.modifier);continue}n+=`(?:${S(s.prefix)}`,n+=`((?:${o})(?:`,n+=S(s.suffix),n+=S(s.prefix),n+=`(?:${o}))*)${S(s.suffix)})`,s.modifier===0&&(n+="?");}let a=`[${S(r.endsWith)}]|$`,c=`[${S(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${c}?`),r.endsWith.length?n+=`(?=${a})`:n+="$",new RegExp(n,B(r));r.strict||(n+=`(?:${c}(?=${a}))?`);let l=!1;if(e.length){let s=e[e.length-1];s.type===3&&s.modifier===3&&(l=r.delimiter.indexOf(s)>-1);}return l||(n+=`(?=${c}|${a})`),new RegExp(n,B(r))}var x={delimiter:"",prefixes:"",sensitive:!0,strict:!0},J={delimiter:".",prefixes:"",sensitive:!0,strict:!0},Q={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function ee(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function te(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function Ce(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function _(e){return !e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var re=["ftp","file","http","https","ws","wss"];function N(e){if(!e)return !0;for(let t of re)if(e.test(t))return !0;return !1}function ne(e,t){if(e=te(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}function se(e,t){if(e=te(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}function ie(e,t){return t||e===""?e:_(e)?K(e):j(e)}function ae(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function oe(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function ce(e,t,r){if(r||e==="")return e;if(t&&!re.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]=="/";return e=new URL(n?e:"/-"+e,"https://example.com").pathname,n||(e=e.substring(2,e.length)),e}function le(e,t,r){return z(t)===e&&(e=""),r||e===""?e:G(e)}function fe(e,t){return e=Ce(e,":"),t||e===""?e:y(e)}function z(e){switch(e){case"ws":case"http":return "80";case"wws":case"https":return "443";case"ftp":return "21";default:return ""}}function y(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function he(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function ue(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function j(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}function K(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function G(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function de(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}function pe(e){return e===""?e:new URL(`data:${e}`).pathname}function ge(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function me(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var H=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(t){this.#i=t;}get result(){return this.#t}parse(){for(this.#n=D(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type==="END"){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())this.#d-=1;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r);}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&(this.#p-=1),this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="");}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?"/":""),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??="")),this.#R(t,r);}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0;}#b(){this.#e=this.#l,this.#s=0;}#u(t){this.#b(),this.#o=t;}#m(t){return t<0&&(t=this.#n.length-t),t<this.#n.length?this.#n[t]:this.#n[this.#n.length-1]}#a(t,r){let n=this.#m(t);return n.value===r&&(n.type==="CHAR"||n.type==="ESCAPED_CHAR"||n.type==="INVALID_CHAR")}#P(){return this.#a(this.#e,":")}#E(){return this.#a(this.#e+1,"/")&&this.#a(this.#e+2,"/")}#S(){return this.#a(this.#e,"@")}#O(){return this.#a(this.#e,":")}#k(){return this.#a(this.#e,":")}#x(){return this.#a(this.#e,"/")}#h(){if(this.#a(this.#e,"?"))return !0;if(this.#n[this.#e].value!=="?")return !1;let t=this.#m(this.#e-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#f(){return this.#a(this.#e,"#")}#T(){return this.#n[this.#e].type=="OPEN"}#A(){return this.#n[this.#e].type=="CLOSE"}#y(){return this.#a(this.#e,"[")}#w(){return this.#a(this.#e,"]")}#c(){let t=this.#n[this.#e],r=this.#m(this.#l).index;return this.#i.substring(r,t.index)}#C(){let t={};Object.assign(t,x),t.encodePart=y;let r=q(this.#c(),void 0,t);this.#g=N(r);}};var V=["protocol","username","password","hostname","port","pathname","search","hash"],E="*";function Se(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return {protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function b(e,t){return t?C(e):e}function w(e,t,r){let n;if(typeof t.baseURL=="string")try{n=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=b(n.protocol.substring(0,n.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=b(n.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=b(n.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=b(n.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=b(n.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=b(n.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=b(n.search.substring(1,n.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=b(n.hash.substring(1,n.hash.length),r));}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol=="string"&&(e.protocol=fe(t.protocol,r)),typeof t.username=="string"&&(e.username=oe(t.username,r)),typeof t.password=="string"&&(e.password=ae(t.password,r)),typeof t.hostname=="string"&&(e.hostname=ie(t.hostname,r)),typeof t.port=="string"&&(e.port=le(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,n&&!ee(e.pathname,r)){let a=n.pathname.lastIndexOf("/");a>=0&&(e.pathname=b(n.pathname.substring(0,a+1),r)+e.pathname);}e.pathname=ce(e.pathname,e.protocol,r);}return typeof t.search=="string"&&(e.search=se(t.search,r)),typeof t.hash=="string"&&(e.hash=ne(t.hash,r)),e}function C(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function Le(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Ie(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",n=`[^${Le(t.delimiter)}]+?`,a=/[$_\u200C\u200D\p{ID_Continue}]/u,c="";for(let l=0;l<e.length;++l){let s=e[l];if(s.type===3){if(s.modifier===3){c+=C(s.value);continue}c+=`{${C(s.value)}}${k(s.modifier)}`;continue}let i=s.hasCustomName(),o=!!s.suffix.length||!!s.prefix.length&&(s.prefix.length!==1||!t.prefixes.includes(s.prefix)),f=l>0?e[l-1]:null,d=l<e.length-1?e[l+1]:null;if(!o&&i&&s.type===1&&s.modifier===3&&d&&!d.prefix.length&&!d.suffix.length)if(d.type===3){let T=d.value.length>0?d.value[0]:"";o=a.test(T);}else o=!d.hasCustomName();if(!o&&!s.prefix.length&&f&&f.type===3){let T=f.value[f.value.length-1];o=t.prefixes.includes(T);}o&&(c+="{"),c+=C(s.prefix),i&&(c+=`:${s.name}`),s.type===2?c+=`(${s.value})`:s.type===1?i||(c+=`(${n})`):s.type===0&&(!i&&(!f||f.type===3||f.modifier!==3||o||s.prefix!=="")?c+="*":c+=`(${r})`),s.type===1&&i&&s.suffix.length&&a.test(s.suffix[0])&&(c+="\\"),c+=C(s.suffix),o&&(c+="}"),s.modifier!==3&&(c+=k(s.modifier));}return c}var Y=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(t={},r,n){try{let a;if(typeof r=="string"?a=r:n=r,typeof t=="string"){let i=new H(t);if(i.parse(),t=i.result,a===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=a;}else {if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(a)throw new TypeError("parameter 1 is not of type 'string'.")}typeof n>"u"&&(n={ignoreCase:!1});let c={ignoreCase:n.ignoreCase===!0},l={pathname:E,protocol:E,username:E,password:E,hostname:E,port:E,search:E,hash:E};this.#i=w(l,t,!0),z(this.#i.protocol)===this.#i.port&&(this.#i.port="");let s;for(s of V){if(!(s in this.#i))continue;let i={},o=this.#i[s];switch(this.#t[s]=[],s){case"protocol":Object.assign(i,x),i.encodePart=y;break;case"username":Object.assign(i,x),i.encodePart=he;break;case"password":Object.assign(i,x),i.encodePart=ue;break;case"hostname":Object.assign(i,J),_(o)?i.encodePart=K:i.encodePart=j;break;case"port":Object.assign(i,x),i.encodePart=G;break;case"pathname":N(this.#n.protocol)?(Object.assign(i,Q,c),i.encodePart=de):(Object.assign(i,x,c),i.encodePart=pe);break;case"search":Object.assign(i,x,c),i.encodePart=ge;break;case"hash":Object.assign(i,x,c),i.encodePart=me;break}try{this.#s[s]=F(o,i),this.#n[s]=W(this.#s[s],this.#t[s],i),this.#e[s]=Ie(this.#s[s],i),this.#l=this.#l||this.#s[s].some(f=>f.type===2);}catch{throw new TypeError(`invalid ${s} pattern '${this.#i[s]}'.`)}}}catch(a){throw new TypeError(`Failed to construct 'URLPattern': ${a.message}`)}}test(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return !1;try{typeof t=="object"?n=w(n,t,!1):n=w(n,Se(t,r),!1);}catch{return !1}let a;for(a of V)if(!this.#n[a].exec(n[a]))return !1;return !0}exec(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?n=w(n,t,!1):n=w(n,Se(t,r),!1);}catch{return null}let a={};r?a.inputs=[t,r]:a.inputs=[t];let c;for(c of V){let l=this.#n[c].exec(n[c]);if(!l)return null;let s={};for(let[i,o]of this.#t[c].entries())if(typeof o=="string"||typeof o=="number"){let f=l[i+1];s[o]=f;}a[c]={input:n[c]??"",groups:s};}return a}static compareComponent(t,r,n){let a=(i,o)=>{for(let f of ["type","modifier","prefix","value","suffix"]){if(i[f]<o[f])return -1;if(i[f]===o[f])continue;return 1}return 0},c=new R(3,"","","","",3),l=new R(0,"","","","",3),s=(i,o)=>{let f=0;for(;f<Math.min(i.length,o.length);++f){let d=a(i[f],o[f]);if(d)return d}return i.length===o.length?0:a(i[f]??c,o[f]??c)};return !r.#e[t]&&!n.#e[t]?0:r.#e[t]&&!n.#e[t]?s(r.#s[t],[l]):!r.#e[t]&&n.#e[t]?s([l],n.#s[t]):s(r.#s[t],n.#s[t])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}};
  3042. const { URLPattern: URLPattern$2 } = urlpattern;
  3043. var urlpatternPolyfill = { URLPattern: URLPattern$2 };
  3044. if (!globalThis.URLPattern) {
  3045. globalThis.URLPattern = URLPattern$2;
  3046. }
  3047. Object.defineProperty(UrlPattern, "__esModule", { value: true });
  3048. UrlPattern.URLPattern = void 0;
  3049. /**
  3050. * Copyright 2023 Google LLC.
  3051. * Copyright (c) Microsoft Corporation.
  3052. *
  3053. * Licensed under the Apache License, Version 2.0 (the "License");
  3054. * you may not use this file except in compliance with the License.
  3055. * You may obtain a copy of the License at
  3056. *
  3057. * http://www.apache.org/licenses/LICENSE-2.0
  3058. *
  3059. * Unless required by applicable law or agreed to in writing, software
  3060. * distributed under the License is distributed on an "AS IS" BASIS,
  3061. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3062. * See the License for the specific language governing permissions and
  3063. * limitations under the License.
  3064. */
  3065. const urlpattern_polyfill_1 = urlpatternPolyfill;
  3066. // XXX: Switch to native URLPattern when available.
  3067. // https://github.com/nodejs/node/issues/40844
  3068. let URLPattern$1 = urlpattern_polyfill_1.URLPattern;
  3069. UrlPattern.URLPattern = URLPattern$1;
  3070. if ('URLPattern' in globalThis) {
  3071. UrlPattern.URLPattern = URLPattern$1 = globalThis.URLPattern;
  3072. }
  3073. /*
  3074. * Copyright 2023 Google LLC.
  3075. * Copyright (c) Microsoft Corporation.
  3076. *
  3077. * Licensed under the Apache License, Version 2.0 (the "License");
  3078. * you may not use this file except in compliance with the License.
  3079. * You may obtain a copy of the License at
  3080. *
  3081. * http://www.apache.org/licenses/LICENSE-2.0
  3082. *
  3083. * Unless required by applicable law or agreed to in writing, software
  3084. * distributed under the License is distributed on an "AS IS" BASIS,
  3085. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3086. * See the License for the specific language governing permissions and
  3087. * limitations under the License.
  3088. *
  3089. */
  3090. Object.defineProperty(NetworkUtils, "__esModule", { value: true });
  3091. NetworkUtils.matchUrlPattern = NetworkUtils.isSpecialScheme = NetworkUtils.sameSiteBiDiToCdp = NetworkUtils.bidiToCdpCookie = NetworkUtils.deserializeByteValue = NetworkUtils.cdpToBiDiCookie = NetworkUtils.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction = NetworkUtils.cdpFetchHeadersFromBidiNetworkHeaders = NetworkUtils.bidiNetworkHeadersFromCdpFetchHeaders = NetworkUtils.cdpNetworkHeadersFromBidiNetworkHeaders = NetworkUtils.bidiNetworkHeadersFromCdpNetworkHeaders = NetworkUtils.computeHeadersSize = void 0;
  3092. const ErrorResponse_js_1 = ErrorResponse;
  3093. const Base64_js_1 = Base64;
  3094. const UrlPattern_js_1 = UrlPattern;
  3095. function computeHeadersSize(headers) {
  3096. const requestHeaders = headers.reduce((acc, header) => {
  3097. return `${acc}${header.name}: ${header.value.value}\r\n`;
  3098. }, '');
  3099. return new TextEncoder().encode(requestHeaders).length;
  3100. }
  3101. NetworkUtils.computeHeadersSize = computeHeadersSize;
  3102. /** Converts from CDP Network domain headers to Bidi network headers. */
  3103. function bidiNetworkHeadersFromCdpNetworkHeaders(headers) {
  3104. if (!headers) {
  3105. return [];
  3106. }
  3107. return Object.entries(headers).map(([name, value]) => ({
  3108. name,
  3109. value: {
  3110. type: 'string',
  3111. value,
  3112. },
  3113. }));
  3114. }
  3115. NetworkUtils.bidiNetworkHeadersFromCdpNetworkHeaders = bidiNetworkHeadersFromCdpNetworkHeaders;
  3116. /** Converts from Bidi network headers to CDP Network domain headers. */
  3117. function cdpNetworkHeadersFromBidiNetworkHeaders(headers) {
  3118. if (headers === undefined) {
  3119. return undefined;
  3120. }
  3121. return headers.reduce((result, header) => {
  3122. // TODO: Distinguish between string and bytes?
  3123. result[header.name] = header.value.value;
  3124. return result;
  3125. }, {});
  3126. }
  3127. NetworkUtils.cdpNetworkHeadersFromBidiNetworkHeaders = cdpNetworkHeadersFromBidiNetworkHeaders;
  3128. /** Converts from CDP Fetch domain header entries to Bidi network headers. */
  3129. function bidiNetworkHeadersFromCdpFetchHeaders(headers) {
  3130. if (!headers) {
  3131. return [];
  3132. }
  3133. return headers.map(({ name, value }) => ({
  3134. name,
  3135. value: {
  3136. type: 'string',
  3137. value,
  3138. },
  3139. }));
  3140. }
  3141. NetworkUtils.bidiNetworkHeadersFromCdpFetchHeaders = bidiNetworkHeadersFromCdpFetchHeaders;
  3142. /** Converts from Bidi network headers to CDP Fetch domain header entries. */
  3143. function cdpFetchHeadersFromBidiNetworkHeaders(headers) {
  3144. if (headers === undefined) {
  3145. return undefined;
  3146. }
  3147. return headers.map(({ name, value }) => ({
  3148. name,
  3149. value: value.value,
  3150. }));
  3151. }
  3152. NetworkUtils.cdpFetchHeadersFromBidiNetworkHeaders = cdpFetchHeadersFromBidiNetworkHeaders;
  3153. /** Converts from Bidi auth action to CDP auth challenge response. */
  3154. function cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction(action) {
  3155. switch (action) {
  3156. case 'default':
  3157. return 'Default';
  3158. case 'cancel':
  3159. return 'CancelAuth';
  3160. case 'provideCredentials':
  3161. return 'ProvideCredentials';
  3162. }
  3163. }
  3164. NetworkUtils.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction = cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction;
  3165. /**
  3166. * Converts from CDP Network domain cookie to BiDi network cookie.
  3167. * * https://chromedevtools.github.io/devtools-protocol/tot/Network/#type-Cookie
  3168. * * https://w3c.github.io/webdriver-bidi/#type-network-Cookie
  3169. */
  3170. function cdpToBiDiCookie(cookie) {
  3171. const result = {
  3172. name: cookie.name,
  3173. value: { type: 'string', value: cookie.value },
  3174. domain: cookie.domain,
  3175. path: cookie.path,
  3176. size: cookie.size,
  3177. httpOnly: cookie.httpOnly,
  3178. secure: cookie.secure,
  3179. sameSite: cookie.sameSite === undefined
  3180. ? "none" /* Network.SameSite.None */
  3181. : sameSiteCdpToBiDi(cookie.sameSite),
  3182. ...(cookie.expires >= 0 ? { expiry: cookie.expires } : undefined),
  3183. };
  3184. // Extending with CDP-specific properties with `goog:` prefix.
  3185. result[`goog:session`] = cookie.session;
  3186. result[`goog:priority`] = cookie.priority;
  3187. result[`goog:sameParty`] = cookie.sameParty;
  3188. result[`goog:sourceScheme`] = cookie.sourceScheme;
  3189. result[`goog:sourcePort`] = cookie.sourcePort;
  3190. if (cookie.partitionKey !== undefined) {
  3191. result[`goog:partitionKey`] = cookie.partitionKey;
  3192. }
  3193. if (cookie.partitionKeyOpaque !== undefined) {
  3194. result[`goog:partitionKeyOpaque`] = cookie.partitionKeyOpaque;
  3195. }
  3196. return result;
  3197. }
  3198. NetworkUtils.cdpToBiDiCookie = cdpToBiDiCookie;
  3199. /**
  3200. * Decodes a byte value to a string.
  3201. * @param {Network.BytesValue} value
  3202. * @return {string}
  3203. */
  3204. function deserializeByteValue(value) {
  3205. if (value.type === 'base64') {
  3206. return (0, Base64_js_1.base64ToString)(value.value);
  3207. }
  3208. return value.value;
  3209. }
  3210. NetworkUtils.deserializeByteValue = deserializeByteValue;
  3211. /**
  3212. * Converts from BiDi set network cookie params to CDP Network domain cookie.
  3213. * * https://w3c.github.io/webdriver-bidi/#type-network-Cookie
  3214. * * https://chromedevtools.github.io/devtools-protocol/tot/Network/#type-CookieParam
  3215. */
  3216. function bidiToCdpCookie(params, partitionKey) {
  3217. const deserializedValue = deserializeByteValue(params.cookie.value);
  3218. const result = {
  3219. name: params.cookie.name,
  3220. value: deserializedValue,
  3221. domain: params.cookie.domain,
  3222. path: params.cookie.path ?? '/',
  3223. secure: params.cookie.secure ?? false,
  3224. httpOnly: params.cookie.httpOnly ?? false,
  3225. // CDP's `partitionKey` is the BiDi's `partition.sourceOrigin`.
  3226. ...(partitionKey.sourceOrigin !== undefined && {
  3227. partitionKey: partitionKey.sourceOrigin,
  3228. }),
  3229. ...(params.cookie.expiry !== undefined && {
  3230. expires: params.cookie.expiry,
  3231. }),
  3232. ...(params.cookie.sameSite !== undefined && {
  3233. sameSite: sameSiteBiDiToCdp(params.cookie.sameSite),
  3234. }),
  3235. };
  3236. // Extending with CDP-specific properties with `goog:` prefix.
  3237. if (params.cookie[`goog:url`] !== undefined) {
  3238. result.url = params.cookie[`goog:url`];
  3239. }
  3240. if (params.cookie[`goog:priority`] !== undefined) {
  3241. result.priority = params.cookie[`goog:priority`];
  3242. }
  3243. if (params.cookie[`goog:sameParty`] !== undefined) {
  3244. result.sameParty = params.cookie[`goog:sameParty`];
  3245. }
  3246. if (params.cookie[`goog:sourceScheme`] !== undefined) {
  3247. result.sourceScheme = params.cookie[`goog:sourceScheme`];
  3248. }
  3249. if (params.cookie[`goog:sourcePort`] !== undefined) {
  3250. result.sourcePort = params.cookie[`goog:sourcePort`];
  3251. }
  3252. return result;
  3253. }
  3254. NetworkUtils.bidiToCdpCookie = bidiToCdpCookie;
  3255. function sameSiteCdpToBiDi(sameSite) {
  3256. switch (sameSite) {
  3257. case 'Strict':
  3258. return "strict" /* Network.SameSite.Strict */;
  3259. case 'None':
  3260. return "none" /* Network.SameSite.None */;
  3261. case 'Lax':
  3262. return "lax" /* Network.SameSite.Lax */;
  3263. default:
  3264. // Defaults to `Lax`:
  3265. // https://web.dev/articles/samesite-cookies-explained#samesitelax_by_default
  3266. return "lax" /* Network.SameSite.Lax */;
  3267. }
  3268. }
  3269. function sameSiteBiDiToCdp(sameSite) {
  3270. switch (sameSite) {
  3271. case "strict" /* Network.SameSite.Strict */:
  3272. return 'Strict';
  3273. case "lax" /* Network.SameSite.Lax */:
  3274. return 'Lax';
  3275. case "none" /* Network.SameSite.None */:
  3276. return 'None';
  3277. }
  3278. throw new ErrorResponse_js_1.InvalidArgumentException(`Unknown 'sameSite' value ${sameSite}`);
  3279. }
  3280. NetworkUtils.sameSiteBiDiToCdp = sameSiteBiDiToCdp;
  3281. /**
  3282. * Returns true if the given protocol is special.
  3283. * Special protocols are those that have a default port.
  3284. *
  3285. * Example inputs: 'http', 'http:'
  3286. *
  3287. * @see https://url.spec.whatwg.org/#special-scheme
  3288. */
  3289. function isSpecialScheme(protocol) {
  3290. return ['ftp', 'file', 'http', 'https', 'ws', 'wss'].includes(protocol.replace(/:$/, ''));
  3291. }
  3292. NetworkUtils.isSpecialScheme = isSpecialScheme;
  3293. /** Matches the given URLPattern against the given URL. */
  3294. function matchUrlPattern(urlPattern, url) {
  3295. switch (urlPattern.type) {
  3296. case 'string': {
  3297. const pattern = new UrlPattern_js_1.URLPattern(urlPattern.pattern);
  3298. return new UrlPattern_js_1.URLPattern({
  3299. protocol: pattern.protocol,
  3300. hostname: pattern.hostname,
  3301. port: pattern.port,
  3302. pathname: pattern.pathname,
  3303. search: pattern.search,
  3304. }).test(url);
  3305. }
  3306. case 'pattern':
  3307. return new UrlPattern_js_1.URLPattern(urlPattern).test(url);
  3308. }
  3309. }
  3310. NetworkUtils.matchUrlPattern = matchUrlPattern;
  3311. Object.defineProperty(NetworkProcessor$1, "__esModule", { value: true });
  3312. NetworkProcessor$1.NetworkProcessor = void 0;
  3313. const protocol_js_1$h = protocol;
  3314. const NetworkUtils_js_1$3 = NetworkUtils;
  3315. /** Dispatches Network domain commands. */
  3316. class NetworkProcessor {
  3317. #browsingContextStorage;
  3318. #networkStorage;
  3319. constructor(browsingContextStorage, networkStorage) {
  3320. this.#browsingContextStorage = browsingContextStorage;
  3321. this.#networkStorage = networkStorage;
  3322. }
  3323. async addIntercept(params) {
  3324. this.#browsingContextStorage.verifyTopLevelContextsList(params.contexts);
  3325. const urlPatterns = params.urlPatterns ?? [];
  3326. const parsedUrlPatterns = NetworkProcessor.parseUrlPatterns(urlPatterns);
  3327. const intercept = this.#networkStorage.addIntercept({
  3328. urlPatterns: parsedUrlPatterns,
  3329. phases: params.phases,
  3330. contexts: params.contexts,
  3331. });
  3332. await Promise.all(this.#browsingContextStorage.getAllContexts().map((context) => {
  3333. return context.cdpTarget.toggleFetchIfNeeded();
  3334. }));
  3335. return {
  3336. intercept,
  3337. };
  3338. }
  3339. async continueRequest(params) {
  3340. const { url, method, headers: commandHeaders, body, request: networkId, } = params;
  3341. if (params.url !== undefined) {
  3342. NetworkProcessor.parseUrlString(params.url);
  3343. }
  3344. const request = this.#getBlockedRequestOrFail(networkId, [
  3345. "beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */,
  3346. ]);
  3347. const headers = (0, NetworkUtils_js_1$3.cdpFetchHeadersFromBidiNetworkHeaders)(commandHeaders);
  3348. // TODO: Set / expand.
  3349. // ; Step 9. cookies
  3350. await request.continueRequest({
  3351. url,
  3352. method,
  3353. headers,
  3354. postData: getCdpBodyFromBiDiBytesValue(body),
  3355. });
  3356. return {};
  3357. }
  3358. async continueResponse(params) {
  3359. const { request: networkId, statusCode, reasonPhrase, headers } = params;
  3360. const responseHeaders = (0, NetworkUtils_js_1$3.cdpFetchHeadersFromBidiNetworkHeaders)(headers);
  3361. const request = this.#getBlockedRequestOrFail(networkId, [
  3362. "authRequired" /* Network.InterceptPhase.AuthRequired */,
  3363. "responseStarted" /* Network.InterceptPhase.ResponseStarted */,
  3364. ]);
  3365. if (request.interceptPhase === "authRequired" /* Network.InterceptPhase.AuthRequired */) {
  3366. if (params.credentials) {
  3367. await Promise.all([
  3368. request.waitNextPhase,
  3369. request.continueWithAuth({
  3370. response: 'ProvideCredentials',
  3371. username: params.credentials.username,
  3372. password: params.credentials.password,
  3373. }),
  3374. ]);
  3375. }
  3376. else {
  3377. // We need to use `ProvideCredentials`
  3378. // As `Default` may cancel the request
  3379. await request.continueWithAuth({
  3380. response: 'ProvideCredentials',
  3381. });
  3382. return {};
  3383. }
  3384. }
  3385. if (request.interceptPhase === "responseStarted" /* Network.InterceptPhase.ResponseStarted */) {
  3386. // TODO: Set / expand.
  3387. // ; Step 10. cookies
  3388. await request.continueResponse({
  3389. responseCode: statusCode,
  3390. responsePhrase: reasonPhrase,
  3391. responseHeaders,
  3392. });
  3393. }
  3394. return {};
  3395. }
  3396. async continueWithAuth(params) {
  3397. const networkId = params.request;
  3398. const request = this.#getBlockedRequestOrFail(networkId, [
  3399. "authRequired" /* Network.InterceptPhase.AuthRequired */,
  3400. ]);
  3401. let username;
  3402. let password;
  3403. if (params.action === 'provideCredentials') {
  3404. const { credentials } = params;
  3405. username = credentials.username;
  3406. password = credentials.password;
  3407. }
  3408. const response = (0, NetworkUtils_js_1$3.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction)(params.action);
  3409. await request.continueWithAuth({
  3410. response,
  3411. username,
  3412. password,
  3413. });
  3414. return {};
  3415. }
  3416. async failRequest({ request: networkId, }) {
  3417. const request = this.#getRequestOrFail(networkId);
  3418. if (request.interceptPhase === "authRequired" /* Network.InterceptPhase.AuthRequired */) {
  3419. throw new protocol_js_1$h.InvalidArgumentException(`Request '${networkId}' in 'authRequired' phase cannot be failed`);
  3420. }
  3421. if (!request.interceptPhase) {
  3422. throw new protocol_js_1$h.NoSuchRequestException(`No blocked request found for network id '${networkId}'`);
  3423. }
  3424. await request.failRequest('Failed');
  3425. return {};
  3426. }
  3427. async provideResponse(params) {
  3428. const { statusCode, reasonPhrase: responsePhrase, headers, body, request: networkId, } = params;
  3429. // TODO: Step 6
  3430. // https://w3c.github.io/webdriver-bidi/#command-network-continueResponse
  3431. const responseHeaders = (0, NetworkUtils_js_1$3.cdpFetchHeadersFromBidiNetworkHeaders)(headers);
  3432. // TODO: Set / expand.
  3433. // ; Step 10. cookies
  3434. // ; Step 11. credentials
  3435. const request = this.#getBlockedRequestOrFail(networkId, [
  3436. "beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */,
  3437. "responseStarted" /* Network.InterceptPhase.ResponseStarted */,
  3438. "authRequired" /* Network.InterceptPhase.AuthRequired */,
  3439. ]);
  3440. // We need to pass through if the request is already in
  3441. // AuthRequired phase
  3442. if (request.interceptPhase === "authRequired" /* Network.InterceptPhase.AuthRequired */) {
  3443. // We need to use `ProvideCredentials`
  3444. // As `Default` may cancel the request
  3445. await request.continueWithAuth({
  3446. response: 'ProvideCredentials',
  3447. });
  3448. return {};
  3449. }
  3450. // If we con't modify the response
  3451. // Just continue the request
  3452. if (!body && !headers) {
  3453. await request.continueRequest();
  3454. return {};
  3455. }
  3456. const responseCode = statusCode ?? request.statusCode ?? 200;
  3457. await request.provideResponse({
  3458. responseCode,
  3459. responsePhrase,
  3460. responseHeaders,
  3461. body: getCdpBodyFromBiDiBytesValue(body),
  3462. });
  3463. return {};
  3464. }
  3465. async removeIntercept(params) {
  3466. this.#networkStorage.removeIntercept(params.intercept);
  3467. await Promise.all(this.#browsingContextStorage.getAllContexts().map((context) => {
  3468. return context.cdpTarget.toggleFetchIfNeeded();
  3469. }));
  3470. return {};
  3471. }
  3472. #getRequestOrFail(id) {
  3473. const request = this.#networkStorage.getRequestById(id);
  3474. if (!request) {
  3475. throw new protocol_js_1$h.NoSuchRequestException(`Network request with ID '${id}' doesn't exist`);
  3476. }
  3477. return request;
  3478. }
  3479. #getBlockedRequestOrFail(id, phases) {
  3480. const request = this.#getRequestOrFail(id);
  3481. if (!request.interceptPhase) {
  3482. throw new protocol_js_1$h.NoSuchRequestException(`No blocked request found for network id '${id}'`);
  3483. }
  3484. if (request.interceptPhase && !phases.includes(request.interceptPhase)) {
  3485. throw new protocol_js_1$h.InvalidArgumentException(`Blocked request for network id '${id}' is in '${request.interceptPhase}' phase`);
  3486. }
  3487. return request;
  3488. }
  3489. /**
  3490. * Attempts to parse the given url.
  3491. * Throws an InvalidArgumentException if the url is invalid.
  3492. */
  3493. static parseUrlString(url) {
  3494. try {
  3495. return new URL(url);
  3496. }
  3497. catch (error) {
  3498. throw new protocol_js_1$h.InvalidArgumentException(`Invalid URL '${url}': ${error}`);
  3499. }
  3500. }
  3501. static parseUrlPatterns(urlPatterns) {
  3502. return urlPatterns.map((urlPattern) => {
  3503. switch (urlPattern.type) {
  3504. case 'string': {
  3505. NetworkProcessor.parseUrlString(urlPattern.pattern);
  3506. return urlPattern;
  3507. }
  3508. case 'pattern':
  3509. // No params signifies intercept all
  3510. if (urlPattern.protocol === undefined &&
  3511. urlPattern.hostname === undefined &&
  3512. urlPattern.port === undefined &&
  3513. urlPattern.pathname === undefined &&
  3514. urlPattern.search === undefined) {
  3515. return urlPattern;
  3516. }
  3517. if (urlPattern.protocol) {
  3518. urlPattern.protocol = unescapeURLPattern(urlPattern.protocol);
  3519. if (!urlPattern.protocol.match(/^[a-zA-Z+-.]+$/)) {
  3520. throw new protocol_js_1$h.InvalidArgumentException('Forbidden characters');
  3521. }
  3522. }
  3523. if (urlPattern.hostname) {
  3524. urlPattern.hostname = unescapeURLPattern(urlPattern.hostname);
  3525. }
  3526. if (urlPattern.port) {
  3527. urlPattern.port = unescapeURLPattern(urlPattern.port);
  3528. }
  3529. if (urlPattern.pathname) {
  3530. urlPattern.pathname = unescapeURLPattern(urlPattern.pathname);
  3531. if (urlPattern.pathname[0] !== '/') {
  3532. urlPattern.pathname = `/${urlPattern.pathname}`;
  3533. }
  3534. if (urlPattern.pathname.includes('#') ||
  3535. urlPattern.pathname.includes('?')) {
  3536. throw new protocol_js_1$h.InvalidArgumentException('Forbidden characters');
  3537. }
  3538. }
  3539. else if (urlPattern.pathname === '') {
  3540. urlPattern.pathname = '/';
  3541. }
  3542. if (urlPattern.search) {
  3543. urlPattern.search = unescapeURLPattern(urlPattern.search);
  3544. if (urlPattern.search[0] !== '?') {
  3545. urlPattern.search = `?${urlPattern.search}`;
  3546. }
  3547. if (urlPattern.search.includes('#')) {
  3548. throw new protocol_js_1$h.InvalidArgumentException('Forbidden characters');
  3549. }
  3550. }
  3551. if (urlPattern.protocol === '') {
  3552. throw new protocol_js_1$h.InvalidArgumentException(`URL pattern must specify a protocol`);
  3553. }
  3554. if (urlPattern.hostname === '') {
  3555. throw new protocol_js_1$h.InvalidArgumentException(`URL pattern must specify a hostname`);
  3556. }
  3557. if ((urlPattern.hostname?.length ?? 0) > 0) {
  3558. if (urlPattern.protocol?.match(/^file/i)) {
  3559. throw new protocol_js_1$h.InvalidArgumentException(`URL pattern protocol cannot be 'file'`);
  3560. }
  3561. if (urlPattern.hostname?.includes(':')) {
  3562. throw new protocol_js_1$h.InvalidArgumentException(`URL pattern hostname must not contain a colon`);
  3563. }
  3564. }
  3565. if (urlPattern.port === '') {
  3566. throw new protocol_js_1$h.InvalidArgumentException(`URL pattern must specify a port`);
  3567. }
  3568. try {
  3569. new URLPattern(urlPattern);
  3570. }
  3571. catch (error) {
  3572. throw new protocol_js_1$h.InvalidArgumentException(`${error}`);
  3573. }
  3574. return urlPattern;
  3575. }
  3576. });
  3577. }
  3578. }
  3579. NetworkProcessor$1.NetworkProcessor = NetworkProcessor;
  3580. /**
  3581. * See https://w3c.github.io/webdriver-bidi/#unescape-url-pattern
  3582. */
  3583. function unescapeURLPattern(pattern) {
  3584. const forbidden = new Set(['(', ')', '*', '{', '}']);
  3585. let result = '';
  3586. let isEscaped = false;
  3587. for (const c of pattern) {
  3588. if (!isEscaped) {
  3589. if (forbidden.has(c)) {
  3590. throw new protocol_js_1$h.InvalidArgumentException('Forbidden characters');
  3591. }
  3592. if (c === '\\') {
  3593. isEscaped = true;
  3594. continue;
  3595. }
  3596. }
  3597. result += c;
  3598. isEscaped = false;
  3599. }
  3600. return result;
  3601. }
  3602. function getCdpBodyFromBiDiBytesValue(body) {
  3603. let parsedBody;
  3604. if (body?.type === 'string') {
  3605. parsedBody = btoa(body.value);
  3606. }
  3607. else if (body?.type === 'base64') {
  3608. parsedBody = body.value;
  3609. }
  3610. return parsedBody;
  3611. }
  3612. var PermissionsProcessor$1 = {};
  3613. /**
  3614. * Copyright 2024 Google LLC.
  3615. * Copyright (c) Microsoft Corporation.
  3616. *
  3617. * Licensed under the Apache License, Version 2.0 (the "License");
  3618. * you may not use this file except in compliance with the License.
  3619. * You may obtain a copy of the License at
  3620. *
  3621. * http://www.apache.org/licenses/LICENSE-2.0
  3622. *
  3623. * Unless required by applicable law or agreed to in writing, software
  3624. * distributed under the License is distributed on an "AS IS" BASIS,
  3625. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3626. * See the License for the specific language governing permissions and
  3627. * limitations under the License.
  3628. */
  3629. Object.defineProperty(PermissionsProcessor$1, "__esModule", { value: true });
  3630. PermissionsProcessor$1.PermissionsProcessor = void 0;
  3631. const protocol_js_1$g = protocol;
  3632. class PermissionsProcessor {
  3633. #browserCdpClient;
  3634. constructor(browserCdpClient) {
  3635. this.#browserCdpClient = browserCdpClient;
  3636. }
  3637. async setPermissions(params) {
  3638. try {
  3639. const userContextId = params['goog:userContext'] ||
  3640. params.userContext;
  3641. await this.#browserCdpClient.sendCommand('Browser.setPermission', {
  3642. origin: params.origin,
  3643. browserContextId: userContextId && userContextId !== 'default'
  3644. ? userContextId
  3645. : undefined,
  3646. permission: {
  3647. name: params.descriptor.name,
  3648. },
  3649. setting: params.state,
  3650. });
  3651. }
  3652. catch (err) {
  3653. if (err.message ===
  3654. `Permission can't be granted to opaque origins.`) {
  3655. // Return success if the origin is not valid (does not match any
  3656. // existing origins).
  3657. return {};
  3658. }
  3659. throw new protocol_js_1$g.InvalidArgumentException(err.message);
  3660. }
  3661. return {};
  3662. }
  3663. }
  3664. PermissionsProcessor$1.PermissionsProcessor = PermissionsProcessor;
  3665. var ScriptProcessor$1 = {};
  3666. var PreloadScript$1 = {};
  3667. var uuid = {};
  3668. /**
  3669. * Copyright 2023 Google LLC.
  3670. * Copyright (c) Microsoft Corporation.
  3671. *
  3672. * Licensed under the Apache License, Version 2.0 (the "License");
  3673. * you may not use this file except in compliance with the License.
  3674. * You may obtain a copy of the License at
  3675. *
  3676. * http://www.apache.org/licenses/LICENSE-2.0
  3677. *
  3678. * Unless required by applicable law or agreed to in writing, software
  3679. * distributed under the License is distributed on an "AS IS" BASIS,
  3680. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3681. * See the License for the specific language governing permissions and
  3682. * limitations under the License.
  3683. */
  3684. Object.defineProperty(uuid, "__esModule", { value: true });
  3685. uuid.uuidv4 = void 0;
  3686. /**
  3687. * Generates a random v4 UUID, as specified in RFC4122.
  3688. *
  3689. * Uses the native Web Crypto API if available, otherwise falls back to a
  3690. * polyfill.
  3691. *
  3692. * Example: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
  3693. */
  3694. function uuidv4() {
  3695. // Available only in secure contexts
  3696. // https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API
  3697. if ('crypto' in globalThis && 'randomUUID' in globalThis.crypto) {
  3698. // Node with
  3699. // https://nodejs.org/dist/latest-v20.x/docs/api/globals.html#crypto_1 or
  3700. // secure browser context.
  3701. return globalThis.crypto.randomUUID();
  3702. }
  3703. const randomValues = new Uint8Array(16);
  3704. if ('crypto' in globalThis && 'getRandomValues' in globalThis.crypto) {
  3705. // Node with
  3706. // https://nodejs.org/dist/latest-v20.x/docs/api/globals.html#crypto_1 or
  3707. // browser.
  3708. globalThis.crypto.getRandomValues(randomValues);
  3709. }
  3710. else {
  3711. // Node without
  3712. // https://nodejs.org/dist/latest-v20.x/docs/api/globals.html#crypto_1.
  3713. // eslint-disable-next-line @typescript-eslint/no-var-requires
  3714. require('crypto').webcrypto.getRandomValues(randomValues);
  3715. }
  3716. // Set version (4) and variant (RFC4122) bits.
  3717. randomValues[6] = (randomValues[6] & 0x0f) | 0x40;
  3718. randomValues[8] = (randomValues[8] & 0x3f) | 0x80;
  3719. const bytesToHex = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');
  3720. return [
  3721. bytesToHex(randomValues.subarray(0, 4)),
  3722. bytesToHex(randomValues.subarray(4, 6)),
  3723. bytesToHex(randomValues.subarray(6, 8)),
  3724. bytesToHex(randomValues.subarray(8, 10)),
  3725. bytesToHex(randomValues.subarray(10, 16)),
  3726. ].join('-');
  3727. }
  3728. uuid.uuidv4 = uuidv4;
  3729. var ChannelProxy$1 = {};
  3730. /*
  3731. * Copyright 2023 Google LLC.
  3732. * Copyright (c) Microsoft Corporation.
  3733. *
  3734. * Licensed under the Apache License, Version 2.0 (the "License");
  3735. * you may not use this file except in compliance with the License.
  3736. * You may obtain a copy of the License at
  3737. *
  3738. * http://www.apache.org/licenses/LICENSE-2.0
  3739. *
  3740. * Unless required by applicable law or agreed to in writing, software
  3741. * distributed under the License is distributed on an "AS IS" BASIS,
  3742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3743. * See the License for the specific language governing permissions and
  3744. * limitations under the License.
  3745. *
  3746. */
  3747. Object.defineProperty(ChannelProxy$1, "__esModule", { value: true });
  3748. ChannelProxy$1.ChannelProxy = void 0;
  3749. const protocol_js_1$f = protocol;
  3750. const log_js_1$c = log$1;
  3751. const uuid_js_1$3 = uuid;
  3752. /**
  3753. * Used to send messages from realm to BiDi user.
  3754. */
  3755. class ChannelProxy {
  3756. #properties;
  3757. #id = (0, uuid_js_1$3.uuidv4)();
  3758. #logger;
  3759. constructor(channel, logger) {
  3760. this.#properties = channel;
  3761. this.#logger = logger;
  3762. }
  3763. /**
  3764. * Creates a channel proxy in the given realm, initialises listener and
  3765. * returns a handle to `sendMessage` delegate.
  3766. */
  3767. async init(realm, eventManager) {
  3768. const channelHandle = await ChannelProxy.#createAndGetHandleInRealm(realm);
  3769. const sendMessageHandle = await ChannelProxy.#createSendMessageHandle(realm, channelHandle);
  3770. void this.#startListener(realm, channelHandle, eventManager);
  3771. return sendMessageHandle;
  3772. }
  3773. /** Gets a ChannelProxy from window and returns its handle. */
  3774. async startListenerFromWindow(realm, eventManager) {
  3775. try {
  3776. const channelHandle = await this.#getHandleFromWindow(realm);
  3777. void this.#startListener(realm, channelHandle, eventManager);
  3778. }
  3779. catch (error) {
  3780. this.#logger?.(log_js_1$c.LogType.debugError, error);
  3781. }
  3782. }
  3783. /**
  3784. * Evaluation string which creates a ChannelProxy object on the client side.
  3785. */
  3786. static #createChannelProxyEvalStr() {
  3787. const functionStr = String(() => {
  3788. const queue = [];
  3789. let queueNonEmptyResolver = null;
  3790. return {
  3791. /**
  3792. * Gets a promise, which is resolved as soon as a message occurs
  3793. * in the queue.
  3794. */
  3795. async getMessage() {
  3796. const onMessage = queue.length > 0
  3797. ? Promise.resolve()
  3798. : new Promise((resolve) => {
  3799. queueNonEmptyResolver = resolve;
  3800. });
  3801. await onMessage;
  3802. return queue.shift();
  3803. },
  3804. /**
  3805. * Adds a message to the queue.
  3806. * Resolves the pending promise if needed.
  3807. */
  3808. sendMessage(message) {
  3809. queue.push(message);
  3810. if (queueNonEmptyResolver !== null) {
  3811. queueNonEmptyResolver();
  3812. queueNonEmptyResolver = null;
  3813. }
  3814. },
  3815. };
  3816. });
  3817. return `(${functionStr})()`;
  3818. }
  3819. /** Creates a ChannelProxy in the given realm. */
  3820. static async #createAndGetHandleInRealm(realm) {
  3821. const createChannelHandleResult = await realm.cdpClient.sendCommand('Runtime.evaluate', {
  3822. expression: this.#createChannelProxyEvalStr(),
  3823. contextId: realm.executionContextId,
  3824. serializationOptions: {
  3825. serialization: "idOnly" /* Protocol.Runtime.SerializationOptionsSerialization.IdOnly */,
  3826. },
  3827. });
  3828. if (createChannelHandleResult.exceptionDetails ||
  3829. createChannelHandleResult.result.objectId === undefined) {
  3830. throw new Error(`Cannot create channel`);
  3831. }
  3832. return createChannelHandleResult.result.objectId;
  3833. }
  3834. /** Gets a handle to `sendMessage` delegate from the ChannelProxy handle. */
  3835. static async #createSendMessageHandle(realm, channelHandle) {
  3836. const sendMessageArgResult = await realm.cdpClient.sendCommand('Runtime.callFunctionOn', {
  3837. functionDeclaration: String((channelHandle) => {
  3838. return channelHandle.sendMessage;
  3839. }),
  3840. arguments: [{ objectId: channelHandle }],
  3841. executionContextId: realm.executionContextId,
  3842. serializationOptions: {
  3843. serialization: "idOnly" /* Protocol.Runtime.SerializationOptionsSerialization.IdOnly */,
  3844. },
  3845. });
  3846. // TODO: check for exceptionDetails.
  3847. return sendMessageArgResult.result.objectId;
  3848. }
  3849. /** Starts listening for the channel events of the provided ChannelProxy. */
  3850. async #startListener(realm, channelHandle, eventManager) {
  3851. // noinspection InfiniteLoopJS
  3852. for (;;) {
  3853. try {
  3854. const message = await realm.cdpClient.sendCommand('Runtime.callFunctionOn', {
  3855. functionDeclaration: String(async (channelHandle) => await channelHandle.getMessage()),
  3856. arguments: [
  3857. {
  3858. objectId: channelHandle,
  3859. },
  3860. ],
  3861. awaitPromise: true,
  3862. executionContextId: realm.executionContextId,
  3863. serializationOptions: {
  3864. serialization: "deep" /* Protocol.Runtime.SerializationOptionsSerialization.Deep */,
  3865. maxDepth: this.#properties.serializationOptions?.maxObjectDepth ??
  3866. undefined,
  3867. },
  3868. });
  3869. if (message.exceptionDetails) {
  3870. throw message.exceptionDetails;
  3871. }
  3872. for (const browsingContext of realm.associatedBrowsingContexts) {
  3873. eventManager.registerEvent({
  3874. type: 'event',
  3875. method: protocol_js_1$f.ChromiumBidi.Script.EventNames.Message,
  3876. params: {
  3877. channel: this.#properties.channel,
  3878. data: realm.cdpToBidiValue(message, this.#properties.ownership ?? "none" /* Script.ResultOwnership.None */),
  3879. source: realm.source,
  3880. },
  3881. }, browsingContext.id);
  3882. }
  3883. }
  3884. catch (error) {
  3885. // If an error is thrown, then the channel is permanently broken, so we
  3886. // exit the loop.
  3887. this.#logger?.(log_js_1$c.LogType.debugError, error);
  3888. break;
  3889. }
  3890. }
  3891. }
  3892. /**
  3893. * Returns a handle of ChannelProxy from window's property which was set there
  3894. * by `getEvalInWindowStr`. If window property is not set yet, sets a promise
  3895. * resolver to the window property, so that `getEvalInWindowStr` can resolve
  3896. * the promise later on with the channel.
  3897. * This is needed because `getEvalInWindowStr` can be called before or
  3898. * after this method.
  3899. */
  3900. async #getHandleFromWindow(realm) {
  3901. const channelHandleResult = await realm.cdpClient.sendCommand('Runtime.callFunctionOn', {
  3902. functionDeclaration: String((id) => {
  3903. const w = window;
  3904. if (w[id] === undefined) {
  3905. // The channelProxy is not created yet. Create a promise, put the
  3906. // resolver to window property and return the promise.
  3907. // `getEvalInWindowStr` will resolve the promise later.
  3908. return new Promise((resolve) => (w[id] = resolve));
  3909. }
  3910. // The channelProxy is already created by `getEvalInWindowStr` and
  3911. // is set into window property. Return it.
  3912. const channelProxy = w[id];
  3913. delete w[id];
  3914. return channelProxy;
  3915. }),
  3916. arguments: [{ value: this.#id }],
  3917. executionContextId: realm.executionContextId,
  3918. awaitPromise: true,
  3919. serializationOptions: {
  3920. serialization: "idOnly" /* Protocol.Runtime.SerializationOptionsSerialization.IdOnly */,
  3921. },
  3922. });
  3923. if (channelHandleResult.exceptionDetails !== undefined ||
  3924. channelHandleResult.result.objectId === undefined) {
  3925. throw new Error(`ChannelHandle not found in window["${this.#id}"]`);
  3926. }
  3927. return channelHandleResult.result.objectId;
  3928. }
  3929. /**
  3930. * String to be evaluated to create a ProxyChannel and put it to window.
  3931. * Returns the delegate `sendMessage`. Used to provide an argument for preload
  3932. * script. Does the following:
  3933. * 1. Creates a ChannelProxy.
  3934. * 2. Puts the ChannelProxy to window['${this.#id}'] or resolves the promise
  3935. * by calling delegate stored in window['${this.#id}'].
  3936. * This is needed because `#getHandleFromWindow` can be called before or
  3937. * after this method.
  3938. * 3. Returns the delegate `sendMessage` of the created ChannelProxy.
  3939. */
  3940. getEvalInWindowStr() {
  3941. const delegate = String((id, channelProxy) => {
  3942. const w = window;
  3943. if (w[id] === undefined) {
  3944. // `#getHandleFromWindow` is not initialized yet, and will get the
  3945. // channelProxy later.
  3946. w[id] = channelProxy;
  3947. }
  3948. else {
  3949. // `#getHandleFromWindow` is already set a delegate to window property
  3950. // and is waiting for it to be called with the channelProxy.
  3951. w[id](channelProxy);
  3952. delete w[id];
  3953. }
  3954. return channelProxy.sendMessage;
  3955. });
  3956. const channelProxyEval = ChannelProxy.#createChannelProxyEvalStr();
  3957. return `(${delegate})('${this.#id}',${channelProxyEval})`;
  3958. }
  3959. }
  3960. ChannelProxy$1.ChannelProxy = ChannelProxy;
  3961. /*
  3962. * Copyright 2023 Google LLC.
  3963. * Copyright (c) Microsoft Corporation.
  3964. *
  3965. * Licensed under the Apache License, Version 2.0 (the "License");
  3966. * you may not use this file except in compliance with the License.
  3967. * You may obtain a copy of the License at
  3968. *
  3969. * http://www.apache.org/licenses/LICENSE-2.0
  3970. *
  3971. * Unless required by applicable law or agreed to in writing, software
  3972. * distributed under the License is distributed on an "AS IS" BASIS,
  3973. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3974. * See the License for the specific language governing permissions and
  3975. * limitations under the License.
  3976. *
  3977. */
  3978. Object.defineProperty(PreloadScript$1, "__esModule", { value: true });
  3979. PreloadScript$1.PreloadScript = void 0;
  3980. const uuid_js_1$2 = uuid;
  3981. const ChannelProxy_js_1$1 = ChannelProxy$1;
  3982. /**
  3983. * BiDi IDs are generated by the server and are unique within contexts.
  3984. *
  3985. * CDP preload script IDs are generated by the client and are unique
  3986. * within sessions.
  3987. *
  3988. * The mapping between BiDi and CDP preload script IDs is 1:many.
  3989. * BiDi IDs are needed by the mapper to keep track of potential multiple CDP IDs
  3990. * in the client.
  3991. */
  3992. class PreloadScript {
  3993. /** BiDi ID, an automatically generated UUID. */
  3994. #id = (0, uuid_js_1$2.uuidv4)();
  3995. /** CDP preload scripts. */
  3996. #cdpPreloadScripts = [];
  3997. /** The script itself, in a format expected by the spec i.e. a function. */
  3998. #functionDeclaration;
  3999. /** Targets, in which the preload script is initialized. */
  4000. #targetIds = new Set();
  4001. /** Channels to be added as arguments to functionDeclaration. */
  4002. #channels;
  4003. /** The script sandbox / world name. */
  4004. #sandbox;
  4005. /** The browsing contexts to execute the preload scripts in, if any. */
  4006. #contexts;
  4007. get id() {
  4008. return this.#id;
  4009. }
  4010. get targetIds() {
  4011. return this.#targetIds;
  4012. }
  4013. constructor(params, logger) {
  4014. this.#channels =
  4015. params.arguments?.map((a) => new ChannelProxy_js_1$1.ChannelProxy(a.value, logger)) ?? [];
  4016. this.#functionDeclaration = params.functionDeclaration;
  4017. this.#sandbox = params.sandbox;
  4018. this.#contexts = params.contexts;
  4019. }
  4020. /** Channels of the preload script. */
  4021. get channels() {
  4022. return this.#channels;
  4023. }
  4024. /** Contexts of the preload script, if any */
  4025. get contexts() {
  4026. return this.#contexts;
  4027. }
  4028. /**
  4029. * String to be evaluated. Wraps user-provided function so that the following
  4030. * steps are run:
  4031. * 1. Create channels.
  4032. * 2. Store the created channels in window.
  4033. * 3. Call the user-provided function with channels as arguments.
  4034. */
  4035. #getEvaluateString() {
  4036. const channelsArgStr = `[${this.channels
  4037. .map((c) => c.getEvalInWindowStr())
  4038. .join(', ')}]`;
  4039. return `(()=>{(${this.#functionDeclaration})(...${channelsArgStr})})()`;
  4040. }
  4041. /**
  4042. * Adds the script to the given CDP targets by calling the
  4043. * `Page.addScriptToEvaluateOnNewDocument` command.
  4044. */
  4045. async initInTargets(cdpTargets, runImmediately) {
  4046. await Promise.all(Array.from(cdpTargets).map((cdpTarget) => this.initInTarget(cdpTarget, runImmediately)));
  4047. }
  4048. /**
  4049. * Adds the script to the given CDP target by calling the
  4050. * `Page.addScriptToEvaluateOnNewDocument` command.
  4051. */
  4052. async initInTarget(cdpTarget, runImmediately) {
  4053. const addCdpPreloadScriptResult = await cdpTarget.cdpClient.sendCommand('Page.addScriptToEvaluateOnNewDocument', {
  4054. source: this.#getEvaluateString(),
  4055. worldName: this.#sandbox,
  4056. runImmediately,
  4057. });
  4058. this.#cdpPreloadScripts.push({
  4059. target: cdpTarget,
  4060. preloadScriptId: addCdpPreloadScriptResult.identifier,
  4061. });
  4062. this.#targetIds.add(cdpTarget.id);
  4063. }
  4064. /**
  4065. * Removes this script from all CDP targets.
  4066. */
  4067. async remove() {
  4068. await Promise.all([
  4069. this.#cdpPreloadScripts.map(async (cdpPreloadScript) => {
  4070. const cdpTarget = cdpPreloadScript.target;
  4071. const cdpPreloadScriptId = cdpPreloadScript.preloadScriptId;
  4072. return await cdpTarget.cdpClient.sendCommand('Page.removeScriptToEvaluateOnNewDocument', {
  4073. identifier: cdpPreloadScriptId,
  4074. });
  4075. }),
  4076. ]);
  4077. }
  4078. /** Removes the provided cdp target from the list of cdp preload scripts. */
  4079. dispose(cdpTargetId) {
  4080. this.#cdpPreloadScripts = this.#cdpPreloadScripts.filter((cdpPreloadScript) => cdpPreloadScript.target?.id !== cdpTargetId);
  4081. this.#targetIds.delete(cdpTargetId);
  4082. }
  4083. }
  4084. PreloadScript$1.PreloadScript = PreloadScript;
  4085. /**
  4086. * Copyright 2023 Google LLC.
  4087. * Copyright (c) Microsoft Corporation.
  4088. *
  4089. * Licensed under the Apache License, Version 2.0 (the "License");
  4090. * you may not use this file except in compliance with the License.
  4091. * You may obtain a copy of the License at
  4092. *
  4093. * http://www.apache.org/licenses/LICENSE-2.0
  4094. *
  4095. * Unless required by applicable law or agreed to in writing, software
  4096. * distributed under the License is distributed on an "AS IS" BASIS,
  4097. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4098. * See the License for the specific language governing permissions and
  4099. * limitations under the License.
  4100. */
  4101. Object.defineProperty(ScriptProcessor$1, "__esModule", { value: true });
  4102. ScriptProcessor$1.ScriptProcessor = void 0;
  4103. const protocol_js_1$e = protocol;
  4104. const PreloadScript_js_1 = PreloadScript$1;
  4105. class ScriptProcessor {
  4106. #browsingContextStorage;
  4107. #realmStorage;
  4108. #preloadScriptStorage;
  4109. #logger;
  4110. constructor(browsingContextStorage, realmStorage, preloadScriptStorage, logger) {
  4111. this.#browsingContextStorage = browsingContextStorage;
  4112. this.#realmStorage = realmStorage;
  4113. this.#preloadScriptStorage = preloadScriptStorage;
  4114. this.#logger = logger;
  4115. }
  4116. async addPreloadScript(params) {
  4117. const contexts = this.#browsingContextStorage.verifyTopLevelContextsList(params.contexts);
  4118. const preloadScript = new PreloadScript_js_1.PreloadScript(params, this.#logger);
  4119. this.#preloadScriptStorage.add(preloadScript);
  4120. const cdpTargets = contexts.size === 0
  4121. ? new Set(this.#browsingContextStorage
  4122. .getTopLevelContexts()
  4123. .map((context) => context.cdpTarget))
  4124. : new Set([...contexts.values()].map((context) => context.cdpTarget));
  4125. await preloadScript.initInTargets(cdpTargets, false);
  4126. return {
  4127. script: preloadScript.id,
  4128. };
  4129. }
  4130. async removePreloadScript(params) {
  4131. const { script: id } = params;
  4132. const scripts = this.#preloadScriptStorage.find({ id });
  4133. if (scripts.length === 0) {
  4134. throw new protocol_js_1$e.NoSuchScriptException(`No preload script with id '${id}'`);
  4135. }
  4136. await Promise.all(scripts.map((script) => script.remove()));
  4137. this.#preloadScriptStorage.remove({ id });
  4138. return {};
  4139. }
  4140. async callFunction(params) {
  4141. const realm = await this.#getRealm(params.target);
  4142. return await realm.callFunction(params.functionDeclaration, params.awaitPromise, params.this, params.arguments, params.resultOwnership, params.serializationOptions, params.userActivation);
  4143. }
  4144. async evaluate(params) {
  4145. const realm = await this.#getRealm(params.target);
  4146. return await realm.evaluate(params.expression, params.awaitPromise, params.resultOwnership, params.serializationOptions, params.userActivation);
  4147. }
  4148. async disown(params) {
  4149. const realm = await this.#getRealm(params.target);
  4150. await Promise.all(params.handles.map(async (handle) => await realm.disown(handle)));
  4151. return {};
  4152. }
  4153. getRealms(params) {
  4154. if (params.context !== undefined) {
  4155. // Make sure the context is known.
  4156. this.#browsingContextStorage.getContext(params.context);
  4157. }
  4158. const realms = this.#realmStorage
  4159. .findRealms({
  4160. browsingContextId: params.context,
  4161. type: params.type,
  4162. })
  4163. .map((realm) => realm.realmInfo);
  4164. return { realms };
  4165. }
  4166. async #getRealm(target) {
  4167. if ('context' in target) {
  4168. const context = this.#browsingContextStorage.getContext(target.context);
  4169. return await context.getOrCreateSandbox(target.sandbox);
  4170. }
  4171. return this.#realmStorage.getRealm({
  4172. realmId: target.realm,
  4173. });
  4174. }
  4175. }
  4176. ScriptProcessor$1.ScriptProcessor = ScriptProcessor;
  4177. var SessionProcessor$1 = {};
  4178. /**
  4179. * Copyright 2023 Google LLC.
  4180. * Copyright (c) Microsoft Corporation.
  4181. *
  4182. * Licensed under the Apache License, Version 2.0 (the "License");
  4183. * you may not use this file except in compliance with the License.
  4184. * You may obtain a copy of the License at
  4185. *
  4186. * http://www.apache.org/licenses/LICENSE-2.0
  4187. *
  4188. * Unless required by applicable law or agreed to in writing, software
  4189. * distributed under the License is distributed on an "AS IS" BASIS,
  4190. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4191. * See the License for the specific language governing permissions and
  4192. * limitations under the License.
  4193. */
  4194. Object.defineProperty(SessionProcessor$1, "__esModule", { value: true });
  4195. SessionProcessor$1.SessionProcessor = void 0;
  4196. class SessionProcessor {
  4197. #eventManager;
  4198. #browserCdpClient;
  4199. constructor(eventManager, browserCdpClient) {
  4200. this.#eventManager = eventManager;
  4201. this.#browserCdpClient = browserCdpClient;
  4202. }
  4203. status() {
  4204. return { ready: false, message: 'already connected' };
  4205. }
  4206. async create(_params) {
  4207. // Since mapper exists, there is a session already.
  4208. // Still the mapper can handle capabilities for us.
  4209. // Currently, only Puppeteer calls here but, eventually, every client
  4210. // should delegrate capability processing here.
  4211. const version = await this.#browserCdpClient.sendCommand('Browser.getVersion');
  4212. return {
  4213. sessionId: 'unknown',
  4214. capabilities: {
  4215. acceptInsecureCerts: false,
  4216. browserName: version.product,
  4217. browserVersion: version.revision,
  4218. platformName: '',
  4219. setWindowRect: false,
  4220. webSocketUrl: '',
  4221. userAgent: version.userAgent,
  4222. },
  4223. };
  4224. }
  4225. async subscribe(params, channel = null) {
  4226. await this.#eventManager.subscribe(params.events, params.contexts ?? [null], channel);
  4227. return {};
  4228. }
  4229. async unsubscribe(params, channel = null) {
  4230. await this.#eventManager.unsubscribe(params.events, params.contexts ?? [null], channel);
  4231. return {};
  4232. }
  4233. }
  4234. SessionProcessor$1.SessionProcessor = SessionProcessor;
  4235. var StorageProcessor$1 = {};
  4236. Object.defineProperty(StorageProcessor$1, "__esModule", { value: true });
  4237. StorageProcessor$1.StorageProcessor = void 0;
  4238. const protocol_js_1$d = protocol;
  4239. const assert_js_1$3 = assert$1;
  4240. const log_js_1$b = log$1;
  4241. const NetworkProcessor_js_1$1 = NetworkProcessor$1;
  4242. const NetworkUtils_js_1$2 = NetworkUtils;
  4243. /**
  4244. * Responsible for handling the `storage` domain.
  4245. */
  4246. class StorageProcessor {
  4247. #browserCdpClient;
  4248. #browsingContextStorage;
  4249. #logger;
  4250. constructor(browserCdpClient, browsingContextStorage, logger) {
  4251. this.#browsingContextStorage = browsingContextStorage;
  4252. this.#browserCdpClient = browserCdpClient;
  4253. this.#logger = logger;
  4254. }
  4255. async deleteCookies(params) {
  4256. const partitionKey = this.#expandStoragePartitionSpec(params.partition);
  4257. let cdpResponse;
  4258. try {
  4259. cdpResponse = await this.#browserCdpClient.sendCommand('Storage.getCookies', {
  4260. browserContextId: this.#getCdpBrowserContextId(partitionKey),
  4261. });
  4262. }
  4263. catch (err) {
  4264. if (this.#isNoSuchUserContextError(err)) {
  4265. // If the user context is not found, special error is thrown.
  4266. throw new protocol_js_1$d.NoSuchUserContextException(err.message);
  4267. }
  4268. throw err;
  4269. }
  4270. const cdpCookiesToDelete = cdpResponse.cookies
  4271. .filter(
  4272. // CDP's partition key is the source origin. If the request specifies the
  4273. // `sourceOrigin` partition key, only cookies with the requested source origin
  4274. // are returned.
  4275. (c) => partitionKey.sourceOrigin === undefined ||
  4276. c.partitionKey === partitionKey.sourceOrigin)
  4277. .filter((cdpCookie) => {
  4278. const bidiCookie = (0, NetworkUtils_js_1$2.cdpToBiDiCookie)(cdpCookie);
  4279. return this.#matchCookie(bidiCookie, params.filter);
  4280. })
  4281. .map((cookie) => ({
  4282. ...cookie,
  4283. // Set expiry to pass date to delete the cookie.
  4284. expires: 1,
  4285. }));
  4286. await this.#browserCdpClient.sendCommand('Storage.setCookies', {
  4287. cookies: cdpCookiesToDelete,
  4288. browserContextId: this.#getCdpBrowserContextId(partitionKey),
  4289. });
  4290. return {
  4291. partitionKey,
  4292. };
  4293. }
  4294. async getCookies(params) {
  4295. const partitionKey = this.#expandStoragePartitionSpec(params.partition);
  4296. let cdpResponse;
  4297. try {
  4298. cdpResponse = await this.#browserCdpClient.sendCommand('Storage.getCookies', {
  4299. browserContextId: this.#getCdpBrowserContextId(partitionKey),
  4300. });
  4301. }
  4302. catch (err) {
  4303. if (this.#isNoSuchUserContextError(err)) {
  4304. // If the user context is not found, special error is thrown.
  4305. throw new protocol_js_1$d.NoSuchUserContextException(err.message);
  4306. }
  4307. throw err;
  4308. }
  4309. const filteredBiDiCookies = cdpResponse.cookies
  4310. .filter(
  4311. // CDP's partition key is the source origin. If the request specifies the
  4312. // `sourceOrigin` partition key, only cookies with the requested source origin
  4313. // are returned.
  4314. (c) => partitionKey.sourceOrigin === undefined ||
  4315. c.partitionKey === partitionKey.sourceOrigin)
  4316. .map((c) => (0, NetworkUtils_js_1$2.cdpToBiDiCookie)(c))
  4317. .filter((c) => this.#matchCookie(c, params.filter));
  4318. return {
  4319. cookies: filteredBiDiCookies,
  4320. partitionKey,
  4321. };
  4322. }
  4323. async setCookie(params) {
  4324. const partitionKey = this.#expandStoragePartitionSpec(params.partition);
  4325. const cdpCookie = (0, NetworkUtils_js_1$2.bidiToCdpCookie)(params, partitionKey);
  4326. try {
  4327. await this.#browserCdpClient.sendCommand('Storage.setCookies', {
  4328. cookies: [cdpCookie],
  4329. browserContextId: this.#getCdpBrowserContextId(partitionKey),
  4330. });
  4331. }
  4332. catch (err) {
  4333. if (this.#isNoSuchUserContextError(err)) {
  4334. // If the user context is not found, special error is thrown.
  4335. throw new protocol_js_1$d.NoSuchUserContextException(err.message);
  4336. }
  4337. this.#logger?.(log_js_1$b.LogType.debugError, err);
  4338. throw new protocol_js_1$d.UnableToSetCookieException(err.toString());
  4339. }
  4340. return {
  4341. partitionKey,
  4342. };
  4343. }
  4344. #isNoSuchUserContextError(err) {
  4345. // Heuristic to detect if the user context is not found.
  4346. // See https://source.chromium.org/chromium/chromium/src/+/main:content/browser/devtools/protocol/browser_handler.cc;drc=a56154dd81e4679712422ac6eed2c9581cb51ab0;l=314
  4347. return err.message?.startsWith('Failed to find browser context for id');
  4348. }
  4349. #getCdpBrowserContextId(partitionKey) {
  4350. return partitionKey.userContext === 'default'
  4351. ? undefined
  4352. : partitionKey.userContext;
  4353. }
  4354. #expandStoragePartitionSpecByBrowsingContext(descriptor) {
  4355. const browsingContextId = descriptor.context;
  4356. const browsingContext = this.#browsingContextStorage.getContext(browsingContextId);
  4357. // https://w3c.github.io/webdriver-bidi/#associated-storage-partition.
  4358. // Each browsing context also has an associated storage partition, which is the
  4359. // storage partition it uses to persist data. In Chromium it's a `BrowserContext`
  4360. // which maps to BiDi `UserContext`.
  4361. return {
  4362. userContext: browsingContext.userContext,
  4363. };
  4364. }
  4365. #expandStoragePartitionSpecByStorageKey(descriptor) {
  4366. const unsupportedPartitionKeys = new Map();
  4367. let sourceOrigin = descriptor.sourceOrigin;
  4368. if (sourceOrigin !== undefined) {
  4369. const url = NetworkProcessor_js_1$1.NetworkProcessor.parseUrlString(sourceOrigin);
  4370. if (url.origin === 'null') {
  4371. // Origin `null` is a special case for local pages.
  4372. sourceOrigin = url.origin;
  4373. }
  4374. else {
  4375. // Port is not supported in CDP Cookie's `partitionKey`, so it should be stripped
  4376. // from the requested source origin.
  4377. sourceOrigin = `${url.protocol}//${url.hostname}`;
  4378. }
  4379. }
  4380. for (const [key, value] of Object.entries(descriptor)) {
  4381. if (key !== undefined &&
  4382. value !== undefined &&
  4383. !['type', 'sourceOrigin', 'userContext'].includes(key)) {
  4384. unsupportedPartitionKeys.set(key, value);
  4385. }
  4386. }
  4387. if (unsupportedPartitionKeys.size > 0) {
  4388. this.#logger?.(log_js_1$b.LogType.debugInfo, `Unsupported partition keys: ${JSON.stringify(Object.fromEntries(unsupportedPartitionKeys))}`);
  4389. }
  4390. // Set `userContext` to `default` if not provided, as it's required in Chromium.
  4391. const userContext = descriptor.userContext ?? 'default';
  4392. return {
  4393. userContext,
  4394. ...(sourceOrigin === undefined ? {} : { sourceOrigin }),
  4395. };
  4396. }
  4397. #expandStoragePartitionSpec(partitionSpec) {
  4398. if (partitionSpec === undefined) {
  4399. // `userContext` is required in Chromium.
  4400. return { userContext: 'default' };
  4401. }
  4402. if (partitionSpec.type === 'context') {
  4403. return this.#expandStoragePartitionSpecByBrowsingContext(partitionSpec);
  4404. }
  4405. (0, assert_js_1$3.assert)(partitionSpec.type === 'storageKey', 'Unknown partition type');
  4406. // Partition spec is a storage partition.
  4407. // Let partition key be partition spec.
  4408. return this.#expandStoragePartitionSpecByStorageKey(partitionSpec);
  4409. }
  4410. #matchCookie(cookie, filter) {
  4411. if (filter === undefined) {
  4412. return true;
  4413. }
  4414. return ((filter.domain === undefined || filter.domain === cookie.domain) &&
  4415. (filter.name === undefined || filter.name === cookie.name) &&
  4416. // `value` contains fields `type` and `value`.
  4417. (filter.value === undefined ||
  4418. (0, NetworkUtils_js_1$2.deserializeByteValue)(filter.value) ===
  4419. (0, NetworkUtils_js_1$2.deserializeByteValue)(cookie.value)) &&
  4420. (filter.path === undefined || filter.path === cookie.path) &&
  4421. (filter.size === undefined || filter.size === cookie.size) &&
  4422. (filter.httpOnly === undefined || filter.httpOnly === cookie.httpOnly) &&
  4423. (filter.secure === undefined || filter.secure === cookie.secure) &&
  4424. (filter.sameSite === undefined || filter.sameSite === cookie.sameSite) &&
  4425. (filter.expiry === undefined || filter.expiry === cookie.expiry));
  4426. }
  4427. }
  4428. StorageProcessor$1.StorageProcessor = StorageProcessor;
  4429. var OutgoingMessage$1 = {};
  4430. /**
  4431. * Copyright 2021 Google LLC.
  4432. * Copyright (c) Microsoft Corporation.
  4433. *
  4434. * Licensed under the Apache License, Version 2.0 (the "License");
  4435. * you may not use this file except in compliance with the License.
  4436. * You may obtain a copy of the License at
  4437. *
  4438. * http://www.apache.org/licenses/LICENSE-2.0
  4439. *
  4440. * Unless required by applicable law or agreed to in writing, software
  4441. * distributed under the License is distributed on an "AS IS" BASIS,
  4442. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4443. * See the License for the specific language governing permissions and
  4444. * limitations under the License.
  4445. */
  4446. Object.defineProperty(OutgoingMessage$1, "__esModule", { value: true });
  4447. OutgoingMessage$1.OutgoingMessage = void 0;
  4448. class OutgoingMessage {
  4449. #message;
  4450. #channel;
  4451. constructor(message, channel = null) {
  4452. this.#message = message;
  4453. this.#channel = channel;
  4454. }
  4455. static createFromPromise(messagePromise, channel) {
  4456. return messagePromise.then((message) => {
  4457. if (message.kind === 'success') {
  4458. return {
  4459. kind: 'success',
  4460. value: new OutgoingMessage(message.value, channel),
  4461. };
  4462. }
  4463. return message;
  4464. });
  4465. }
  4466. static createResolved(message, channel) {
  4467. return Promise.resolve({
  4468. kind: 'success',
  4469. value: new OutgoingMessage(message, channel),
  4470. });
  4471. }
  4472. get message() {
  4473. return this.#message;
  4474. }
  4475. get channel() {
  4476. return this.#channel;
  4477. }
  4478. }
  4479. OutgoingMessage$1.OutgoingMessage = OutgoingMessage;
  4480. /**
  4481. * Copyright 2021 Google LLC.
  4482. * Copyright (c) Microsoft Corporation.
  4483. *
  4484. * Licensed under the Apache License, Version 2.0 (the "License");
  4485. * you may not use this file except in compliance with the License.
  4486. * You may obtain a copy of the License at
  4487. *
  4488. * http://www.apache.org/licenses/LICENSE-2.0
  4489. *
  4490. * Unless required by applicable law or agreed to in writing, software
  4491. * distributed under the License is distributed on an "AS IS" BASIS,
  4492. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4493. * See the License for the specific language governing permissions and
  4494. * limitations under the License.
  4495. */
  4496. Object.defineProperty(CommandProcessor$1, "__esModule", { value: true });
  4497. CommandProcessor$1.CommandProcessor = void 0;
  4498. const protocol_js_1$c = protocol;
  4499. const EventEmitter_js_1$3 = EventEmitter$1;
  4500. const log_js_1$a = log$1;
  4501. const BidiNoOpParser_js_1 = BidiNoOpParser$1;
  4502. const BrowserProcessor_js_1 = BrowserProcessor$1;
  4503. const CdpProcessor_js_1 = CdpProcessor$1;
  4504. const BrowsingContextProcessor_js_1 = BrowsingContextProcessor$1;
  4505. const InputProcessor_js_1 = InputProcessor$1;
  4506. const NetworkProcessor_js_1 = NetworkProcessor$1;
  4507. const PermissionsProcessor_js_1 = PermissionsProcessor$1;
  4508. const ScriptProcessor_js_1 = ScriptProcessor$1;
  4509. const SessionProcessor_js_1 = SessionProcessor$1;
  4510. const StorageProcessor_js_1 = StorageProcessor$1;
  4511. const OutgoingMessage_js_1$1 = OutgoingMessage$1;
  4512. class CommandProcessor extends EventEmitter_js_1$3.EventEmitter {
  4513. // keep-sorted start
  4514. #browserProcessor;
  4515. #browsingContextProcessor;
  4516. #cdpProcessor;
  4517. #inputProcessor;
  4518. #networkProcessor;
  4519. #permissionsProcessor;
  4520. #scriptProcessor;
  4521. #sessionProcessor;
  4522. #storageProcessor;
  4523. // keep-sorted end
  4524. #parser;
  4525. #logger;
  4526. constructor(cdpConnection, browserCdpClient, eventManager, browsingContextStorage, realmStorage, preloadScriptStorage, networkStorage, parser = new BidiNoOpParser_js_1.BidiNoOpParser(), logger) {
  4527. super();
  4528. this.#parser = parser;
  4529. this.#logger = logger;
  4530. // keep-sorted start block=yes
  4531. this.#browserProcessor = new BrowserProcessor_js_1.BrowserProcessor(browserCdpClient);
  4532. this.#browsingContextProcessor = new BrowsingContextProcessor_js_1.BrowsingContextProcessor(browserCdpClient, browsingContextStorage);
  4533. this.#cdpProcessor = new CdpProcessor_js_1.CdpProcessor(browsingContextStorage, realmStorage, cdpConnection, browserCdpClient);
  4534. this.#inputProcessor = new InputProcessor_js_1.InputProcessor(browsingContextStorage, realmStorage);
  4535. this.#networkProcessor = new NetworkProcessor_js_1.NetworkProcessor(browsingContextStorage, networkStorage);
  4536. this.#permissionsProcessor = new PermissionsProcessor_js_1.PermissionsProcessor(browserCdpClient);
  4537. this.#scriptProcessor = new ScriptProcessor_js_1.ScriptProcessor(browsingContextStorage, realmStorage, preloadScriptStorage, logger);
  4538. this.#sessionProcessor = new SessionProcessor_js_1.SessionProcessor(eventManager, browserCdpClient);
  4539. this.#storageProcessor = new StorageProcessor_js_1.StorageProcessor(browserCdpClient, browsingContextStorage, logger);
  4540. // keep-sorted end
  4541. }
  4542. async #processCommand(command) {
  4543. switch (command.method) {
  4544. case 'session.end':
  4545. // TODO: Implement.
  4546. break;
  4547. // Browser domain
  4548. // keep-sorted start block=yes
  4549. case 'browser.close':
  4550. return this.#browserProcessor.close();
  4551. case 'browser.createUserContext':
  4552. return await this.#browserProcessor.createUserContext(command.params);
  4553. case 'browser.getUserContexts':
  4554. return await this.#browserProcessor.getUserContexts();
  4555. case 'browser.removeUserContext':
  4556. return await this.#browserProcessor.removeUserContext(this.#parser.parseRemoveUserContextParams(command.params));
  4557. // keep-sorted end
  4558. // Browsing Context domain
  4559. // keep-sorted start block=yes
  4560. case 'browsingContext.activate':
  4561. return await this.#browsingContextProcessor.activate(this.#parser.parseActivateParams(command.params));
  4562. case 'browsingContext.captureScreenshot':
  4563. return await this.#browsingContextProcessor.captureScreenshot(this.#parser.parseCaptureScreenshotParams(command.params));
  4564. case 'browsingContext.close':
  4565. return await this.#browsingContextProcessor.close(this.#parser.parseCloseParams(command.params));
  4566. case 'browsingContext.create':
  4567. return await this.#browsingContextProcessor.create(this.#parser.parseCreateParams(command.params));
  4568. case 'browsingContext.getTree':
  4569. return this.#browsingContextProcessor.getTree(this.#parser.parseGetTreeParams(command.params));
  4570. case 'browsingContext.handleUserPrompt':
  4571. return await this.#browsingContextProcessor.handleUserPrompt(this.#parser.parseHandleUserPromptParams(command.params));
  4572. case 'browsingContext.locateNodes':
  4573. return await this.#browsingContextProcessor.locateNodes(this.#parser.parseLocateNodesParams(command.params));
  4574. case 'browsingContext.navigate':
  4575. return await this.#browsingContextProcessor.navigate(this.#parser.parseNavigateParams(command.params));
  4576. case 'browsingContext.print':
  4577. return await this.#browsingContextProcessor.print(this.#parser.parsePrintParams(command.params));
  4578. case 'browsingContext.reload':
  4579. return await this.#browsingContextProcessor.reload(this.#parser.parseReloadParams(command.params));
  4580. case 'browsingContext.setViewport':
  4581. return await this.#browsingContextProcessor.setViewport(this.#parser.parseSetViewportParams(command.params));
  4582. case 'browsingContext.traverseHistory':
  4583. return await this.#browsingContextProcessor.traverseHistory(this.#parser.parseTraverseHistoryParams(command.params));
  4584. // keep-sorted end
  4585. // CDP domain
  4586. // keep-sorted start block=yes
  4587. case 'cdp.getSession':
  4588. return this.#cdpProcessor.getSession(this.#parser.parseGetSessionParams(command.params));
  4589. case 'cdp.resolveRealm':
  4590. return this.#cdpProcessor.resolveRealm(this.#parser.parseResolveRealmParams(command.params));
  4591. case 'cdp.sendCommand':
  4592. return await this.#cdpProcessor.sendCommand(this.#parser.parseSendCommandParams(command.params));
  4593. // keep-sorted end
  4594. // Input domain
  4595. // keep-sorted start block=yes
  4596. case 'input.performActions':
  4597. return await this.#inputProcessor.performActions(this.#parser.parsePerformActionsParams(command.params));
  4598. case 'input.releaseActions':
  4599. return await this.#inputProcessor.releaseActions(this.#parser.parseReleaseActionsParams(command.params));
  4600. case 'input.setFiles':
  4601. return await this.#inputProcessor.setFiles(this.#parser.parseSetFilesParams(command.params));
  4602. // keep-sorted end
  4603. // Network domain
  4604. // keep-sorted start block=yes
  4605. case 'network.addIntercept':
  4606. return await this.#networkProcessor.addIntercept(this.#parser.parseAddInterceptParams(command.params));
  4607. case 'network.continueRequest':
  4608. return await this.#networkProcessor.continueRequest(this.#parser.parseContinueRequestParams(command.params));
  4609. case 'network.continueResponse':
  4610. return await this.#networkProcessor.continueResponse(this.#parser.parseContinueResponseParams(command.params));
  4611. case 'network.continueWithAuth':
  4612. return await this.#networkProcessor.continueWithAuth(this.#parser.parseContinueWithAuthParams(command.params));
  4613. case 'network.failRequest':
  4614. return await this.#networkProcessor.failRequest(this.#parser.parseFailRequestParams(command.params));
  4615. case 'network.provideResponse':
  4616. return await this.#networkProcessor.provideResponse(this.#parser.parseProvideResponseParams(command.params));
  4617. case 'network.removeIntercept':
  4618. return await this.#networkProcessor.removeIntercept(this.#parser.parseRemoveInterceptParams(command.params));
  4619. // keep-sorted end
  4620. // Permissions domain
  4621. // keep-sorted start block=yes
  4622. case 'permissions.setPermission':
  4623. return await this.#permissionsProcessor.setPermissions(this.#parser.parseSetPermissionsParams(command.params));
  4624. // keep-sorted end
  4625. // Script domain
  4626. // keep-sorted start block=yes
  4627. case 'script.addPreloadScript':
  4628. return await this.#scriptProcessor.addPreloadScript(this.#parser.parseAddPreloadScriptParams(command.params));
  4629. case 'script.callFunction':
  4630. return await this.#scriptProcessor.callFunction(this.#parser.parseCallFunctionParams(this.#processTargetParams(command.params)));
  4631. case 'script.disown':
  4632. return await this.#scriptProcessor.disown(this.#parser.parseDisownParams(this.#processTargetParams(command.params)));
  4633. case 'script.evaluate':
  4634. return await this.#scriptProcessor.evaluate(this.#parser.parseEvaluateParams(this.#processTargetParams(command.params)));
  4635. case 'script.getRealms':
  4636. return this.#scriptProcessor.getRealms(this.#parser.parseGetRealmsParams(command.params));
  4637. case 'script.removePreloadScript':
  4638. return await this.#scriptProcessor.removePreloadScript(this.#parser.parseRemovePreloadScriptParams(command.params));
  4639. // keep-sorted end
  4640. // Session domain
  4641. // keep-sorted start block=yes
  4642. case 'session.new':
  4643. return await this.#sessionProcessor.create(command.params);
  4644. case 'session.status':
  4645. return this.#sessionProcessor.status();
  4646. case 'session.subscribe':
  4647. return await this.#sessionProcessor.subscribe(this.#parser.parseSubscribeParams(command.params), command.channel);
  4648. case 'session.unsubscribe':
  4649. return await this.#sessionProcessor.unsubscribe(this.#parser.parseSubscribeParams(command.params), command.channel);
  4650. // keep-sorted end
  4651. // Storage domain
  4652. // keep-sorted start block=yes
  4653. case 'storage.deleteCookies':
  4654. return await this.#storageProcessor.deleteCookies(this.#parser.parseDeleteCookiesParams(command.params));
  4655. case 'storage.getCookies':
  4656. return await this.#storageProcessor.getCookies(this.#parser.parseGetCookiesParams(command.params));
  4657. case 'storage.setCookie':
  4658. return await this.#storageProcessor.setCookie(this.#parser.parseSetCookieParams(command.params));
  4659. // keep-sorted end
  4660. }
  4661. // Intentionally kept outside the switch statement to ensure that
  4662. // ESLint @typescript-eslint/switch-exhaustiveness-check triggers if a new
  4663. // command is added.
  4664. throw new protocol_js_1$c.UnknownCommandException(`Unknown command '${command.method}'.`);
  4665. }
  4666. // Workaround for as zod.union always take the first schema
  4667. // https://github.com/w3c/webdriver-bidi/issues/635
  4668. #processTargetParams(params) {
  4669. if (typeof params === 'object' &&
  4670. params &&
  4671. 'target' in params &&
  4672. typeof params.target === 'object' &&
  4673. params.target &&
  4674. 'context' in params.target) {
  4675. delete params.target['realm'];
  4676. }
  4677. return params;
  4678. }
  4679. async processCommand(command) {
  4680. try {
  4681. const result = await this.#processCommand(command);
  4682. const response = {
  4683. type: 'success',
  4684. id: command.id,
  4685. result,
  4686. };
  4687. this.emit("response" /* CommandProcessorEvents.Response */, {
  4688. message: OutgoingMessage_js_1$1.OutgoingMessage.createResolved(response, command.channel),
  4689. event: command.method,
  4690. });
  4691. }
  4692. catch (e) {
  4693. if (e instanceof protocol_js_1$c.Exception) {
  4694. this.emit("response" /* CommandProcessorEvents.Response */, {
  4695. message: OutgoingMessage_js_1$1.OutgoingMessage.createResolved(e.toErrorResponse(command.id), command.channel),
  4696. event: command.method,
  4697. });
  4698. }
  4699. else {
  4700. const error = e;
  4701. this.#logger?.(log_js_1$a.LogType.bidi, error);
  4702. this.emit("response" /* CommandProcessorEvents.Response */, {
  4703. message: OutgoingMessage_js_1$1.OutgoingMessage.createResolved(new protocol_js_1$c.UnknownErrorException(error.message, error.stack).toErrorResponse(command.id), command.channel),
  4704. event: command.method,
  4705. });
  4706. }
  4707. }
  4708. }
  4709. }
  4710. CommandProcessor$1.CommandProcessor = CommandProcessor;
  4711. var CdpTargetManager$1 = {};
  4712. var BrowsingContextImpl$1 = {};
  4713. var Deferred$1 = {};
  4714. /**
  4715. * Copyright 2022 Google LLC.
  4716. * Copyright (c) Microsoft Corporation.
  4717. *
  4718. * Licensed under the Apache License, Version 2.0 (the "License");
  4719. * you may not use this file except in compliance with the License.
  4720. * You may obtain a copy of the License at
  4721. *
  4722. * http://www.apache.org/licenses/LICENSE-2.0
  4723. *
  4724. * Unless required by applicable law or agreed to in writing, software
  4725. * distributed under the License is distributed on an "AS IS" BASIS,
  4726. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4727. * See the License for the specific language governing permissions and
  4728. * limitations under the License.
  4729. */
  4730. Object.defineProperty(Deferred$1, "__esModule", { value: true });
  4731. Deferred$1.Deferred = void 0;
  4732. class Deferred {
  4733. #isFinished = false;
  4734. #promise;
  4735. #resolve;
  4736. #reject;
  4737. get isFinished() {
  4738. return this.#isFinished;
  4739. }
  4740. constructor() {
  4741. this.#promise = new Promise((resolve, reject) => {
  4742. this.#resolve = resolve;
  4743. this.#reject = reject;
  4744. });
  4745. // Needed to avoid `Uncaught (in promise)`. The promises returned by `then`
  4746. // and `catch` will be rejected anyway.
  4747. this.#promise.catch((_error) => {
  4748. // Intentionally empty.
  4749. });
  4750. }
  4751. then(onFulfilled, onRejected) {
  4752. return this.#promise.then(onFulfilled, onRejected);
  4753. }
  4754. catch(onRejected) {
  4755. return this.#promise.catch(onRejected);
  4756. }
  4757. resolve(value) {
  4758. if (!this.#isFinished) {
  4759. this.#isFinished = true;
  4760. this.#resolve(value);
  4761. }
  4762. }
  4763. reject(reason) {
  4764. if (!this.#isFinished) {
  4765. this.#isFinished = true;
  4766. this.#reject(reason);
  4767. }
  4768. }
  4769. finally(onFinally) {
  4770. return this.#promise.finally(onFinally);
  4771. }
  4772. [Symbol.toStringTag] = 'Promise';
  4773. }
  4774. Deferred$1.Deferred = Deferred;
  4775. var unitConversions = {};
  4776. /**
  4777. * Copyright 2023 Google LLC.
  4778. * Copyright (c) Microsoft Corporation.
  4779. *
  4780. * Licensed under the Apache License, Version 2.0 (the "License");
  4781. * you may not use this file except in compliance with the License.
  4782. * You may obtain a copy of the License at
  4783. *
  4784. * http://www.apache.org/licenses/LICENSE-2.0
  4785. *
  4786. * Unless required by applicable law or agreed to in writing, software
  4787. * distributed under the License is distributed on an "AS IS" BASIS,
  4788. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4789. * See the License for the specific language governing permissions and
  4790. * limitations under the License.
  4791. */
  4792. Object.defineProperty(unitConversions, "__esModule", { value: true });
  4793. unitConversions.inchesFromCm = void 0;
  4794. /** @return Given an input in cm, convert it to inches. */
  4795. function inchesFromCm(cm) {
  4796. return cm / 2.54;
  4797. }
  4798. unitConversions.inchesFromCm = inchesFromCm;
  4799. var WindowRealm$1 = {};
  4800. var Realm$1 = {};
  4801. Object.defineProperty(Realm$1, "__esModule", { value: true });
  4802. Realm$1.Realm = void 0;
  4803. const protocol_js_1$b = protocol;
  4804. const log_js_1$9 = log$1;
  4805. const uuid_js_1$1 = uuid;
  4806. const ChannelProxy_js_1 = ChannelProxy$1;
  4807. class Realm {
  4808. #cdpClient;
  4809. #eventManager;
  4810. #executionContextId;
  4811. #logger;
  4812. #origin;
  4813. #realmId;
  4814. #realmStorage;
  4815. constructor(cdpClient, eventManager, executionContextId, logger, origin, realmId, realmStorage) {
  4816. this.#cdpClient = cdpClient;
  4817. this.#eventManager = eventManager;
  4818. this.#executionContextId = executionContextId;
  4819. this.#logger = logger;
  4820. this.#origin = origin;
  4821. this.#realmId = realmId;
  4822. this.#realmStorage = realmStorage;
  4823. this.#realmStorage.addRealm(this);
  4824. }
  4825. cdpToBidiValue(cdpValue, resultOwnership) {
  4826. const bidiValue = this.serializeForBiDi(cdpValue.result.deepSerializedValue, new Map());
  4827. if (cdpValue.result.objectId) {
  4828. const objectId = cdpValue.result.objectId;
  4829. if (resultOwnership === "root" /* Script.ResultOwnership.Root */) {
  4830. // Extend BiDi value with `handle` based on required `resultOwnership`
  4831. // and CDP response but not on the actual BiDi type.
  4832. bidiValue.handle = objectId;
  4833. // Remember all the handles sent to client.
  4834. this.#realmStorage.knownHandlesToRealmMap.set(objectId, this.realmId);
  4835. }
  4836. else {
  4837. // No need to await for the object to be released.
  4838. void this.#releaseObject(objectId).catch((error) => this.#logger?.(log_js_1$9.LogType.debugError, error));
  4839. }
  4840. }
  4841. return bidiValue;
  4842. }
  4843. /**
  4844. * Relies on the CDP to implement proper BiDi serialization, except:
  4845. * * CDP integer property `backendNodeId` is replaced with `sharedId` of
  4846. * `{documentId}_element_{backendNodeId}`;
  4847. * * CDP integer property `weakLocalObjectReference` is replaced with UUID `internalId`
  4848. * using unique-per serialization `internalIdMap`.
  4849. * * CDP type `platformobject` is replaced with `object`.
  4850. * @param deepSerializedValue - CDP value to be converted to BiDi.
  4851. * @param internalIdMap - Map from CDP integer `weakLocalObjectReference` to BiDi UUID
  4852. * `internalId`.
  4853. */
  4854. serializeForBiDi(deepSerializedValue, internalIdMap) {
  4855. if (Object.hasOwn(deepSerializedValue, 'weakLocalObjectReference')) {
  4856. const weakLocalObjectReference = deepSerializedValue.weakLocalObjectReference;
  4857. if (!internalIdMap.has(weakLocalObjectReference)) {
  4858. internalIdMap.set(weakLocalObjectReference, (0, uuid_js_1$1.uuidv4)());
  4859. }
  4860. deepSerializedValue.internalId = internalIdMap.get(weakLocalObjectReference);
  4861. delete deepSerializedValue['weakLocalObjectReference'];
  4862. }
  4863. // Platform object is a special case. It should have only `{type: object}`
  4864. // without `value` field.
  4865. if (deepSerializedValue.type === 'platformobject') {
  4866. return { type: 'object' };
  4867. }
  4868. const bidiValue = deepSerializedValue.value;
  4869. if (bidiValue === undefined) {
  4870. return deepSerializedValue;
  4871. }
  4872. // Recursively update the nested values.
  4873. if (['array', 'set', 'htmlcollection', 'nodelist'].includes(deepSerializedValue.type)) {
  4874. for (const i in bidiValue) {
  4875. bidiValue[i] = this.serializeForBiDi(bidiValue[i], internalIdMap);
  4876. }
  4877. }
  4878. if (['object', 'map'].includes(deepSerializedValue.type)) {
  4879. for (const i in bidiValue) {
  4880. bidiValue[i] = [
  4881. this.serializeForBiDi(bidiValue[i][0], internalIdMap),
  4882. this.serializeForBiDi(bidiValue[i][1], internalIdMap),
  4883. ];
  4884. }
  4885. }
  4886. return deepSerializedValue;
  4887. }
  4888. get realmId() {
  4889. return this.#realmId;
  4890. }
  4891. get executionContextId() {
  4892. return this.#executionContextId;
  4893. }
  4894. get origin() {
  4895. return this.#origin;
  4896. }
  4897. get source() {
  4898. return {
  4899. realm: this.realmId,
  4900. };
  4901. }
  4902. get cdpClient() {
  4903. return this.#cdpClient;
  4904. }
  4905. get baseInfo() {
  4906. return {
  4907. realm: this.realmId,
  4908. origin: this.origin,
  4909. };
  4910. }
  4911. async evaluate(expression, awaitPromise, resultOwnership = "none" /* Script.ResultOwnership.None */, serializationOptions = {}, userActivation = false) {
  4912. const cdpEvaluateResult = await this.cdpClient.sendCommand('Runtime.evaluate', {
  4913. contextId: this.executionContextId,
  4914. expression,
  4915. awaitPromise,
  4916. serializationOptions: Realm.#getSerializationOptions("deep" /* Protocol.Runtime.SerializationOptionsSerialization.Deep */, serializationOptions),
  4917. userGesture: userActivation,
  4918. });
  4919. if (cdpEvaluateResult.exceptionDetails) {
  4920. return await this.#getExceptionResult(cdpEvaluateResult.exceptionDetails, 0, resultOwnership);
  4921. }
  4922. return {
  4923. realm: this.realmId,
  4924. result: this.cdpToBidiValue(cdpEvaluateResult, resultOwnership),
  4925. type: 'success',
  4926. };
  4927. }
  4928. #registerEvent(event) {
  4929. if (this.associatedBrowsingContexts.length === 0) {
  4930. this.#eventManager.registerEvent(event, null);
  4931. }
  4932. else {
  4933. for (const browsingContext of this.associatedBrowsingContexts) {
  4934. this.#eventManager.registerEvent(event, browsingContext.id);
  4935. }
  4936. }
  4937. }
  4938. initialize() {
  4939. this.#registerEvent({
  4940. type: 'event',
  4941. method: protocol_js_1$b.ChromiumBidi.Script.EventNames.RealmCreated,
  4942. params: this.realmInfo,
  4943. });
  4944. }
  4945. /**
  4946. * Serializes a given CDP object into BiDi, keeping references in the
  4947. * target's `globalThis`.
  4948. */
  4949. async serializeCdpObject(cdpRemoteObject, resultOwnership) {
  4950. const argument = Realm.#cdpRemoteObjectToCallArgument(cdpRemoteObject);
  4951. const cdpValue = await this.cdpClient.sendCommand('Runtime.callFunctionOn', {
  4952. functionDeclaration: String((remoteObject) => remoteObject),
  4953. awaitPromise: false,
  4954. arguments: [argument],
  4955. serializationOptions: {
  4956. serialization: "deep" /* Protocol.Runtime.SerializationOptionsSerialization.Deep */,
  4957. },
  4958. executionContextId: this.executionContextId,
  4959. });
  4960. return this.cdpToBidiValue(cdpValue, resultOwnership);
  4961. }
  4962. static #cdpRemoteObjectToCallArgument(cdpRemoteObject) {
  4963. if (cdpRemoteObject.objectId !== undefined) {
  4964. return { objectId: cdpRemoteObject.objectId };
  4965. }
  4966. if (cdpRemoteObject.unserializableValue !== undefined) {
  4967. return { unserializableValue: cdpRemoteObject.unserializableValue };
  4968. }
  4969. return { value: cdpRemoteObject.value };
  4970. }
  4971. /**
  4972. * Gets the string representation of an object. This is equivalent to
  4973. * calling `toString()` on the object value.
  4974. */
  4975. async stringifyObject(cdpRemoteObject) {
  4976. const { result } = await this.cdpClient.sendCommand('Runtime.callFunctionOn', {
  4977. functionDeclaration: String((remoteObject) => String(remoteObject)),
  4978. awaitPromise: false,
  4979. arguments: [cdpRemoteObject],
  4980. returnByValue: true,
  4981. executionContextId: this.executionContextId,
  4982. });
  4983. return result.value;
  4984. }
  4985. async #flattenKeyValuePairs(mappingLocalValue) {
  4986. const keyValueArray = await Promise.all(mappingLocalValue.map(async ([key, value]) => {
  4987. let keyArg;
  4988. if (typeof key === 'string') {
  4989. // Key is a string.
  4990. keyArg = { value: key };
  4991. }
  4992. else {
  4993. // Key is a serialized value.
  4994. keyArg = await this.deserializeForCdp(key);
  4995. }
  4996. const valueArg = await this.deserializeForCdp(value);
  4997. return [keyArg, valueArg];
  4998. }));
  4999. return keyValueArray.flat();
  5000. }
  5001. async #flattenValueList(listLocalValue) {
  5002. return await Promise.all(listLocalValue.map((localValue) => this.deserializeForCdp(localValue)));
  5003. }
  5004. async #serializeCdpExceptionDetails(cdpExceptionDetails, lineOffset, resultOwnership) {
  5005. const callFrames = cdpExceptionDetails.stackTrace?.callFrames.map((frame) => ({
  5006. url: frame.url,
  5007. functionName: frame.functionName,
  5008. lineNumber: frame.lineNumber - lineOffset,
  5009. columnNumber: frame.columnNumber,
  5010. })) ?? [];
  5011. // Exception should always be there.
  5012. const exception = cdpExceptionDetails.exception;
  5013. return {
  5014. exception: await this.serializeCdpObject(exception, resultOwnership),
  5015. columnNumber: cdpExceptionDetails.columnNumber,
  5016. lineNumber: cdpExceptionDetails.lineNumber - lineOffset,
  5017. stackTrace: {
  5018. callFrames,
  5019. },
  5020. text: (await this.stringifyObject(exception)) || cdpExceptionDetails.text,
  5021. };
  5022. }
  5023. async callFunction(functionDeclaration, awaitPromise, thisLocalValue = {
  5024. type: 'undefined',
  5025. }, argumentsLocalValues = [], resultOwnership = "none" /* Script.ResultOwnership.None */, serializationOptions = {}, userActivation = false) {
  5026. const callFunctionAndSerializeScript = `(...args) => {
  5027. function callFunction(f, args) {
  5028. const deserializedThis = args.shift();
  5029. const deserializedArgs = args;
  5030. return f.apply(deserializedThis, deserializedArgs);
  5031. }
  5032. return callFunction((
  5033. ${functionDeclaration}
  5034. ), args);
  5035. }`;
  5036. const thisAndArgumentsList = [
  5037. await this.deserializeForCdp(thisLocalValue),
  5038. ...(await Promise.all(argumentsLocalValues.map(async (argumentLocalValue) => await this.deserializeForCdp(argumentLocalValue)))),
  5039. ];
  5040. let cdpCallFunctionResult;
  5041. try {
  5042. cdpCallFunctionResult = await this.cdpClient.sendCommand('Runtime.callFunctionOn', {
  5043. functionDeclaration: callFunctionAndSerializeScript,
  5044. awaitPromise,
  5045. arguments: thisAndArgumentsList,
  5046. serializationOptions: Realm.#getSerializationOptions("deep" /* Protocol.Runtime.SerializationOptionsSerialization.Deep */, serializationOptions),
  5047. executionContextId: this.executionContextId,
  5048. userGesture: userActivation,
  5049. });
  5050. }
  5051. catch (error) {
  5052. // Heuristic to determine if the problem is in the argument.
  5053. // The check can be done on the `deserialization` step, but this approach
  5054. // helps to save round-trips.
  5055. if (error.code === -32000 /* CdpErrorConstants.GENERIC_ERROR */ &&
  5056. [
  5057. 'Could not find object with given id',
  5058. 'Argument should belong to the same JavaScript world as target object',
  5059. 'Invalid remote object id',
  5060. ].includes(error.message)) {
  5061. throw new protocol_js_1$b.NoSuchHandleException('Handle was not found.');
  5062. }
  5063. throw error;
  5064. }
  5065. if (cdpCallFunctionResult.exceptionDetails) {
  5066. return await this.#getExceptionResult(cdpCallFunctionResult.exceptionDetails, 1, resultOwnership);
  5067. }
  5068. return {
  5069. type: 'success',
  5070. result: this.cdpToBidiValue(cdpCallFunctionResult, resultOwnership),
  5071. realm: this.realmId,
  5072. };
  5073. }
  5074. async deserializeForCdp(localValue) {
  5075. if ('handle' in localValue && localValue.handle) {
  5076. return { objectId: localValue.handle };
  5077. // We tried to find a handle value but failed
  5078. // This allows us to have exhaustive switch on `localValue.type`
  5079. }
  5080. else if ('handle' in localValue || 'sharedId' in localValue) {
  5081. throw new protocol_js_1$b.NoSuchHandleException('Handle was not found.');
  5082. }
  5083. switch (localValue.type) {
  5084. case 'undefined':
  5085. return { unserializableValue: 'undefined' };
  5086. case 'null':
  5087. return { unserializableValue: 'null' };
  5088. case 'string':
  5089. return { value: localValue.value };
  5090. case 'number':
  5091. if (localValue.value === 'NaN') {
  5092. return { unserializableValue: 'NaN' };
  5093. }
  5094. else if (localValue.value === '-0') {
  5095. return { unserializableValue: '-0' };
  5096. }
  5097. else if (localValue.value === 'Infinity') {
  5098. return { unserializableValue: 'Infinity' };
  5099. }
  5100. else if (localValue.value === '-Infinity') {
  5101. return { unserializableValue: '-Infinity' };
  5102. }
  5103. return {
  5104. value: localValue.value,
  5105. };
  5106. case 'boolean':
  5107. return { value: Boolean(localValue.value) };
  5108. case 'bigint':
  5109. return {
  5110. unserializableValue: `BigInt(${JSON.stringify(localValue.value)})`,
  5111. };
  5112. case 'date':
  5113. return {
  5114. unserializableValue: `new Date(Date.parse(${JSON.stringify(localValue.value)}))`,
  5115. };
  5116. case 'regexp':
  5117. return {
  5118. unserializableValue: `new RegExp(${JSON.stringify(localValue.value.pattern)}, ${JSON.stringify(localValue.value.flags)})`,
  5119. };
  5120. case 'map': {
  5121. // TODO: If none of the nested keys and values has a remote
  5122. // reference, serialize to `unserializableValue` without CDP roundtrip.
  5123. const keyValueArray = await this.#flattenKeyValuePairs(localValue.value);
  5124. const { result } = await this.cdpClient.sendCommand('Runtime.callFunctionOn', {
  5125. functionDeclaration: String((...args) => {
  5126. const result = new Map();
  5127. for (let i = 0; i < args.length; i += 2) {
  5128. result.set(args[i], args[i + 1]);
  5129. }
  5130. return result;
  5131. }),
  5132. awaitPromise: false,
  5133. arguments: keyValueArray,
  5134. returnByValue: false,
  5135. executionContextId: this.executionContextId,
  5136. });
  5137. // TODO(#375): Release `result.objectId` after using.
  5138. return { objectId: result.objectId };
  5139. }
  5140. case 'object': {
  5141. // TODO: If none of the nested keys and values has a remote
  5142. // reference, serialize to `unserializableValue` without CDP roundtrip.
  5143. const keyValueArray = await this.#flattenKeyValuePairs(localValue.value);
  5144. const { result } = await this.cdpClient.sendCommand('Runtime.callFunctionOn', {
  5145. functionDeclaration: String((...args) => {
  5146. const result = {};
  5147. for (let i = 0; i < args.length; i += 2) {
  5148. // Key should be either `string`, `number`, or `symbol`.
  5149. const key = args[i];
  5150. result[key] = args[i + 1];
  5151. }
  5152. return result;
  5153. }),
  5154. awaitPromise: false,
  5155. arguments: keyValueArray,
  5156. returnByValue: false,
  5157. executionContextId: this.executionContextId,
  5158. });
  5159. // TODO(#375): Release `result.objectId` after using.
  5160. return { objectId: result.objectId };
  5161. }
  5162. case 'array': {
  5163. // TODO: If none of the nested items has a remote reference,
  5164. // serialize to `unserializableValue` without CDP roundtrip.
  5165. const args = await this.#flattenValueList(localValue.value);
  5166. const { result } = await this.cdpClient.sendCommand('Runtime.callFunctionOn', {
  5167. functionDeclaration: String((...args) => args),
  5168. awaitPromise: false,
  5169. arguments: args,
  5170. returnByValue: false,
  5171. executionContextId: this.executionContextId,
  5172. });
  5173. // TODO(#375): Release `result.objectId` after using.
  5174. return { objectId: result.objectId };
  5175. }
  5176. case 'set': {
  5177. // TODO: if none of the nested items has a remote reference,
  5178. // serialize to `unserializableValue` without CDP roundtrip.
  5179. const args = await this.#flattenValueList(localValue.value);
  5180. const { result } = await this.cdpClient.sendCommand('Runtime.callFunctionOn', {
  5181. functionDeclaration: String((...args) => new Set(args)),
  5182. awaitPromise: false,
  5183. arguments: args,
  5184. returnByValue: false,
  5185. executionContextId: this.executionContextId,
  5186. });
  5187. // TODO(#375): Release `result.objectId` after using.
  5188. return { objectId: result.objectId };
  5189. }
  5190. case 'channel': {
  5191. const channelProxy = new ChannelProxy_js_1.ChannelProxy(localValue.value, this.#logger);
  5192. const channelProxySendMessageHandle = await channelProxy.init(this, this.#eventManager);
  5193. return { objectId: channelProxySendMessageHandle };
  5194. }
  5195. // TODO(#375): Dispose of nested objects.
  5196. }
  5197. // Intentionally outside to handle unknown types
  5198. throw new Error(`Value ${JSON.stringify(localValue)} is not deserializable.`);
  5199. }
  5200. async #getExceptionResult(exceptionDetails, lineOffset, resultOwnership) {
  5201. return {
  5202. exceptionDetails: await this.#serializeCdpExceptionDetails(exceptionDetails, lineOffset, resultOwnership),
  5203. realm: this.realmId,
  5204. type: 'exception',
  5205. };
  5206. }
  5207. static #getSerializationOptions(serialization, serializationOptions) {
  5208. return {
  5209. serialization,
  5210. additionalParameters: Realm.#getAdditionalSerializationParameters(serializationOptions),
  5211. ...Realm.#getMaxObjectDepth(serializationOptions),
  5212. };
  5213. }
  5214. static #getAdditionalSerializationParameters(serializationOptions) {
  5215. const additionalParameters = {};
  5216. if (serializationOptions.maxDomDepth !== undefined) {
  5217. additionalParameters['maxNodeDepth'] =
  5218. serializationOptions.maxDomDepth === null
  5219. ? 1000
  5220. : serializationOptions.maxDomDepth;
  5221. }
  5222. if (serializationOptions.includeShadowTree !== undefined) {
  5223. additionalParameters['includeShadowTree'] =
  5224. serializationOptions.includeShadowTree;
  5225. }
  5226. return additionalParameters;
  5227. }
  5228. static #getMaxObjectDepth(serializationOptions) {
  5229. return serializationOptions.maxObjectDepth === undefined ||
  5230. serializationOptions.maxObjectDepth === null
  5231. ? {}
  5232. : { maxDepth: serializationOptions.maxObjectDepth };
  5233. }
  5234. async #releaseObject(handle) {
  5235. try {
  5236. await this.cdpClient.sendCommand('Runtime.releaseObject', {
  5237. objectId: handle,
  5238. });
  5239. }
  5240. catch (error) {
  5241. // Heuristic to determine if the problem is in the unknown handler.
  5242. // Ignore the error if so.
  5243. if (!(error.code === -32000 /* CdpErrorConstants.GENERIC_ERROR */ &&
  5244. error.message === 'Invalid remote object id')) {
  5245. throw error;
  5246. }
  5247. }
  5248. }
  5249. async disown(handle) {
  5250. // Disowning an object from different realm does nothing.
  5251. if (this.#realmStorage.knownHandlesToRealmMap.get(handle) !== this.realmId) {
  5252. return;
  5253. }
  5254. await this.#releaseObject(handle);
  5255. this.#realmStorage.knownHandlesToRealmMap.delete(handle);
  5256. }
  5257. dispose() {
  5258. this.#registerEvent({
  5259. type: 'event',
  5260. method: protocol_js_1$b.ChromiumBidi.Script.EventNames.RealmDestroyed,
  5261. params: {
  5262. realm: this.realmId,
  5263. },
  5264. });
  5265. }
  5266. }
  5267. Realm$1.Realm = Realm;
  5268. var SharedId = {};
  5269. /*
  5270. * Copyright 2023 Google LLC.
  5271. * Copyright (c) Microsoft Corporation.
  5272. *
  5273. * Licensed under the Apache License, Version 2.0 (the "License");
  5274. * you may not use this file except in compliance with the License.
  5275. * You may obtain a copy of the License at
  5276. *
  5277. * http://www.apache.org/licenses/LICENSE-2.0
  5278. *
  5279. * Unless required by applicable law or agreed to in writing, software
  5280. * distributed under the License is distributed on an "AS IS" BASIS,
  5281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5282. * See the License for the specific language governing permissions and
  5283. * limitations under the License.
  5284. */
  5285. Object.defineProperty(SharedId, "__esModule", { value: true });
  5286. SharedId.parseSharedId = SharedId.getSharedId = void 0;
  5287. const SHARED_ID_DIVIDER = '_element_';
  5288. function getSharedId(frameId, documentId, backendNodeId) {
  5289. return `f.${frameId}.d.${documentId}.e.${backendNodeId}`;
  5290. }
  5291. SharedId.getSharedId = getSharedId;
  5292. function parseLegacySharedId(sharedId) {
  5293. const match = sharedId.match(new RegExp(`(.*)${SHARED_ID_DIVIDER}(.*)`));
  5294. if (!match) {
  5295. // SharedId is incorrectly formatted.
  5296. return null;
  5297. }
  5298. const documentId = match[1];
  5299. const elementId = match[2];
  5300. if (documentId === undefined || elementId === undefined) {
  5301. return null;
  5302. }
  5303. const backendNodeId = parseInt(elementId ?? '');
  5304. if (isNaN(backendNodeId)) {
  5305. return null;
  5306. }
  5307. return {
  5308. documentId,
  5309. backendNodeId,
  5310. };
  5311. }
  5312. function parseSharedId(sharedId) {
  5313. // TODO: remove legacy check once ChromeDriver provides sharedId in the new format.
  5314. const legacyFormattedSharedId = parseLegacySharedId(sharedId);
  5315. if (legacyFormattedSharedId !== null) {
  5316. return { ...legacyFormattedSharedId, frameId: undefined };
  5317. }
  5318. const match = sharedId.match(/f\.(.*)\.d\.(.*)\.e\.([0-9]*)/);
  5319. if (!match) {
  5320. // SharedId is incorrectly formatted.
  5321. return null;
  5322. }
  5323. const frameId = match[1];
  5324. const documentId = match[2];
  5325. const elementId = match[3];
  5326. if (frameId === undefined ||
  5327. documentId === undefined ||
  5328. elementId === undefined) {
  5329. return null;
  5330. }
  5331. const backendNodeId = parseInt(elementId ?? '');
  5332. if (isNaN(backendNodeId)) {
  5333. return null;
  5334. }
  5335. return {
  5336. frameId,
  5337. documentId,
  5338. backendNodeId,
  5339. };
  5340. }
  5341. SharedId.parseSharedId = parseSharedId;
  5342. /**
  5343. * Copyright 2024 Google LLC.
  5344. * Copyright (c) Microsoft Corporation.
  5345. *
  5346. * Licensed under the Apache License, Version 2.0 (the "License");
  5347. * you may not use this file except in compliance with the License.
  5348. * You may obtain a copy of the License at
  5349. *
  5350. * http://www.apache.org/licenses/LICENSE-2.0
  5351. *
  5352. * Unless required by applicable law or agreed to in writing, software
  5353. * distributed under the License is distributed on an "AS IS" BASIS,
  5354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5355. * See the License for the specific language governing permissions and
  5356. * limitations under the License.
  5357. */
  5358. Object.defineProperty(WindowRealm$1, "__esModule", { value: true });
  5359. WindowRealm$1.WindowRealm = void 0;
  5360. const protocol_js_1$a = protocol;
  5361. const Realm_js_1$1 = Realm$1;
  5362. const SharedId_js_1 = SharedId;
  5363. class WindowRealm extends Realm_js_1$1.Realm {
  5364. #browsingContextId;
  5365. #browsingContextStorage;
  5366. sandbox;
  5367. constructor(browsingContextId, browsingContextStorage, cdpClient, eventManager, executionContextId, logger, origin, realmId, realmStorage, sandbox) {
  5368. super(cdpClient, eventManager, executionContextId, logger, origin, realmId, realmStorage);
  5369. this.#browsingContextId = browsingContextId;
  5370. this.#browsingContextStorage = browsingContextStorage;
  5371. this.sandbox = sandbox;
  5372. this.initialize();
  5373. }
  5374. #getBrowsingContextId(navigableId) {
  5375. const maybeBrowsingContext = this.#browsingContextStorage
  5376. .getAllContexts()
  5377. .find((context) => context.navigableId === navigableId);
  5378. return maybeBrowsingContext?.id ?? 'UNKNOWN';
  5379. }
  5380. get browsingContext() {
  5381. return this.#browsingContextStorage.getContext(this.#browsingContextId);
  5382. }
  5383. get associatedBrowsingContexts() {
  5384. return [this.browsingContext];
  5385. }
  5386. get realmType() {
  5387. return 'window';
  5388. }
  5389. get realmInfo() {
  5390. return {
  5391. ...this.baseInfo,
  5392. type: this.realmType,
  5393. context: this.#browsingContextId,
  5394. sandbox: this.sandbox,
  5395. };
  5396. }
  5397. get source() {
  5398. return {
  5399. realm: this.realmId,
  5400. context: this.browsingContext.id,
  5401. };
  5402. }
  5403. serializeForBiDi(deepSerializedValue, internalIdMap) {
  5404. const bidiValue = deepSerializedValue.value;
  5405. if (deepSerializedValue.type === 'node' && bidiValue !== undefined) {
  5406. if (Object.hasOwn(bidiValue, 'backendNodeId')) {
  5407. let navigableId = this.browsingContext.navigableId ?? 'UNKNOWN';
  5408. if (Object.hasOwn(bidiValue, 'loaderId')) {
  5409. // `loaderId` should be always there after ~2024-03-05, when
  5410. // https://crrev.com/c/5116240 reaches stable.
  5411. // TODO: remove the check after the date.
  5412. navigableId = bidiValue.loaderId;
  5413. delete bidiValue['loaderId'];
  5414. }
  5415. deepSerializedValue.sharedId =
  5416. (0, SharedId_js_1.getSharedId)(this.#getBrowsingContextId(navigableId), navigableId, bidiValue.backendNodeId);
  5417. delete bidiValue['backendNodeId'];
  5418. }
  5419. if (Object.hasOwn(bidiValue, 'children')) {
  5420. for (const i in bidiValue.children) {
  5421. bidiValue.children[i] = this.serializeForBiDi(bidiValue.children[i], internalIdMap);
  5422. }
  5423. }
  5424. if (Object.hasOwn(bidiValue, 'shadowRoot') &&
  5425. bidiValue.shadowRoot !== null) {
  5426. bidiValue.shadowRoot = this.serializeForBiDi(bidiValue.shadowRoot, internalIdMap);
  5427. }
  5428. // `namespaceURI` can be is either `null` or non-empty string.
  5429. if (bidiValue.namespaceURI === '') {
  5430. bidiValue.namespaceURI = null;
  5431. }
  5432. }
  5433. return super.serializeForBiDi(deepSerializedValue, internalIdMap);
  5434. }
  5435. async deserializeForCdp(localValue) {
  5436. if ('sharedId' in localValue && localValue.sharedId) {
  5437. const parsedSharedId = (0, SharedId_js_1.parseSharedId)(localValue.sharedId);
  5438. if (parsedSharedId === null) {
  5439. throw new protocol_js_1$a.NoSuchNodeException(`SharedId "${localValue.sharedId}" was not found.`);
  5440. }
  5441. const { documentId, backendNodeId } = parsedSharedId;
  5442. // TODO: add proper validation if the element is accessible from the current realm.
  5443. if (this.browsingContext.navigableId !== documentId) {
  5444. throw new protocol_js_1$a.NoSuchNodeException(`SharedId "${localValue.sharedId}" belongs to different document. Current document is ${this.browsingContext.navigableId}.`);
  5445. }
  5446. try {
  5447. const { object } = await this.cdpClient.sendCommand('DOM.resolveNode', {
  5448. backendNodeId,
  5449. executionContextId: this.executionContextId,
  5450. });
  5451. // TODO(#375): Release `obj.object.objectId` after using.
  5452. return { objectId: object.objectId };
  5453. }
  5454. catch (error) {
  5455. // Heuristic to detect "no such node" exception. Based on the specific
  5456. // CDP implementation.
  5457. if (error.code === -32000 /* CdpErrorConstants.GENERIC_ERROR */ &&
  5458. error.message === 'No node with given id found') {
  5459. throw new protocol_js_1$a.NoSuchNodeException(`SharedId "${localValue.sharedId}" was not found.`);
  5460. }
  5461. throw new protocol_js_1$a.UnknownErrorException(error.message, error.stack);
  5462. }
  5463. }
  5464. return await super.deserializeForCdp(localValue);
  5465. }
  5466. async evaluate(expression, awaitPromise, resultOwnership, serializationOptions, userActivation) {
  5467. await this.#browsingContextStorage
  5468. .getContext(this.#browsingContextId)
  5469. .targetUnblockedOrThrow();
  5470. return await super.evaluate(expression, awaitPromise, resultOwnership, serializationOptions, userActivation);
  5471. }
  5472. async callFunction(functionDeclaration, awaitPromise, thisLocalValue, argumentsLocalValues, resultOwnership, serializationOptions, userActivation) {
  5473. await this.#browsingContextStorage
  5474. .getContext(this.#browsingContextId)
  5475. .targetUnblockedOrThrow();
  5476. return await super.callFunction(functionDeclaration, awaitPromise, thisLocalValue, argumentsLocalValues, resultOwnership, serializationOptions, userActivation);
  5477. }
  5478. }
  5479. WindowRealm$1.WindowRealm = WindowRealm;
  5480. /**
  5481. * Copyright 2022 Google LLC.
  5482. * Copyright (c) Microsoft Corporation.
  5483. *
  5484. * Licensed under the Apache License, Version 2.0 (the "License");
  5485. * you may not use this file except in compliance with the License.
  5486. * You may obtain a copy of the License at
  5487. *
  5488. * http://www.apache.org/licenses/LICENSE-2.0
  5489. *
  5490. * Unless required by applicable law or agreed to in writing, software
  5491. * distributed under the License is distributed on an "AS IS" BASIS,
  5492. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5493. * See the License for the specific language governing permissions and
  5494. * limitations under the License.
  5495. */
  5496. Object.defineProperty(BrowsingContextImpl$1, "__esModule", { value: true });
  5497. BrowsingContextImpl$1.serializeOrigin = BrowsingContextImpl$1.BrowsingContextImpl = void 0;
  5498. const protocol_js_1$9 = protocol;
  5499. const assert_js_1$2 = assert$1;
  5500. const Deferred_js_1$2 = Deferred$1;
  5501. const log_js_1$8 = log$1;
  5502. const unitConversions_js_1 = unitConversions;
  5503. const WindowRealm_js_1$1 = WindowRealm$1;
  5504. class BrowsingContextImpl {
  5505. static LOGGER_PREFIX = `${log_js_1$8.LogType.debug}:browsingContext`;
  5506. /** The ID of this browsing context. */
  5507. #id;
  5508. userContext;
  5509. /**
  5510. * The ID of the parent browsing context.
  5511. * If null, this is a top-level context.
  5512. */
  5513. #parentId;
  5514. /** Direct children browsing contexts. */
  5515. #children = new Set();
  5516. #browsingContextStorage;
  5517. #lifecycle = {
  5518. DOMContentLoaded: new Deferred_js_1$2.Deferred(),
  5519. load: new Deferred_js_1$2.Deferred(),
  5520. };
  5521. #navigation = {
  5522. withinDocument: new Deferred_js_1$2.Deferred(),
  5523. };
  5524. #url = 'about:blank';
  5525. #eventManager;
  5526. #realmStorage;
  5527. #loaderId;
  5528. #cdpTarget;
  5529. #maybeDefaultRealm;
  5530. #logger;
  5531. // Keeps track of the previously set viewport.
  5532. #previousViewport = { width: 0, height: 0 };
  5533. constructor(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, logger) {
  5534. this.#cdpTarget = cdpTarget;
  5535. this.#id = id;
  5536. this.#parentId = parentId;
  5537. this.userContext = userContext;
  5538. this.#eventManager = eventManager;
  5539. this.#browsingContextStorage = browsingContextStorage;
  5540. this.#realmStorage = realmStorage;
  5541. this.#logger = logger;
  5542. }
  5543. static create(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, logger) {
  5544. const context = new BrowsingContextImpl(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, logger);
  5545. context.#initListeners();
  5546. browsingContextStorage.addContext(context);
  5547. if (!context.isTopLevelContext()) {
  5548. context.parent.addChild(context.id);
  5549. }
  5550. eventManager.registerEvent({
  5551. type: 'event',
  5552. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.ContextCreated,
  5553. params: context.serializeToBidiValue(),
  5554. }, context.id);
  5555. return context;
  5556. }
  5557. static getTimestamp() {
  5558. // `timestamp` from the event is MonotonicTime, not real time, so
  5559. // the best Mapper can do is to set the timestamp to the epoch time
  5560. // of the event arrived.
  5561. // https://chromedevtools.github.io/devtools-protocol/tot/Network/#type-MonotonicTime
  5562. return new Date().getTime();
  5563. }
  5564. /**
  5565. * @see https://html.spec.whatwg.org/multipage/document-sequences.html#navigable
  5566. */
  5567. get navigableId() {
  5568. return this.#loaderId;
  5569. }
  5570. dispose() {
  5571. this.#deleteAllChildren();
  5572. this.#realmStorage.deleteRealms({
  5573. browsingContextId: this.id,
  5574. });
  5575. // Remove context from the parent.
  5576. if (!this.isTopLevelContext()) {
  5577. this.parent.#children.delete(this.id);
  5578. }
  5579. // Fail all ongoing navigations.
  5580. this.#failLifecycleIfNotFinished();
  5581. this.#eventManager.registerEvent({
  5582. type: 'event',
  5583. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.ContextDestroyed,
  5584. params: this.serializeToBidiValue(),
  5585. }, this.id);
  5586. this.#browsingContextStorage.deleteContextById(this.id);
  5587. }
  5588. /** Returns the ID of this context. */
  5589. get id() {
  5590. return this.#id;
  5591. }
  5592. /** Returns the parent context ID. */
  5593. get parentId() {
  5594. return this.#parentId;
  5595. }
  5596. /** Returns the parent context. */
  5597. get parent() {
  5598. if (this.parentId === null) {
  5599. return null;
  5600. }
  5601. return this.#browsingContextStorage.getContext(this.parentId);
  5602. }
  5603. /** Returns all direct children contexts. */
  5604. get directChildren() {
  5605. return [...this.#children].map((id) => this.#browsingContextStorage.getContext(id));
  5606. }
  5607. /** Returns all children contexts, flattened. */
  5608. get allChildren() {
  5609. const children = this.directChildren;
  5610. return children.concat(...children.map((child) => child.allChildren));
  5611. }
  5612. /**
  5613. * Returns true if this is a top-level context.
  5614. * This is the case whenever the parent context ID is null.
  5615. */
  5616. isTopLevelContext() {
  5617. return this.#parentId === null;
  5618. }
  5619. get top() {
  5620. // eslint-disable-next-line @typescript-eslint/no-this-alias
  5621. let topContext = this;
  5622. let parent = topContext.parent;
  5623. while (parent) {
  5624. topContext = parent;
  5625. parent = topContext.parent;
  5626. }
  5627. return topContext;
  5628. }
  5629. addChild(childId) {
  5630. this.#children.add(childId);
  5631. }
  5632. #deleteAllChildren() {
  5633. this.directChildren.map((child) => child.dispose());
  5634. }
  5635. get #defaultRealm() {
  5636. (0, assert_js_1$2.assert)(this.#maybeDefaultRealm, `No default realm for browsing context ${this.#id}`);
  5637. return this.#maybeDefaultRealm;
  5638. }
  5639. get cdpTarget() {
  5640. return this.#cdpTarget;
  5641. }
  5642. updateCdpTarget(cdpTarget) {
  5643. this.#cdpTarget = cdpTarget;
  5644. this.#initListeners();
  5645. }
  5646. get url() {
  5647. return this.#url;
  5648. }
  5649. async lifecycleLoaded() {
  5650. await this.#lifecycle.load;
  5651. }
  5652. async targetUnblockedOrThrow() {
  5653. const result = await this.#cdpTarget.unblocked;
  5654. if (result.kind === 'error') {
  5655. throw result.error;
  5656. }
  5657. }
  5658. async getOrCreateSandbox(sandbox) {
  5659. if (sandbox === undefined || sandbox === '') {
  5660. return this.#defaultRealm;
  5661. }
  5662. let maybeSandboxes = this.#realmStorage.findRealms({
  5663. browsingContextId: this.id,
  5664. sandbox,
  5665. });
  5666. if (maybeSandboxes.length === 0) {
  5667. await this.#cdpTarget.cdpClient.sendCommand('Page.createIsolatedWorld', {
  5668. frameId: this.id,
  5669. worldName: sandbox,
  5670. });
  5671. // `Runtime.executionContextCreated` should be emitted by the time the
  5672. // previous command is done.
  5673. maybeSandboxes = this.#realmStorage.findRealms({
  5674. browsingContextId: this.id,
  5675. sandbox,
  5676. });
  5677. (0, assert_js_1$2.assert)(maybeSandboxes.length !== 0);
  5678. }
  5679. // It's possible for more than one sandbox to be created due to provisional
  5680. // frames. In this case, it's always the first one (i.e. the oldest one)
  5681. // that is more relevant since the user may have set that one up already
  5682. // through evaluation.
  5683. return maybeSandboxes[0];
  5684. }
  5685. serializeToBidiValue(maxDepth = 0, addParentField = true) {
  5686. return {
  5687. context: this.#id,
  5688. url: this.url,
  5689. userContext: this.userContext,
  5690. children: maxDepth > 0
  5691. ? this.directChildren.map((c) => c.serializeToBidiValue(maxDepth - 1, false))
  5692. : null,
  5693. ...(addParentField ? { parent: this.#parentId } : {}),
  5694. };
  5695. }
  5696. onTargetInfoChanged(params) {
  5697. this.#url = params.targetInfo.url;
  5698. }
  5699. #initListeners() {
  5700. this.#cdpTarget.cdpClient.on('Page.frameNavigated', (params) => {
  5701. if (this.id !== params.frame.id) {
  5702. return;
  5703. }
  5704. this.#url = params.frame.url + (params.frame.urlFragment ?? '');
  5705. // At the point the page is initialized, all the nested iframes from the
  5706. // previous page are detached and realms are destroyed.
  5707. // Remove children from context.
  5708. this.#deleteAllChildren();
  5709. });
  5710. this.#cdpTarget.cdpClient.on('Page.navigatedWithinDocument', (params) => {
  5711. if (this.id !== params.frameId) {
  5712. return;
  5713. }
  5714. const timestamp = BrowsingContextImpl.getTimestamp();
  5715. this.#url = params.url;
  5716. this.#navigation.withinDocument.resolve(params);
  5717. this.#eventManager.registerEvent({
  5718. type: 'event',
  5719. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.FragmentNavigated,
  5720. params: {
  5721. context: this.id,
  5722. navigation: null,
  5723. timestamp,
  5724. url: this.#url,
  5725. },
  5726. }, this.id);
  5727. });
  5728. this.#cdpTarget.cdpClient.on('Page.frameStartedLoading', (params) => {
  5729. if (this.id !== params.frameId) {
  5730. return;
  5731. }
  5732. this.#eventManager.registerEvent({
  5733. type: 'event',
  5734. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.NavigationStarted,
  5735. params: {
  5736. context: this.id,
  5737. navigation: null,
  5738. timestamp: BrowsingContextImpl.getTimestamp(),
  5739. url: '',
  5740. },
  5741. }, this.id);
  5742. });
  5743. this.#cdpTarget.cdpClient.on('Page.lifecycleEvent', (params) => {
  5744. if (this.id !== params.frameId) {
  5745. return;
  5746. }
  5747. if (params.name === 'init') {
  5748. this.#documentChanged(params.loaderId);
  5749. return;
  5750. }
  5751. if (params.name === 'commit') {
  5752. this.#loaderId = params.loaderId;
  5753. return;
  5754. }
  5755. // If mapper attached to the page late, it might miss init and
  5756. // commit events. In that case, save the first loaderId for this
  5757. // frameId.
  5758. if (!this.#loaderId) {
  5759. this.#loaderId = params.loaderId;
  5760. }
  5761. // Ignore event from not current navigation.
  5762. if (params.loaderId !== this.#loaderId) {
  5763. return;
  5764. }
  5765. const timestamp = BrowsingContextImpl.getTimestamp();
  5766. switch (params.name) {
  5767. case 'DOMContentLoaded':
  5768. this.#eventManager.registerEvent({
  5769. type: 'event',
  5770. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.DomContentLoaded,
  5771. params: {
  5772. context: this.id,
  5773. navigation: this.#loaderId ?? null,
  5774. timestamp,
  5775. url: this.#url,
  5776. },
  5777. }, this.id);
  5778. this.#lifecycle.DOMContentLoaded.resolve(params);
  5779. break;
  5780. case 'load':
  5781. this.#eventManager.registerEvent({
  5782. type: 'event',
  5783. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.Load,
  5784. params: {
  5785. context: this.id,
  5786. navigation: this.#loaderId ?? null,
  5787. timestamp,
  5788. url: this.#url,
  5789. },
  5790. }, this.id);
  5791. this.#lifecycle.load.resolve(params);
  5792. break;
  5793. }
  5794. });
  5795. this.#cdpTarget.cdpClient.on('Runtime.executionContextCreated', (params) => {
  5796. const { auxData, name, uniqueId, id } = params.context;
  5797. if (!auxData || auxData.frameId !== this.id) {
  5798. return;
  5799. }
  5800. let origin;
  5801. let sandbox;
  5802. // Only these execution contexts are supported for now.
  5803. switch (auxData.type) {
  5804. case 'isolated':
  5805. sandbox = name;
  5806. // Sandbox should have the same origin as the context itself, but in CDP
  5807. // it has an empty one.
  5808. origin = this.#defaultRealm.origin;
  5809. break;
  5810. case 'default':
  5811. origin = serializeOrigin(params.context.origin);
  5812. break;
  5813. default:
  5814. return;
  5815. }
  5816. const realm = new WindowRealm_js_1$1.WindowRealm(this.id, this.#browsingContextStorage, this.#cdpTarget.cdpClient, this.#eventManager, id, this.#logger, origin, uniqueId, this.#realmStorage, sandbox);
  5817. if (auxData.isDefault) {
  5818. this.#maybeDefaultRealm = realm;
  5819. // Initialize ChannelProxy listeners for all the channels of all the
  5820. // preload scripts related to this BrowsingContext.
  5821. // TODO: extend for not default realms by the sandbox name.
  5822. void Promise.all(this.#cdpTarget
  5823. .getChannels()
  5824. .map((channel) => channel.startListenerFromWindow(realm, this.#eventManager)));
  5825. }
  5826. });
  5827. this.#cdpTarget.cdpClient.on('Runtime.executionContextDestroyed', (params) => {
  5828. this.#realmStorage.deleteRealms({
  5829. cdpSessionId: this.#cdpTarget.cdpSessionId,
  5830. executionContextId: params.executionContextId,
  5831. });
  5832. });
  5833. this.#cdpTarget.cdpClient.on('Runtime.executionContextsCleared', () => {
  5834. this.#realmStorage.deleteRealms({
  5835. cdpSessionId: this.#cdpTarget.cdpSessionId,
  5836. });
  5837. });
  5838. this.#cdpTarget.cdpClient.on('Page.javascriptDialogClosed', (params) => {
  5839. const accepted = params.result;
  5840. this.#eventManager.registerEvent({
  5841. type: 'event',
  5842. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.UserPromptClosed,
  5843. params: {
  5844. context: this.id,
  5845. accepted,
  5846. userText: accepted && params.userInput ? params.userInput : undefined,
  5847. },
  5848. }, this.id);
  5849. });
  5850. this.#cdpTarget.cdpClient.on('Page.javascriptDialogOpening', (params) => {
  5851. this.#eventManager.registerEvent({
  5852. type: 'event',
  5853. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.UserPromptOpened,
  5854. params: {
  5855. context: this.id,
  5856. type: params.type,
  5857. message: params.message,
  5858. // Don't set the value if empty string
  5859. defaultValue: params.defaultPrompt || undefined,
  5860. },
  5861. }, this.id);
  5862. });
  5863. }
  5864. #documentChanged(loaderId) {
  5865. // Same document navigation.
  5866. if (loaderId === undefined || this.#loaderId === loaderId) {
  5867. if (this.#navigation.withinDocument.isFinished) {
  5868. this.#navigation.withinDocument =
  5869. new Deferred_js_1$2.Deferred();
  5870. }
  5871. else {
  5872. this.#logger?.(BrowsingContextImpl.LOGGER_PREFIX, 'Document changed (navigatedWithinDocument)');
  5873. }
  5874. return;
  5875. }
  5876. this.#resetLifecycleIfFinished();
  5877. this.#loaderId = loaderId;
  5878. }
  5879. #resetLifecycleIfFinished() {
  5880. if (this.#lifecycle.DOMContentLoaded.isFinished) {
  5881. this.#lifecycle.DOMContentLoaded =
  5882. new Deferred_js_1$2.Deferred();
  5883. }
  5884. else {
  5885. this.#logger?.(BrowsingContextImpl.LOGGER_PREFIX, 'Document changed (DOMContentLoaded)');
  5886. }
  5887. if (this.#lifecycle.load.isFinished) {
  5888. this.#lifecycle.load = new Deferred_js_1$2.Deferred();
  5889. }
  5890. else {
  5891. this.#logger?.(BrowsingContextImpl.LOGGER_PREFIX, 'Document changed (load)');
  5892. }
  5893. }
  5894. #failLifecycleIfNotFinished() {
  5895. if (!this.#lifecycle.DOMContentLoaded.isFinished) {
  5896. this.#lifecycle.DOMContentLoaded.reject(new protocol_js_1$9.UnknownErrorException('navigation canceled'));
  5897. }
  5898. if (!this.#lifecycle.load.isFinished) {
  5899. this.#lifecycle.load.reject(new protocol_js_1$9.UnknownErrorException('navigation canceled'));
  5900. }
  5901. }
  5902. async navigate(url, wait) {
  5903. try {
  5904. new URL(url);
  5905. }
  5906. catch {
  5907. throw new protocol_js_1$9.InvalidArgumentException(`Invalid URL: ${url}`);
  5908. }
  5909. await this.targetUnblockedOrThrow();
  5910. // TODO: handle loading errors.
  5911. const cdpNavigateResult = await this.#cdpTarget.cdpClient.sendCommand('Page.navigate', {
  5912. url,
  5913. frameId: this.id,
  5914. });
  5915. if (cdpNavigateResult.errorText) {
  5916. this.#eventManager.registerEvent({
  5917. type: 'event',
  5918. method: protocol_js_1$9.ChromiumBidi.BrowsingContext.EventNames.NavigationFailed,
  5919. params: {
  5920. context: this.id,
  5921. navigation: cdpNavigateResult.loaderId ?? null,
  5922. timestamp: BrowsingContextImpl.getTimestamp(),
  5923. url,
  5924. },
  5925. }, this.id);
  5926. throw new protocol_js_1$9.UnknownErrorException(cdpNavigateResult.errorText);
  5927. }
  5928. this.#documentChanged(cdpNavigateResult.loaderId);
  5929. switch (wait) {
  5930. case "none" /* BrowsingContext.ReadinessState.None */:
  5931. break;
  5932. case "interactive" /* BrowsingContext.ReadinessState.Interactive */:
  5933. // No `loaderId` means same-document navigation.
  5934. if (cdpNavigateResult.loaderId === undefined) {
  5935. await this.#navigation.withinDocument;
  5936. }
  5937. else {
  5938. await this.#lifecycle.DOMContentLoaded;
  5939. }
  5940. break;
  5941. case "complete" /* BrowsingContext.ReadinessState.Complete */:
  5942. // No `loaderId` means same-document navigation.
  5943. if (cdpNavigateResult.loaderId === undefined) {
  5944. await this.#navigation.withinDocument;
  5945. }
  5946. else {
  5947. await this.#lifecycle.load;
  5948. }
  5949. break;
  5950. }
  5951. return {
  5952. navigation: cdpNavigateResult.loaderId ?? null,
  5953. // Url can change due to redirect get the latest one.
  5954. url: wait === "none" /* BrowsingContext.ReadinessState.None */ ? url : this.#url,
  5955. };
  5956. }
  5957. async reload(ignoreCache, wait) {
  5958. await this.targetUnblockedOrThrow();
  5959. this.#resetLifecycleIfFinished();
  5960. await this.#cdpTarget.cdpClient.sendCommand('Page.reload', {
  5961. ignoreCache,
  5962. });
  5963. switch (wait) {
  5964. case "none" /* BrowsingContext.ReadinessState.None */:
  5965. break;
  5966. case "interactive" /* BrowsingContext.ReadinessState.Interactive */:
  5967. await this.#lifecycle.DOMContentLoaded;
  5968. break;
  5969. case "complete" /* BrowsingContext.ReadinessState.Complete */:
  5970. await this.#lifecycle.load;
  5971. break;
  5972. }
  5973. return {
  5974. navigation: wait === "none" /* BrowsingContext.ReadinessState.None */
  5975. ? null
  5976. : this.navigableId ?? null,
  5977. url: this.url,
  5978. };
  5979. }
  5980. async setViewport(viewport, devicePixelRatio) {
  5981. if (viewport === null && devicePixelRatio === null) {
  5982. await this.#cdpTarget.cdpClient.sendCommand('Emulation.clearDeviceMetricsOverride');
  5983. }
  5984. else {
  5985. try {
  5986. let appliedViewport;
  5987. if (viewport === undefined) {
  5988. appliedViewport = this.#previousViewport;
  5989. }
  5990. else if (viewport === null) {
  5991. appliedViewport = {
  5992. width: 0,
  5993. height: 0,
  5994. };
  5995. }
  5996. else {
  5997. appliedViewport = viewport;
  5998. }
  5999. this.#previousViewport = appliedViewport;
  6000. await this.#cdpTarget.cdpClient.sendCommand('Emulation.setDeviceMetricsOverride', {
  6001. width: this.#previousViewport.width,
  6002. height: this.#previousViewport.height,
  6003. deviceScaleFactor: devicePixelRatio ? devicePixelRatio : 0,
  6004. mobile: false,
  6005. dontSetVisibleSize: true,
  6006. });
  6007. }
  6008. catch (err) {
  6009. if (err.message.startsWith(
  6010. // https://crsrc.org/c/content/browser/devtools/protocol/emulation_handler.cc;l=257;drc=2f6eee84cf98d4227e7c41718dd71b82f26d90ff
  6011. 'Width and height values must be positive')) {
  6012. throw new protocol_js_1$9.UnsupportedOperationException('Provided viewport dimensions are not supported');
  6013. }
  6014. throw err;
  6015. }
  6016. }
  6017. }
  6018. async handleUserPrompt(params) {
  6019. await this.#cdpTarget.cdpClient.sendCommand('Page.handleJavaScriptDialog', {
  6020. accept: params.accept ?? true,
  6021. promptText: params.userText,
  6022. });
  6023. }
  6024. async activate() {
  6025. await this.#cdpTarget.cdpClient.sendCommand('Page.bringToFront');
  6026. }
  6027. async captureScreenshot(params) {
  6028. if (!this.isTopLevelContext()) {
  6029. throw new protocol_js_1$9.UnsupportedOperationException(`Non-top-level 'context' (${params.context}) is currently not supported`);
  6030. }
  6031. const formatParameters = getImageFormatParameters(params);
  6032. // XXX: Focus the original tab after the screenshot is taken.
  6033. // This is needed because the screenshot gets blocked until the active tab gets focus.
  6034. await this.#cdpTarget.cdpClient.sendCommand('Page.bringToFront');
  6035. let captureBeyondViewport = false;
  6036. let script;
  6037. params.origin ??= 'viewport';
  6038. switch (params.origin) {
  6039. case 'document': {
  6040. script = String(() => {
  6041. const element = document.documentElement;
  6042. return {
  6043. x: 0,
  6044. y: 0,
  6045. width: element.scrollWidth,
  6046. height: element.scrollHeight,
  6047. };
  6048. });
  6049. captureBeyondViewport = true;
  6050. break;
  6051. }
  6052. case 'viewport': {
  6053. script = String(() => {
  6054. const viewport = window.visualViewport;
  6055. return {
  6056. x: viewport.pageLeft,
  6057. y: viewport.pageTop,
  6058. width: viewport.width,
  6059. height: viewport.height,
  6060. };
  6061. });
  6062. break;
  6063. }
  6064. }
  6065. const realm = await this.getOrCreateSandbox(undefined);
  6066. const originResult = await realm.callFunction(script, false);
  6067. (0, assert_js_1$2.assert)(originResult.type === 'success');
  6068. const origin = deserializeDOMRect(originResult.result);
  6069. (0, assert_js_1$2.assert)(origin);
  6070. const rect = params.clip
  6071. ? getIntersectionRect(await this.#parseRect(params.clip), origin)
  6072. : origin;
  6073. if (rect.width === 0 || rect.height === 0) {
  6074. throw new protocol_js_1$9.UnableToCaptureScreenException(`Unable to capture screenshot with zero dimensions: width=${rect.width}, height=${rect.height}`);
  6075. }
  6076. return await this.#cdpTarget.cdpClient.sendCommand('Page.captureScreenshot', {
  6077. clip: { ...rect, scale: 1.0 },
  6078. ...formatParameters,
  6079. captureBeyondViewport,
  6080. });
  6081. }
  6082. async print(params) {
  6083. const cdpParams = {};
  6084. if (params.background !== undefined) {
  6085. cdpParams.printBackground = params.background;
  6086. }
  6087. if (params.margin?.bottom !== undefined) {
  6088. cdpParams.marginBottom = (0, unitConversions_js_1.inchesFromCm)(params.margin.bottom);
  6089. }
  6090. if (params.margin?.left !== undefined) {
  6091. cdpParams.marginLeft = (0, unitConversions_js_1.inchesFromCm)(params.margin.left);
  6092. }
  6093. if (params.margin?.right !== undefined) {
  6094. cdpParams.marginRight = (0, unitConversions_js_1.inchesFromCm)(params.margin.right);
  6095. }
  6096. if (params.margin?.top !== undefined) {
  6097. cdpParams.marginTop = (0, unitConversions_js_1.inchesFromCm)(params.margin.top);
  6098. }
  6099. if (params.orientation !== undefined) {
  6100. cdpParams.landscape = params.orientation === 'landscape';
  6101. }
  6102. if (params.page?.height !== undefined) {
  6103. cdpParams.paperHeight = (0, unitConversions_js_1.inchesFromCm)(params.page.height);
  6104. }
  6105. if (params.page?.width !== undefined) {
  6106. cdpParams.paperWidth = (0, unitConversions_js_1.inchesFromCm)(params.page.width);
  6107. }
  6108. if (params.pageRanges !== undefined) {
  6109. for (const range of params.pageRanges) {
  6110. if (typeof range === 'number') {
  6111. continue;
  6112. }
  6113. const rangeParts = range.split('-');
  6114. if (rangeParts.length < 1 || rangeParts.length > 2) {
  6115. throw new protocol_js_1$9.InvalidArgumentException(`Invalid page range: ${range} is not a valid integer range.`);
  6116. }
  6117. if (rangeParts.length === 1) {
  6118. void parseInteger(rangeParts[0] ?? '');
  6119. continue;
  6120. }
  6121. let lowerBound;
  6122. let upperBound;
  6123. const [rangeLowerPart = '', rangeUpperPart = ''] = rangeParts;
  6124. if (rangeLowerPart === '') {
  6125. lowerBound = 1;
  6126. }
  6127. else {
  6128. lowerBound = parseInteger(rangeLowerPart);
  6129. }
  6130. if (rangeUpperPart === '') {
  6131. upperBound = Number.MAX_SAFE_INTEGER;
  6132. }
  6133. else {
  6134. upperBound = parseInteger(rangeUpperPart);
  6135. }
  6136. if (lowerBound > upperBound) {
  6137. throw new protocol_js_1$9.InvalidArgumentException(`Invalid page range: ${rangeLowerPart} > ${rangeUpperPart}`);
  6138. }
  6139. }
  6140. cdpParams.pageRanges = params.pageRanges.join(',');
  6141. }
  6142. if (params.scale !== undefined) {
  6143. cdpParams.scale = params.scale;
  6144. }
  6145. if (params.shrinkToFit !== undefined) {
  6146. cdpParams.preferCSSPageSize = !params.shrinkToFit;
  6147. }
  6148. try {
  6149. const result = await this.#cdpTarget.cdpClient.sendCommand('Page.printToPDF', cdpParams);
  6150. return {
  6151. data: result.data,
  6152. };
  6153. }
  6154. catch (error) {
  6155. // Effectively zero dimensions.
  6156. if (error.message ===
  6157. 'invalid print parameters: content area is empty') {
  6158. throw new protocol_js_1$9.UnsupportedOperationException(error.message);
  6159. }
  6160. throw error;
  6161. }
  6162. }
  6163. /**
  6164. * See
  6165. * https://w3c.github.io/webdriver-bidi/#:~:text=If%20command%20parameters%20contains%20%22clip%22%3A
  6166. */
  6167. async #parseRect(clip) {
  6168. switch (clip.type) {
  6169. case 'box':
  6170. return { x: clip.x, y: clip.y, width: clip.width, height: clip.height };
  6171. case 'element': {
  6172. // TODO: #1213: Use custom sandbox specifically for Chromium BiDi
  6173. const sandbox = await this.getOrCreateSandbox(undefined);
  6174. const result = await sandbox.callFunction(String((element) => {
  6175. return element instanceof Element;
  6176. }), false, { type: 'undefined' }, [clip.element]);
  6177. if (result.type === 'exception') {
  6178. throw new protocol_js_1$9.NoSuchElementException(`Element '${clip.element.sharedId}' was not found`);
  6179. }
  6180. (0, assert_js_1$2.assert)(result.result.type === 'boolean');
  6181. if (!result.result.value) {
  6182. throw new protocol_js_1$9.NoSuchElementException(`Node '${clip.element.sharedId}' is not an Element`);
  6183. }
  6184. {
  6185. const result = await sandbox.callFunction(String((element) => {
  6186. const rect = element.getBoundingClientRect();
  6187. return {
  6188. x: rect.x,
  6189. y: rect.y,
  6190. height: rect.height,
  6191. width: rect.width,
  6192. };
  6193. }), false, { type: 'undefined' }, [clip.element]);
  6194. (0, assert_js_1$2.assert)(result.type === 'success');
  6195. const rect = deserializeDOMRect(result.result);
  6196. if (!rect) {
  6197. throw new protocol_js_1$9.UnableToCaptureScreenException(`Could not get bounding box for Element '${clip.element.sharedId}'`);
  6198. }
  6199. return rect;
  6200. }
  6201. }
  6202. }
  6203. }
  6204. async close() {
  6205. await this.#cdpTarget.cdpClient.sendCommand('Page.close');
  6206. }
  6207. async traverseHistory(delta) {
  6208. if (delta === 0) {
  6209. return;
  6210. }
  6211. const history = await this.#cdpTarget.cdpClient.sendCommand('Page.getNavigationHistory');
  6212. const entry = history.entries[history.currentIndex + delta];
  6213. if (!entry) {
  6214. throw new protocol_js_1$9.NoSuchHistoryEntryException(`No history entry at delta ${delta}`);
  6215. }
  6216. await this.#cdpTarget.cdpClient.sendCommand('Page.navigateToHistoryEntry', {
  6217. entryId: entry.id,
  6218. });
  6219. }
  6220. async toggleModulesIfNeeded() {
  6221. await this.#cdpTarget.toggleNetworkIfNeeded();
  6222. }
  6223. async locateNodes(params) {
  6224. // TODO: create a dedicated sandbox instead of `#defaultRealm`.
  6225. return await this.#locateNodesByLocator(this.#defaultRealm, params.locator, params.startNodes ?? [], params.maxNodeCount, params.serializationOptions);
  6226. }
  6227. #getLocatorDelegate(locator, maxNodeCount, startNodes) {
  6228. switch (locator.type) {
  6229. case 'css':
  6230. return {
  6231. functionDeclaration: String((cssSelector, maxNodeCount, ...startNodes) => {
  6232. const locateNodesUsingCss = (element) => {
  6233. if (!(element instanceof HTMLElement)) {
  6234. throw new Error('startNodes in css selector should be HTMLElement');
  6235. }
  6236. return [...element.querySelectorAll(cssSelector)];
  6237. };
  6238. startNodes = startNodes.length > 0 ? startNodes : [document.body];
  6239. const returnedNodes = startNodes
  6240. .map((startNode) =>
  6241. // TODO: stop search early if `maxNodeCount` is reached.
  6242. locateNodesUsingCss(startNode))
  6243. .flat(1);
  6244. return maxNodeCount === 0
  6245. ? returnedNodes
  6246. : returnedNodes.slice(0, maxNodeCount);
  6247. }),
  6248. argumentsLocalValues: [
  6249. // `cssSelector`
  6250. { type: 'string', value: locator.value },
  6251. // `maxNodeCount` with `0` means no limit.
  6252. { type: 'number', value: maxNodeCount ?? 0 },
  6253. // `startNodes`
  6254. ...startNodes,
  6255. ],
  6256. };
  6257. case 'xpath':
  6258. return {
  6259. functionDeclaration: String((xPathSelector, maxNodeCount, ...startNodes) => {
  6260. // https://w3c.github.io/webdriver-bidi/#locate-nodes-using-xpath
  6261. const evaluator = new XPathEvaluator();
  6262. const expression = evaluator.createExpression(xPathSelector);
  6263. const locateNodesUsingXpath = (element) => {
  6264. const xPathResult = expression.evaluate(element, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
  6265. const returnedNodes = [];
  6266. for (let i = 0; i < xPathResult.snapshotLength; i++) {
  6267. returnedNodes.push(xPathResult.snapshotItem(i));
  6268. }
  6269. return returnedNodes;
  6270. };
  6271. startNodes = startNodes.length > 0 ? startNodes : [document.body];
  6272. const returnedNodes = startNodes
  6273. .map((startNode) =>
  6274. // TODO: stop search early if `maxNodeCount` is reached.
  6275. locateNodesUsingXpath(startNode))
  6276. .flat(1);
  6277. return maxNodeCount === 0
  6278. ? returnedNodes
  6279. : returnedNodes.slice(0, maxNodeCount);
  6280. }),
  6281. argumentsLocalValues: [
  6282. // `xPathSelector`
  6283. { type: 'string', value: locator.value },
  6284. // `maxNodeCount` with `0` means no limit.
  6285. { type: 'number', value: maxNodeCount ?? 0 },
  6286. // `startNodes`
  6287. ...startNodes,
  6288. ],
  6289. };
  6290. case 'innerText':
  6291. // https://w3c.github.io/webdriver-bidi/#locate-nodes-using-inner-text
  6292. if (locator.value === '') {
  6293. throw new protocol_js_1$9.InvalidSelectorException('innerText locator cannot be empty');
  6294. }
  6295. return {
  6296. functionDeclaration: String((innerTextSelector, fullMatch, ignoreCase, maxNodeCount, maxDepth, ...startNodes) => {
  6297. const searchText = ignoreCase
  6298. ? innerTextSelector.toUpperCase()
  6299. : innerTextSelector;
  6300. const locateNodesUsingInnerText = (element, currentMaxDepth) => {
  6301. const returnedNodes = [];
  6302. const nodeInnerText = ignoreCase
  6303. ? element.innerText?.toUpperCase()
  6304. : element.innerText;
  6305. if (!nodeInnerText.includes(searchText)) {
  6306. return [];
  6307. }
  6308. const childNodes = [];
  6309. for (const child of element.children) {
  6310. if (child instanceof HTMLElement) {
  6311. childNodes.push(child);
  6312. }
  6313. }
  6314. if (childNodes.length === 0) {
  6315. if (fullMatch && nodeInnerText === searchText) {
  6316. returnedNodes.push(element);
  6317. }
  6318. else {
  6319. if (!fullMatch) {
  6320. // Note: `nodeInnerText.includes(searchText)` is already checked
  6321. returnedNodes.push(element);
  6322. }
  6323. }
  6324. }
  6325. else {
  6326. const childNodeMatches =
  6327. // Don't search deeper if `maxDepth` is reached.
  6328. currentMaxDepth === 0
  6329. ? []
  6330. : childNodes
  6331. .map((child) => locateNodesUsingInnerText(child, currentMaxDepth - 1))
  6332. .flat(1);
  6333. if (childNodeMatches.length === 0) {
  6334. // Note: `nodeInnerText.includes(searchText)` is already checked
  6335. if (!fullMatch || nodeInnerText === searchText) {
  6336. returnedNodes.push(element);
  6337. }
  6338. }
  6339. else {
  6340. returnedNodes.push(...childNodeMatches);
  6341. }
  6342. }
  6343. // TODO: stop search early if `maxNodeCount` is reached.
  6344. return returnedNodes;
  6345. };
  6346. // TODO: add maxDepth.
  6347. // TODO: stop search early if `maxNodeCount` is reached.
  6348. startNodes = startNodes.length > 0 ? startNodes : [document.body];
  6349. const returnedNodes = startNodes
  6350. .map((startNode) =>
  6351. // TODO: stop search early if `maxNodeCount` is reached.
  6352. locateNodesUsingInnerText(startNode, maxDepth))
  6353. .flat(1);
  6354. return maxNodeCount === 0
  6355. ? returnedNodes
  6356. : returnedNodes.slice(0, maxNodeCount);
  6357. }),
  6358. argumentsLocalValues: [
  6359. // `innerTextSelector`
  6360. { type: 'string', value: locator.value },
  6361. // `fullMatch` with default `true`.
  6362. { type: 'boolean', value: locator.matchType !== 'partial' },
  6363. // `ignoreCase` with default `false`.
  6364. { type: 'boolean', value: locator.ignoreCase === true },
  6365. // `maxNodeCount` with `0` means no limit.
  6366. { type: 'number', value: maxNodeCount ?? 0 },
  6367. // `maxDepth` with default `1000` (same as default full serialization depth).
  6368. { type: 'number', value: locator.maxDepth ?? 1000 },
  6369. // `startNodes`
  6370. ...startNodes,
  6371. ],
  6372. };
  6373. }
  6374. }
  6375. async #locateNodesByLocator(realm, locator, startNodes, maxNodeCount, serializationOptions) {
  6376. const locatorDelegate = this.#getLocatorDelegate(locator, maxNodeCount, startNodes);
  6377. serializationOptions = {
  6378. ...serializationOptions,
  6379. // The returned object is an array of nodes, so no need in deeper JS serialization.
  6380. maxObjectDepth: 1,
  6381. };
  6382. const locatorResult = await realm.callFunction(locatorDelegate.functionDeclaration, false, { type: 'undefined' }, locatorDelegate.argumentsLocalValues, "none" /* Script.ResultOwnership.None */, serializationOptions);
  6383. if (locatorResult.type !== 'success') {
  6384. this.#logger?.(BrowsingContextImpl.LOGGER_PREFIX, 'Failed locateNodesByLocator', locatorResult);
  6385. // Heuristic to detect invalid selector for different types of selectors.
  6386. if (
  6387. // CSS selector.
  6388. locatorResult.exceptionDetails.text?.endsWith('is not a valid selector.') ||
  6389. // XPath selector.
  6390. locatorResult.exceptionDetails.text?.endsWith('is not a valid XPath expression.')) {
  6391. throw new protocol_js_1$9.InvalidSelectorException(`Not valid selector ${locator.value}`);
  6392. }
  6393. // Heuristic to detect if the `startNode` is not an `HTMLElement` in css selector.
  6394. if (locatorResult.exceptionDetails.text ===
  6395. 'Error: startNodes in css selector should be HTMLElement') {
  6396. throw new protocol_js_1$9.InvalidArgumentException(`startNodes in css selector should be HTMLElement`);
  6397. }
  6398. throw new protocol_js_1$9.UnknownErrorException(`Unexpected error in selector script: ${locatorResult.exceptionDetails.text}`);
  6399. }
  6400. if (locatorResult.result.type !== 'array') {
  6401. throw new protocol_js_1$9.UnknownErrorException(`Unexpected selector script result type: ${locatorResult.result.type}`);
  6402. }
  6403. // Check there are no non-node elements in the result.
  6404. const nodes = locatorResult.result.value.map((value) => {
  6405. if (value.type !== 'node') {
  6406. throw new protocol_js_1$9.UnknownErrorException(`Unexpected selector script result element: ${value.type}`);
  6407. }
  6408. return value;
  6409. });
  6410. return { nodes };
  6411. }
  6412. }
  6413. BrowsingContextImpl$1.BrowsingContextImpl = BrowsingContextImpl;
  6414. function serializeOrigin(origin) {
  6415. // https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin
  6416. if (['://', ''].includes(origin)) {
  6417. origin = 'null';
  6418. }
  6419. return origin;
  6420. }
  6421. BrowsingContextImpl$1.serializeOrigin = serializeOrigin;
  6422. function getImageFormatParameters(params) {
  6423. const { quality, type } = params.format ?? {
  6424. type: 'image/png',
  6425. };
  6426. switch (type) {
  6427. case 'image/png': {
  6428. return { format: 'png' };
  6429. }
  6430. case 'image/jpeg': {
  6431. return {
  6432. format: 'jpeg',
  6433. ...(quality === undefined ? {} : { quality: Math.round(quality * 100) }),
  6434. };
  6435. }
  6436. case 'image/webp': {
  6437. return {
  6438. format: 'webp',
  6439. ...(quality === undefined ? {} : { quality: Math.round(quality * 100) }),
  6440. };
  6441. }
  6442. }
  6443. throw new protocol_js_1$9.InvalidArgumentException(`Image format '${type}' is not a supported format`);
  6444. }
  6445. function deserializeDOMRect(result) {
  6446. if (result.type !== 'object' || result.value === undefined) {
  6447. return;
  6448. }
  6449. const x = result.value.find(([key]) => {
  6450. return key === 'x';
  6451. })?.[1];
  6452. const y = result.value.find(([key]) => {
  6453. return key === 'y';
  6454. })?.[1];
  6455. const height = result.value.find(([key]) => {
  6456. return key === 'height';
  6457. })?.[1];
  6458. const width = result.value.find(([key]) => {
  6459. return key === 'width';
  6460. })?.[1];
  6461. if (x?.type !== 'number' ||
  6462. y?.type !== 'number' ||
  6463. height?.type !== 'number' ||
  6464. width?.type !== 'number') {
  6465. return;
  6466. }
  6467. return {
  6468. x: x.value,
  6469. y: y.value,
  6470. width: width.value,
  6471. height: height.value,
  6472. };
  6473. }
  6474. /** @see https://w3c.github.io/webdriver-bidi/#normalize-rect */
  6475. function normalizeRect(box) {
  6476. return {
  6477. ...(box.width < 0
  6478. ? {
  6479. x: box.x + box.width,
  6480. width: -box.width,
  6481. }
  6482. : {
  6483. x: box.x,
  6484. width: box.width,
  6485. }),
  6486. ...(box.height < 0
  6487. ? {
  6488. y: box.y + box.height,
  6489. height: -box.height,
  6490. }
  6491. : {
  6492. y: box.y,
  6493. height: box.height,
  6494. }),
  6495. };
  6496. }
  6497. /** @see https://w3c.github.io/webdriver-bidi/#rectangle-intersection */
  6498. function getIntersectionRect(first, second) {
  6499. first = normalizeRect(first);
  6500. second = normalizeRect(second);
  6501. const x = Math.max(first.x, second.x);
  6502. const y = Math.max(first.y, second.y);
  6503. return {
  6504. x,
  6505. y,
  6506. width: Math.max(Math.min(first.x + first.width, second.x + second.width) - x, 0),
  6507. height: Math.max(Math.min(first.y + first.height, second.y + second.height) - y, 0),
  6508. };
  6509. }
  6510. function parseInteger(value) {
  6511. value = value.trim();
  6512. if (!/^[0-9]+$/.test(value)) {
  6513. throw new protocol_js_1$9.InvalidArgumentException(`Invalid integer: ${value}`);
  6514. }
  6515. return parseInt(value);
  6516. }
  6517. var WorkerRealm$1 = {};
  6518. /**
  6519. * Copyright 2024 Google LLC.
  6520. * Copyright (c) Microsoft Corporation.
  6521. *
  6522. * Licensed under the Apache License, Version 2.0 (the "License");
  6523. * you may not use this file except in compliance with the License.
  6524. * You may obtain a copy of the License at
  6525. *
  6526. * http://www.apache.org/licenses/LICENSE-2.0
  6527. *
  6528. * Unless required by applicable law or agreed to in writing, software
  6529. * distributed under the License is distributed on an "AS IS" BASIS,
  6530. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6531. * See the License for the specific language governing permissions and
  6532. * limitations under the License.
  6533. */
  6534. Object.defineProperty(WorkerRealm$1, "__esModule", { value: true });
  6535. WorkerRealm$1.WorkerRealm = void 0;
  6536. const Realm_js_1 = Realm$1;
  6537. class WorkerRealm extends Realm_js_1.Realm {
  6538. #realmType;
  6539. #ownerRealms;
  6540. constructor(cdpClient, eventManager, executionContextId, logger, origin, ownerRealms, realmId, realmStorage, realmType) {
  6541. super(cdpClient, eventManager, executionContextId, logger, origin, realmId, realmStorage);
  6542. this.#ownerRealms = ownerRealms;
  6543. this.#realmType = realmType;
  6544. this.initialize();
  6545. }
  6546. get associatedBrowsingContexts() {
  6547. return this.#ownerRealms.flatMap((realm) => realm.associatedBrowsingContexts);
  6548. }
  6549. get realmType() {
  6550. return this.#realmType;
  6551. }
  6552. get source() {
  6553. return {
  6554. realm: this.realmId,
  6555. // This is a hack to make Puppeteer able to track workers.
  6556. // TODO: remove after Puppeteer tracks workers by owners and use the base version.
  6557. context: this.associatedBrowsingContexts[0]?.id,
  6558. };
  6559. }
  6560. get realmInfo() {
  6561. const owners = this.#ownerRealms.map((realm) => realm.realmId);
  6562. const { realmType } = this;
  6563. switch (realmType) {
  6564. case 'dedicated-worker': {
  6565. const owner = owners[0];
  6566. if (owner === undefined || owners.length !== 1) {
  6567. throw new Error('Dedicated worker must have exactly one owner');
  6568. }
  6569. return {
  6570. ...this.baseInfo,
  6571. type: realmType,
  6572. owners: [owner],
  6573. };
  6574. }
  6575. case 'service-worker':
  6576. case 'shared-worker': {
  6577. return {
  6578. ...this.baseInfo,
  6579. type: realmType,
  6580. };
  6581. }
  6582. }
  6583. }
  6584. }
  6585. WorkerRealm$1.WorkerRealm = WorkerRealm;
  6586. var CdpTarget$1 = {};
  6587. var LogManager$1 = {};
  6588. var logHelper = {};
  6589. /**
  6590. * Copyright 2022 Google LLC.
  6591. * Copyright (c) Microsoft Corporation.
  6592. *
  6593. * Licensed under the Apache License, Version 2.0 (the "License");
  6594. * you may not use this file except in compliance with the License.
  6595. * You may obtain a copy of the License at
  6596. *
  6597. * http://www.apache.org/licenses/LICENSE-2.0
  6598. *
  6599. * Unless required by applicable law or agreed to in writing, software
  6600. * distributed under the License is distributed on an "AS IS" BASIS,
  6601. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6602. * See the License for the specific language governing permissions and
  6603. * limitations under the License.
  6604. */
  6605. Object.defineProperty(logHelper, "__esModule", { value: true });
  6606. logHelper.getRemoteValuesText = logHelper.logMessageFormatter = void 0;
  6607. const assert_js_1$1 = assert$1;
  6608. const specifiers = ['%s', '%d', '%i', '%f', '%o', '%O', '%c'];
  6609. function isFormatSpecifier(str) {
  6610. return specifiers.some((spec) => str.includes(spec));
  6611. }
  6612. /**
  6613. * @param args input remote values to be format printed
  6614. * @return parsed text of the remote values in specific format
  6615. */
  6616. function logMessageFormatter(args) {
  6617. let output = '';
  6618. const argFormat = args[0].value.toString();
  6619. const argValues = args.slice(1, undefined);
  6620. const tokens = argFormat.split(new RegExp(specifiers.map((spec) => `(${spec})`).join('|'), 'g'));
  6621. for (const token of tokens) {
  6622. if (token === undefined || token === '') {
  6623. continue;
  6624. }
  6625. if (isFormatSpecifier(token)) {
  6626. const arg = argValues.shift();
  6627. // raise an exception when less value is provided
  6628. (0, assert_js_1$1.assert)(arg, `Less value is provided: "${getRemoteValuesText(args, false)}"`);
  6629. if (token === '%s') {
  6630. output += stringFromArg(arg);
  6631. }
  6632. else if (token === '%d' || token === '%i') {
  6633. if (arg.type === 'bigint' ||
  6634. arg.type === 'number' ||
  6635. arg.type === 'string') {
  6636. output += parseInt(arg.value.toString(), 10);
  6637. }
  6638. else {
  6639. output += 'NaN';
  6640. }
  6641. }
  6642. else if (token === '%f') {
  6643. if (arg.type === 'bigint' ||
  6644. arg.type === 'number' ||
  6645. arg.type === 'string') {
  6646. output += parseFloat(arg.value.toString());
  6647. }
  6648. else {
  6649. output += 'NaN';
  6650. }
  6651. }
  6652. else {
  6653. // %o, %O, %c
  6654. output += toJson(arg);
  6655. }
  6656. }
  6657. else {
  6658. output += token;
  6659. }
  6660. }
  6661. // raise an exception when more value is provided
  6662. if (argValues.length > 0) {
  6663. throw new Error(`More value is provided: "${getRemoteValuesText(args, false)}"`);
  6664. }
  6665. return output;
  6666. }
  6667. logHelper.logMessageFormatter = logMessageFormatter;
  6668. /**
  6669. * @param arg input remote value to be parsed
  6670. * @return parsed text of the remote value
  6671. *
  6672. * input: {"type": "number", "value": 1}
  6673. * output: 1
  6674. *
  6675. * input: {"type": "string", "value": "abc"}
  6676. * output: "abc"
  6677. *
  6678. * input: {"type": "object", "value": [["id", {"type": "number", "value": 1}]]}
  6679. * output: '{"id": 1}'
  6680. *
  6681. * input: {"type": "object", "value": [["font-size", {"type": "string", "value": "20px"}]]}
  6682. * output: '{"font-size": "20px"}'
  6683. */
  6684. function toJson(arg) {
  6685. // arg type validation
  6686. if (arg.type !== 'array' &&
  6687. arg.type !== 'bigint' &&
  6688. arg.type !== 'date' &&
  6689. arg.type !== 'number' &&
  6690. arg.type !== 'object' &&
  6691. arg.type !== 'string') {
  6692. return stringFromArg(arg);
  6693. }
  6694. if (arg.type === 'bigint') {
  6695. return `${arg.value.toString()}n`;
  6696. }
  6697. if (arg.type === 'number') {
  6698. return arg.value.toString();
  6699. }
  6700. if (['date', 'string'].includes(arg.type)) {
  6701. return JSON.stringify(arg.value);
  6702. }
  6703. if (arg.type === 'object') {
  6704. return `{${arg.value
  6705. .map((pair) => {
  6706. return `${JSON.stringify(pair[0])}:${toJson(pair[1])}`;
  6707. })
  6708. .join(',')}}`;
  6709. }
  6710. if (arg.type === 'array') {
  6711. return `[${arg.value?.map((val) => toJson(val)).join(',') ?? ''}]`;
  6712. }
  6713. // eslint-disable-next-line @typescript-eslint/no-base-to-string
  6714. throw Error(`Invalid value type: ${arg}`);
  6715. }
  6716. function stringFromArg(arg) {
  6717. if (!Object.hasOwn(arg, 'value')) {
  6718. return arg.type;
  6719. }
  6720. switch (arg.type) {
  6721. case 'string':
  6722. case 'number':
  6723. case 'boolean':
  6724. case 'bigint':
  6725. return String(arg.value);
  6726. case 'regexp':
  6727. return `/${arg.value.pattern}/${arg.value.flags ?? ''}`;
  6728. case 'date':
  6729. return new Date(arg.value).toString();
  6730. case 'object':
  6731. return `Object(${arg.value?.length ?? ''})`;
  6732. case 'array':
  6733. return `Array(${arg.value?.length ?? ''})`;
  6734. case 'map':
  6735. return `Map(${arg.value?.length})`;
  6736. case 'set':
  6737. return `Set(${arg.value?.length})`;
  6738. default:
  6739. return arg.type;
  6740. }
  6741. }
  6742. function getRemoteValuesText(args, formatText) {
  6743. const arg = args[0];
  6744. if (!arg) {
  6745. return '';
  6746. }
  6747. // if args[0] is a format specifier, format the args as output
  6748. if (arg.type === 'string' &&
  6749. isFormatSpecifier(arg.value.toString()) &&
  6750. formatText) {
  6751. return logMessageFormatter(args);
  6752. }
  6753. // if args[0] is not a format specifier, just join the args with \u0020 (unicode 'SPACE')
  6754. return args
  6755. .map((arg) => {
  6756. return stringFromArg(arg);
  6757. })
  6758. .join('\u0020');
  6759. }
  6760. logHelper.getRemoteValuesText = getRemoteValuesText;
  6761. Object.defineProperty(LogManager$1, "__esModule", { value: true });
  6762. LogManager$1.LogManager = void 0;
  6763. const protocol_js_1$8 = protocol;
  6764. const log_js_1$7 = log$1;
  6765. const logHelper_js_1 = logHelper;
  6766. /** Converts CDP StackTrace object to BiDi StackTrace object. */
  6767. function getBidiStackTrace(cdpStackTrace) {
  6768. const stackFrames = cdpStackTrace?.callFrames.map((callFrame) => {
  6769. return {
  6770. columnNumber: callFrame.columnNumber,
  6771. functionName: callFrame.functionName,
  6772. lineNumber: callFrame.lineNumber,
  6773. url: callFrame.url,
  6774. };
  6775. });
  6776. return stackFrames ? { callFrames: stackFrames } : undefined;
  6777. }
  6778. function getLogLevel(consoleApiType) {
  6779. if (["error" /* Log.Level.Error */, 'assert'].includes(consoleApiType)) {
  6780. return "error" /* Log.Level.Error */;
  6781. }
  6782. if (["debug" /* Log.Level.Debug */, 'trace'].includes(consoleApiType)) {
  6783. return "debug" /* Log.Level.Debug */;
  6784. }
  6785. if (["warn" /* Log.Level.Warn */, 'warning'].includes(consoleApiType)) {
  6786. return "warn" /* Log.Level.Warn */;
  6787. }
  6788. return "info" /* Log.Level.Info */;
  6789. }
  6790. class LogManager {
  6791. #eventManager;
  6792. #realmStorage;
  6793. #cdpTarget;
  6794. #logger;
  6795. constructor(cdpTarget, realmStorage, eventManager, logger) {
  6796. this.#cdpTarget = cdpTarget;
  6797. this.#realmStorage = realmStorage;
  6798. this.#eventManager = eventManager;
  6799. this.#logger = logger;
  6800. }
  6801. static create(cdpTarget, realmStorage, eventManager, logger) {
  6802. const logManager = new LogManager(cdpTarget, realmStorage, eventManager, logger);
  6803. logManager.#initializeEntryAddedEventListener();
  6804. return logManager;
  6805. }
  6806. #initializeEntryAddedEventListener() {
  6807. this.#cdpTarget.cdpClient.on('Runtime.consoleAPICalled', (params) => {
  6808. // Try to find realm by `cdpSessionId` and `executionContextId`,
  6809. // if provided.
  6810. const realm = this.#realmStorage.findRealm({
  6811. cdpSessionId: this.#cdpTarget.cdpSessionId,
  6812. executionContextId: params.executionContextId,
  6813. });
  6814. if (realm === undefined) {
  6815. // Ignore exceptions not attached to any realm.
  6816. this.#logger?.(log_js_1$7.LogType.cdp, params);
  6817. return;
  6818. }
  6819. const argsPromise = realm === undefined
  6820. ? Promise.resolve(params.args)
  6821. : // Properly serialize arguments if possible.
  6822. Promise.all(params.args.map((arg) => {
  6823. return realm.serializeCdpObject(arg, "none" /* Script.ResultOwnership.None */);
  6824. }));
  6825. for (const browsingContext of realm.associatedBrowsingContexts) {
  6826. this.#eventManager.registerPromiseEvent(argsPromise.then((args) => ({
  6827. kind: 'success',
  6828. value: {
  6829. type: 'event',
  6830. method: protocol_js_1$8.ChromiumBidi.Log.EventNames.LogEntryAdded,
  6831. params: {
  6832. level: getLogLevel(params.type),
  6833. source: realm.source,
  6834. text: (0, logHelper_js_1.getRemoteValuesText)(args, true),
  6835. timestamp: Math.round(params.timestamp),
  6836. stackTrace: getBidiStackTrace(params.stackTrace),
  6837. type: 'console',
  6838. // Console method is `warn`, not `warning`.
  6839. method: params.type === 'warning' ? 'warn' : params.type,
  6840. args,
  6841. },
  6842. },
  6843. })), browsingContext.id, protocol_js_1$8.ChromiumBidi.Log.EventNames.LogEntryAdded);
  6844. }
  6845. });
  6846. this.#cdpTarget.cdpClient.on('Runtime.exceptionThrown', (params) => {
  6847. // Try to find realm by `cdpSessionId` and `executionContextId`,
  6848. // if provided.
  6849. const realm = this.#realmStorage.findRealm({
  6850. cdpSessionId: this.#cdpTarget.cdpSessionId,
  6851. executionContextId: params.exceptionDetails.executionContextId,
  6852. });
  6853. if (realm === undefined) {
  6854. // Ignore exceptions not attached to any realm.
  6855. this.#logger?.(log_js_1$7.LogType.cdp, params);
  6856. return;
  6857. }
  6858. for (const browsingContext of realm.associatedBrowsingContexts) {
  6859. this.#eventManager.registerPromiseEvent(LogManager.#getExceptionText(params, realm).then((text) => ({
  6860. kind: 'success',
  6861. value: {
  6862. type: 'event',
  6863. method: protocol_js_1$8.ChromiumBidi.Log.EventNames.LogEntryAdded,
  6864. params: {
  6865. level: "error" /* Log.Level.Error */,
  6866. source: realm.source,
  6867. text,
  6868. timestamp: Math.round(params.timestamp),
  6869. stackTrace: getBidiStackTrace(params.exceptionDetails.stackTrace),
  6870. type: 'javascript',
  6871. },
  6872. },
  6873. })), browsingContext.id, protocol_js_1$8.ChromiumBidi.Log.EventNames.LogEntryAdded);
  6874. }
  6875. });
  6876. }
  6877. /**
  6878. * Try the best to get the exception text.
  6879. */
  6880. static async #getExceptionText(params, realm) {
  6881. if (!params.exceptionDetails.exception) {
  6882. return params.exceptionDetails.text;
  6883. }
  6884. if (realm === undefined) {
  6885. return JSON.stringify(params.exceptionDetails.exception);
  6886. }
  6887. return await realm.stringifyObject(params.exceptionDetails.exception);
  6888. }
  6889. }
  6890. LogManager$1.LogManager = LogManager;
  6891. Object.defineProperty(CdpTarget$1, "__esModule", { value: true });
  6892. CdpTarget$1.CdpTarget = void 0;
  6893. const chromium_bidi_js_1 = chromiumBidi;
  6894. const Deferred_js_1$1 = Deferred$1;
  6895. const LogManager_js_1 = LogManager$1;
  6896. class CdpTarget {
  6897. #id;
  6898. #cdpClient;
  6899. #browserCdpClient;
  6900. #eventManager;
  6901. #preloadScriptStorage;
  6902. #browsingContextStorage;
  6903. #networkStorage;
  6904. #unblocked = new Deferred_js_1$1.Deferred();
  6905. #acceptInsecureCerts;
  6906. #networkDomainEnabled = false;
  6907. #fetchDomainStages = {
  6908. request: false,
  6909. response: false,
  6910. auth: false,
  6911. };
  6912. static create(targetId, cdpClient, browserCdpClient, realmStorage, eventManager, preloadScriptStorage, browsingContextStorage, networkStorage, acceptInsecureCerts, logger) {
  6913. const cdpTarget = new CdpTarget(targetId, cdpClient, browserCdpClient, eventManager, preloadScriptStorage, browsingContextStorage, networkStorage, acceptInsecureCerts);
  6914. LogManager_js_1.LogManager.create(cdpTarget, realmStorage, eventManager, logger);
  6915. cdpTarget.#setEventListeners();
  6916. // No need to await.
  6917. // Deferred will be resolved when the target is unblocked.
  6918. void cdpTarget.#unblock();
  6919. return cdpTarget;
  6920. }
  6921. constructor(targetId, cdpClient, browserCdpClient, eventManager, preloadScriptStorage, browsingContextStorage, networkStorage, acceptInsecureCerts) {
  6922. this.#id = targetId;
  6923. this.#cdpClient = cdpClient;
  6924. this.#browserCdpClient = browserCdpClient;
  6925. this.#eventManager = eventManager;
  6926. this.#preloadScriptStorage = preloadScriptStorage;
  6927. this.#networkStorage = networkStorage;
  6928. this.#browsingContextStorage = browsingContextStorage;
  6929. this.#acceptInsecureCerts = acceptInsecureCerts;
  6930. }
  6931. /** Returns a deferred that resolves when the target is unblocked. */
  6932. get unblocked() {
  6933. return this.#unblocked;
  6934. }
  6935. get id() {
  6936. return this.#id;
  6937. }
  6938. get cdpClient() {
  6939. return this.#cdpClient;
  6940. }
  6941. get browserCdpClient() {
  6942. return this.#browserCdpClient;
  6943. }
  6944. /** Needed for CDP escape path. */
  6945. get cdpSessionId() {
  6946. // SAFETY we got the client by it's id for creating
  6947. return this.#cdpClient.sessionId;
  6948. }
  6949. /**
  6950. * Enables all the required CDP domains and unblocks the target.
  6951. */
  6952. async #unblock() {
  6953. try {
  6954. await Promise.all([
  6955. this.#cdpClient.sendCommand('Runtime.enable'),
  6956. this.#cdpClient.sendCommand('Page.enable'),
  6957. this.#cdpClient.sendCommand('Page.setLifecycleEventsEnabled', {
  6958. enabled: true,
  6959. }),
  6960. // Set ignore certificate errors for each target.
  6961. this.#cdpClient.sendCommand('Security.setIgnoreCertificateErrors', {
  6962. ignore: this.#acceptInsecureCerts,
  6963. }),
  6964. this.toggleNetworkIfNeeded(),
  6965. this.#cdpClient.sendCommand('Target.setAutoAttach', {
  6966. autoAttach: true,
  6967. waitForDebuggerOnStart: true,
  6968. flatten: true,
  6969. }),
  6970. this.#initAndEvaluatePreloadScripts(),
  6971. this.#cdpClient.sendCommand('Runtime.runIfWaitingForDebugger'),
  6972. ]);
  6973. }
  6974. catch (error) {
  6975. // The target might have been closed before the initialization finished.
  6976. if (!this.#cdpClient.isCloseError(error)) {
  6977. this.#unblocked.resolve({
  6978. kind: 'error',
  6979. error,
  6980. });
  6981. return;
  6982. }
  6983. }
  6984. this.#unblocked.resolve({
  6985. kind: 'success',
  6986. value: undefined,
  6987. });
  6988. }
  6989. async toggleFetchIfNeeded() {
  6990. const stages = this.#networkStorage.getInterceptionStages(this.topLevelId);
  6991. if (
  6992. // Only toggle interception when Network is enabled
  6993. !this.#networkDomainEnabled ||
  6994. (this.#fetchDomainStages.request === stages.request &&
  6995. this.#fetchDomainStages.response === stages.response &&
  6996. this.#fetchDomainStages.auth === stages.auth)) {
  6997. return;
  6998. }
  6999. const patterns = [];
  7000. this.#fetchDomainStages = stages;
  7001. if (stages.request || stages.auth) {
  7002. // CDP quirk we need request interception when we intercept auth
  7003. patterns.push({
  7004. urlPattern: '*',
  7005. requestStage: 'Request',
  7006. });
  7007. }
  7008. if (stages.response) {
  7009. patterns.push({
  7010. urlPattern: '*',
  7011. requestStage: 'Response',
  7012. });
  7013. }
  7014. if (patterns.length) {
  7015. await this.#cdpClient.sendCommand('Fetch.enable', {
  7016. patterns,
  7017. handleAuthRequests: stages.auth,
  7018. });
  7019. }
  7020. else {
  7021. await this.#cdpClient.sendCommand('Fetch.disable');
  7022. }
  7023. }
  7024. /**
  7025. * Toggles both Network and Fetch domains.
  7026. */
  7027. async toggleNetworkIfNeeded() {
  7028. const enabled = this.isSubscribedTo(chromium_bidi_js_1.BiDiModule.Network);
  7029. if (enabled === this.#networkDomainEnabled) {
  7030. return;
  7031. }
  7032. this.#networkDomainEnabled = enabled;
  7033. try {
  7034. await Promise.all([
  7035. this.#cdpClient.sendCommand(enabled ? 'Network.enable' : 'Network.disable'),
  7036. this.toggleFetchIfNeeded(),
  7037. ]);
  7038. }
  7039. catch (err) {
  7040. this.#networkDomainEnabled = !enabled;
  7041. }
  7042. }
  7043. #setEventListeners() {
  7044. this.#cdpClient.on('*', (event, params) => {
  7045. // We may encounter uses for EventEmitter other than CDP events,
  7046. // which we want to skip.
  7047. if (typeof event !== 'string') {
  7048. return;
  7049. }
  7050. this.#eventManager.registerEvent({
  7051. type: 'event',
  7052. method: `cdp.${event}`,
  7053. params: {
  7054. event,
  7055. params,
  7056. session: this.cdpSessionId,
  7057. },
  7058. }, this.id);
  7059. });
  7060. }
  7061. /**
  7062. * All the ProxyChannels from all the preload scripts of the given
  7063. * BrowsingContext.
  7064. */
  7065. getChannels() {
  7066. return this.#preloadScriptStorage
  7067. .find()
  7068. .flatMap((script) => script.channels);
  7069. }
  7070. /** Loads all top-level preload scripts. */
  7071. async #initAndEvaluatePreloadScripts() {
  7072. await Promise.all(this.#preloadScriptStorage
  7073. .find({
  7074. // Needed for OOPIF
  7075. targetId: this.topLevelId,
  7076. global: true,
  7077. })
  7078. .map((script) => {
  7079. return script.initInTarget(this, true);
  7080. }));
  7081. }
  7082. get topLevelId() {
  7083. return (this.#browsingContextStorage.findTopLevelContextId(this.id) ?? this.id);
  7084. }
  7085. isSubscribedTo(moduleOrEvent) {
  7086. return this.#eventManager.subscriptionManager.isSubscribedTo(moduleOrEvent, this.topLevelId);
  7087. }
  7088. }
  7089. CdpTarget$1.CdpTarget = CdpTarget;
  7090. Object.defineProperty(CdpTargetManager$1, "__esModule", { value: true });
  7091. CdpTargetManager$1.CdpTargetManager = void 0;
  7092. const log_js_1$6 = log$1;
  7093. const BrowsingContextImpl_js_1 = BrowsingContextImpl$1;
  7094. const WorkerRealm_js_1 = WorkerRealm$1;
  7095. const CdpTarget_js_1 = CdpTarget$1;
  7096. const cdpToBidiTargetTypes = {
  7097. service_worker: 'service-worker',
  7098. shared_worker: 'shared-worker',
  7099. worker: 'dedicated-worker',
  7100. };
  7101. class CdpTargetManager {
  7102. #browserCdpClient;
  7103. #cdpConnection;
  7104. #selfTargetId;
  7105. #eventManager;
  7106. #browsingContextStorage;
  7107. #networkStorage;
  7108. #acceptInsecureCerts;
  7109. #preloadScriptStorage;
  7110. #realmStorage;
  7111. #defaultUserContextId;
  7112. #logger;
  7113. constructor(cdpConnection, browserCdpClient, selfTargetId, eventManager, browsingContextStorage, realmStorage, networkStorage, preloadScriptStorage, acceptInsecureCerts, defaultUserContextId, logger) {
  7114. this.#acceptInsecureCerts = acceptInsecureCerts;
  7115. this.#cdpConnection = cdpConnection;
  7116. this.#browserCdpClient = browserCdpClient;
  7117. this.#selfTargetId = selfTargetId;
  7118. this.#eventManager = eventManager;
  7119. this.#browsingContextStorage = browsingContextStorage;
  7120. this.#preloadScriptStorage = preloadScriptStorage;
  7121. this.#networkStorage = networkStorage;
  7122. this.#realmStorage = realmStorage;
  7123. this.#defaultUserContextId = defaultUserContextId;
  7124. this.#logger = logger;
  7125. this.#setEventListeners(browserCdpClient);
  7126. }
  7127. /**
  7128. * This method is called for each CDP session, since this class is responsible
  7129. * for creating and destroying all targets and browsing contexts.
  7130. */
  7131. #setEventListeners(cdpClient) {
  7132. cdpClient.on('Target.attachedToTarget', (params) => {
  7133. this.#handleAttachedToTargetEvent(params, cdpClient);
  7134. });
  7135. cdpClient.on('Target.detachedFromTarget', this.#handleDetachedFromTargetEvent.bind(this));
  7136. cdpClient.on('Target.targetInfoChanged', this.#handleTargetInfoChangedEvent.bind(this));
  7137. cdpClient.on('Inspector.targetCrashed', () => {
  7138. this.#handleTargetCrashedEvent(cdpClient);
  7139. });
  7140. cdpClient.on('Page.frameAttached', this.#handleFrameAttachedEvent.bind(this));
  7141. cdpClient.on('Page.frameDetached', this.#handleFrameDetachedEvent.bind(this));
  7142. }
  7143. #handleFrameAttachedEvent(params) {
  7144. const parentBrowsingContext = this.#browsingContextStorage.findContext(params.parentFrameId);
  7145. if (parentBrowsingContext !== undefined) {
  7146. BrowsingContextImpl_js_1.BrowsingContextImpl.create(params.frameId, params.parentFrameId, parentBrowsingContext.userContext, parentBrowsingContext.cdpTarget, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, this.#logger);
  7147. }
  7148. }
  7149. #handleFrameDetachedEvent(params) {
  7150. // In case of OOPiF no need in deleting BrowsingContext.
  7151. if (params.reason === 'swap') {
  7152. return;
  7153. }
  7154. this.#browsingContextStorage.findContext(params.frameId)?.dispose();
  7155. }
  7156. #handleAttachedToTargetEvent(params, parentSessionCdpClient) {
  7157. const { sessionId, targetInfo } = params;
  7158. const targetCdpClient = this.#cdpConnection.getCdpClient(sessionId);
  7159. switch (targetInfo.type) {
  7160. case 'page':
  7161. case 'iframe': {
  7162. if (targetInfo.targetId === this.#selfTargetId) {
  7163. break;
  7164. }
  7165. const cdpTarget = this.#createCdpTarget(targetCdpClient, targetInfo);
  7166. const maybeContext = this.#browsingContextStorage.findContext(targetInfo.targetId);
  7167. if (maybeContext) {
  7168. // OOPiF.
  7169. maybeContext.updateCdpTarget(cdpTarget);
  7170. }
  7171. else {
  7172. const userContext = targetInfo.browserContextId &&
  7173. targetInfo.browserContextId !== this.#defaultUserContextId
  7174. ? targetInfo.browserContextId
  7175. : 'default';
  7176. // New context.
  7177. BrowsingContextImpl_js_1.BrowsingContextImpl.create(targetInfo.targetId, null, userContext, cdpTarget, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, this.#logger);
  7178. }
  7179. return;
  7180. }
  7181. case 'service_worker':
  7182. case 'worker': {
  7183. const realm = this.#realmStorage.findRealm({
  7184. cdpSessionId: parentSessionCdpClient.sessionId,
  7185. });
  7186. // If there is no browsing context, this worker is already terminated.
  7187. if (!realm) {
  7188. break;
  7189. }
  7190. const cdpTarget = this.#createCdpTarget(targetCdpClient, targetInfo);
  7191. this.#handleWorkerTarget(cdpToBidiTargetTypes[targetInfo.type], cdpTarget, realm);
  7192. return;
  7193. }
  7194. // In CDP, we only emit shared workers on the browser and not the set of
  7195. // frames that use the shared worker. If we change this in the future to
  7196. // behave like service workers (emits on both browser and frame targets),
  7197. // we can remove this block and merge service workers with the above one.
  7198. case 'shared_worker': {
  7199. const cdpTarget = this.#createCdpTarget(targetCdpClient, targetInfo);
  7200. this.#handleWorkerTarget(cdpToBidiTargetTypes[targetInfo.type], cdpTarget);
  7201. return;
  7202. }
  7203. }
  7204. // DevTools or some other not supported by BiDi target. Just release
  7205. // debugger and ignore them.
  7206. targetCdpClient
  7207. .sendCommand('Runtime.runIfWaitingForDebugger')
  7208. .then(() => parentSessionCdpClient.sendCommand('Target.detachFromTarget', params))
  7209. .catch((error) => this.#logger?.(log_js_1$6.LogType.debugError, error));
  7210. }
  7211. #createCdpTarget(targetCdpClient, targetInfo) {
  7212. this.#setEventListeners(targetCdpClient);
  7213. const target = CdpTarget_js_1.CdpTarget.create(targetInfo.targetId, targetCdpClient, this.#browserCdpClient, this.#realmStorage, this.#eventManager, this.#preloadScriptStorage, this.#browsingContextStorage, this.#networkStorage, this.#acceptInsecureCerts, this.#logger);
  7214. this.#networkStorage.onCdpTargetCreated(target);
  7215. return target;
  7216. }
  7217. #workers = new Map();
  7218. #handleWorkerTarget(realmType, cdpTarget, ownerRealm) {
  7219. cdpTarget.cdpClient.on('Runtime.executionContextCreated', (params) => {
  7220. const { uniqueId, id, origin } = params.context;
  7221. const workerRealm = new WorkerRealm_js_1.WorkerRealm(cdpTarget.cdpClient, this.#eventManager, id, this.#logger, (0, BrowsingContextImpl_js_1.serializeOrigin)(origin), ownerRealm ? [ownerRealm] : [], uniqueId, this.#realmStorage, realmType);
  7222. this.#workers.set(cdpTarget.cdpSessionId, workerRealm);
  7223. });
  7224. }
  7225. #handleDetachedFromTargetEvent({ sessionId, targetId, }) {
  7226. if (targetId) {
  7227. this.#preloadScriptStorage.find({ targetId }).map((preloadScript) => {
  7228. preloadScript.dispose(targetId);
  7229. });
  7230. }
  7231. const context = this.#browsingContextStorage.findContextBySession(sessionId);
  7232. if (context) {
  7233. context.dispose();
  7234. return;
  7235. }
  7236. const worker = this.#workers.get(sessionId);
  7237. if (worker) {
  7238. this.#realmStorage.deleteRealms({
  7239. cdpSessionId: worker.cdpClient.sessionId,
  7240. });
  7241. }
  7242. }
  7243. #handleTargetInfoChangedEvent(params) {
  7244. const context = this.#browsingContextStorage.findContext(params.targetInfo.targetId);
  7245. if (context) {
  7246. context.onTargetInfoChanged(params);
  7247. }
  7248. }
  7249. #handleTargetCrashedEvent(cdpClient) {
  7250. // This is primarily used for service and shared workers. CDP tends to not
  7251. // signal they closed gracefully and instead says they crashed to signal
  7252. // they are closed.
  7253. const realms = this.#realmStorage.findRealms({
  7254. cdpSessionId: cdpClient.sessionId,
  7255. });
  7256. for (const realm of realms) {
  7257. realm.dispose();
  7258. }
  7259. }
  7260. }
  7261. CdpTargetManager$1.CdpTargetManager = CdpTargetManager;
  7262. var BrowsingContextStorage$1 = {};
  7263. /**
  7264. * Copyright 2022 Google LLC.
  7265. * Copyright (c) Microsoft Corporation.
  7266. *
  7267. * Licensed under the Apache License, Version 2.0 (the "License");
  7268. * you may not use this file except in compliance with the License.
  7269. * You may obtain a copy of the License at
  7270. *
  7271. * http://www.apache.org/licenses/LICENSE-2.0
  7272. *
  7273. * Unless required by applicable law or agreed to in writing, software
  7274. * distributed under the License is distributed on an "AS IS" BASIS,
  7275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7276. * See the License for the specific language governing permissions and
  7277. * limitations under the License.
  7278. */
  7279. Object.defineProperty(BrowsingContextStorage$1, "__esModule", { value: true });
  7280. BrowsingContextStorage$1.BrowsingContextStorage = void 0;
  7281. const protocol_js_1$7 = protocol;
  7282. /** Container class for browsing contexts. */
  7283. class BrowsingContextStorage {
  7284. /** Map from context ID to context implementation. */
  7285. #contexts = new Map();
  7286. /** Gets all top-level contexts, i.e. those with no parent. */
  7287. getTopLevelContexts() {
  7288. return this.getAllContexts().filter((context) => context.isTopLevelContext());
  7289. }
  7290. /** Gets all contexts. */
  7291. getAllContexts() {
  7292. return Array.from(this.#contexts.values());
  7293. }
  7294. /** Deletes the context with the given ID. */
  7295. deleteContextById(id) {
  7296. this.#contexts.delete(id);
  7297. }
  7298. /** Deletes the given context. */
  7299. deleteContext(context) {
  7300. this.#contexts.delete(context.id);
  7301. }
  7302. /** Tracks the given context. */
  7303. addContext(context) {
  7304. this.#contexts.set(context.id, context);
  7305. }
  7306. /** Returns true whether there is an existing context with the given ID. */
  7307. hasContext(id) {
  7308. return this.#contexts.has(id);
  7309. }
  7310. /** Gets the context with the given ID, if any. */
  7311. findContext(id) {
  7312. return this.#contexts.get(id);
  7313. }
  7314. /** Returns the top-level context ID of the given context, if any. */
  7315. findTopLevelContextId(id) {
  7316. if (id === null) {
  7317. return null;
  7318. }
  7319. const maybeContext = this.findContext(id);
  7320. const parentId = maybeContext?.parentId ?? null;
  7321. if (parentId === null) {
  7322. return id;
  7323. }
  7324. return this.findTopLevelContextId(parentId);
  7325. }
  7326. findContextBySession(sessionId) {
  7327. for (const context of this.#contexts.values()) {
  7328. if (context.cdpTarget.cdpSessionId === sessionId) {
  7329. return context;
  7330. }
  7331. }
  7332. return;
  7333. }
  7334. /** Gets the context with the given ID, if any, otherwise throws. */
  7335. getContext(id) {
  7336. const result = this.findContext(id);
  7337. if (result === undefined) {
  7338. throw new protocol_js_1$7.NoSuchFrameException(`Context ${id} not found`);
  7339. }
  7340. return result;
  7341. }
  7342. verifyTopLevelContextsList(contexts) {
  7343. const foundContexts = new Set();
  7344. if (!contexts) {
  7345. return foundContexts;
  7346. }
  7347. for (const contextId of contexts) {
  7348. const context = this.getContext(contextId);
  7349. if (context.isTopLevelContext()) {
  7350. foundContexts.add(context);
  7351. }
  7352. else {
  7353. throw new protocol_js_1$7.InvalidArgumentException(`Non top-level context '${contextId}' given.`);
  7354. }
  7355. }
  7356. return foundContexts;
  7357. }
  7358. }
  7359. BrowsingContextStorage$1.BrowsingContextStorage = BrowsingContextStorage;
  7360. var NetworkStorage$1 = {};
  7361. var NetworkRequest$1 = {};
  7362. /*
  7363. * Copyright 2023 Google LLC.
  7364. * Copyright (c) Microsoft Corporation.
  7365. *
  7366. * Licensed under the Apache License, Version 2.0 (the "License");
  7367. * you may not use this file except in compliance with the License.
  7368. * You may obtain a copy of the License at
  7369. *
  7370. * http://www.apache.org/licenses/LICENSE-2.0
  7371. *
  7372. * Unless required by applicable law or agreed to in writing, software
  7373. * distributed under the License is distributed on an "AS IS" BASIS,
  7374. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7375. * See the License for the specific language governing permissions and
  7376. * limitations under the License.
  7377. *
  7378. */
  7379. Object.defineProperty(NetworkRequest$1, "__esModule", { value: true });
  7380. NetworkRequest$1.NetworkRequest = void 0;
  7381. const protocol_js_1$6 = protocol;
  7382. const assert_js_1 = assert$1;
  7383. const Deferred_js_1 = Deferred$1;
  7384. const log_js_1$5 = log$1;
  7385. const NetworkUtils_js_1$1 = NetworkUtils;
  7386. const REALM_REGEX = /(?<=realm=").*(?=")/;
  7387. /** Abstracts one individual network request. */
  7388. class NetworkRequest {
  7389. static unknownParameter = 'UNKNOWN';
  7390. /**
  7391. * Each network request has an associated request id, which is a string
  7392. * uniquely identifying that request.
  7393. *
  7394. * The identifier for a request resulting from a redirect matches that of the
  7395. * request that initiated it.
  7396. */
  7397. #id;
  7398. #fetchId;
  7399. /**
  7400. * Indicates the network intercept phase, if the request is currently blocked.
  7401. * Undefined necessarily implies that the request is not blocked.
  7402. */
  7403. #interceptPhase;
  7404. #servedFromCache = false;
  7405. #redirectCount;
  7406. #request = {};
  7407. #response = {};
  7408. #eventManager;
  7409. #networkStorage;
  7410. #cdpTarget;
  7411. #logger;
  7412. #emittedEvents = {
  7413. [protocol_js_1$6.ChromiumBidi.Network.EventNames.AuthRequired]: false,
  7414. [protocol_js_1$6.ChromiumBidi.Network.EventNames.BeforeRequestSent]: false,
  7415. [protocol_js_1$6.ChromiumBidi.Network.EventNames.FetchError]: false,
  7416. [protocol_js_1$6.ChromiumBidi.Network.EventNames.ResponseCompleted]: false,
  7417. [protocol_js_1$6.ChromiumBidi.Network.EventNames.ResponseStarted]: false,
  7418. };
  7419. waitNextPhase = new Deferred_js_1.Deferred();
  7420. constructor(id, eventManager, networkStorage, cdpTarget, redirectCount = 0, logger) {
  7421. this.#id = id;
  7422. this.#eventManager = eventManager;
  7423. this.#networkStorage = networkStorage;
  7424. this.#cdpTarget = cdpTarget;
  7425. this.#redirectCount = redirectCount;
  7426. this.#logger = logger;
  7427. }
  7428. get id() {
  7429. return this.#id;
  7430. }
  7431. get fetchId() {
  7432. return this.#fetchId;
  7433. }
  7434. /**
  7435. * When blocked returns the phase for it
  7436. */
  7437. get interceptPhase() {
  7438. return this.#interceptPhase;
  7439. }
  7440. get url() {
  7441. const fragment = this.#request.info?.request.urlFragment ??
  7442. this.#request.paused?.request.urlFragment ??
  7443. '';
  7444. const url = this.#response.info?.url ??
  7445. this.#response.paused?.request.url ??
  7446. this.#request.auth?.request.url ??
  7447. this.#request.info?.request.url ??
  7448. this.#request.paused?.request.url ??
  7449. NetworkRequest.unknownParameter;
  7450. return `${url}${fragment}`;
  7451. }
  7452. get method() {
  7453. return (this.#request.info?.request.method ??
  7454. this.#request.paused?.request.method ??
  7455. this.#request.auth?.request.method ??
  7456. this.#response.paused?.request.method ??
  7457. NetworkRequest.unknownParameter);
  7458. }
  7459. get redirectCount() {
  7460. return this.#redirectCount;
  7461. }
  7462. get cdpTarget() {
  7463. return this.#cdpTarget;
  7464. }
  7465. get cdpClient() {
  7466. return this.#cdpTarget.cdpClient;
  7467. }
  7468. isRedirecting() {
  7469. return Boolean(this.#request.info);
  7470. }
  7471. isDataUrl() {
  7472. return this.url.startsWith('data:');
  7473. }
  7474. #phaseChanged() {
  7475. this.waitNextPhase.resolve();
  7476. this.waitNextPhase = new Deferred_js_1.Deferred();
  7477. }
  7478. #interceptsInPhase(phase) {
  7479. if (!this.#cdpTarget.isSubscribedTo(`network.${phase}`)) {
  7480. return new Set();
  7481. }
  7482. return this.#networkStorage.getInterceptsForPhase(this, phase);
  7483. }
  7484. #isBlockedInPhase(phase) {
  7485. return this.#interceptsInPhase(phase).size > 0;
  7486. }
  7487. handleRedirect(event) {
  7488. // TODO: use event.redirectResponse;
  7489. // Temporary workaround to emit ResponseCompleted event for redirects
  7490. this.#response.hasExtraInfo = false;
  7491. this.#response.info = event.redirectResponse;
  7492. this.#emitEventsIfReady({
  7493. wasRedirected: true,
  7494. });
  7495. }
  7496. #emitEventsIfReady(options = {}) {
  7497. const requestExtraInfoCompleted =
  7498. // Flush redirects
  7499. options.wasRedirected ||
  7500. options.hasFailed ||
  7501. this.isDataUrl() ||
  7502. Boolean(this.#request.extraInfo) ||
  7503. // Requests from cache don't have extra info
  7504. this.#servedFromCache ||
  7505. // Sometimes there is no extra info and the response
  7506. // is the only place we can find out
  7507. Boolean(this.#response.info && !this.#response.hasExtraInfo);
  7508. const noInterceptionExpected =
  7509. // We can't intercept data urls from CDP
  7510. this.isDataUrl() ||
  7511. // Cached requests never hit the network
  7512. this.#servedFromCache;
  7513. const requestInterceptionExpected = !noInterceptionExpected &&
  7514. this.#isBlockedInPhase("beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */);
  7515. const requestInterceptionCompleted = !requestInterceptionExpected ||
  7516. (requestInterceptionExpected && Boolean(this.#request.paused));
  7517. if (Boolean(this.#request.info) &&
  7518. (requestInterceptionExpected
  7519. ? requestInterceptionCompleted
  7520. : requestExtraInfoCompleted)) {
  7521. this.#emitEvent(this.#getBeforeRequestEvent.bind(this));
  7522. }
  7523. const responseExtraInfoCompleted = Boolean(this.#response.extraInfo) ||
  7524. // Response from cache don't have extra info
  7525. this.#servedFromCache ||
  7526. // Don't expect extra info if the flag is false
  7527. Boolean(this.#response.info && !this.#response.hasExtraInfo);
  7528. const responseInterceptionExpected = !noInterceptionExpected &&
  7529. this.#isBlockedInPhase("responseStarted" /* Network.InterceptPhase.ResponseStarted */);
  7530. if (this.#response.info ||
  7531. (responseInterceptionExpected && Boolean(this.#response.paused))) {
  7532. this.#emitEvent(this.#getResponseStartedEvent.bind(this));
  7533. }
  7534. const responseInterceptionCompleted = !responseInterceptionExpected ||
  7535. (responseInterceptionExpected && Boolean(this.#response.paused));
  7536. if (Boolean(this.#response.info) &&
  7537. responseExtraInfoCompleted &&
  7538. responseInterceptionCompleted) {
  7539. this.#emitEvent(this.#getResponseReceivedEvent.bind(this));
  7540. }
  7541. }
  7542. onRequestWillBeSentEvent(event) {
  7543. this.#request.info = event;
  7544. this.#emitEventsIfReady();
  7545. }
  7546. onRequestWillBeSentExtraInfoEvent(event) {
  7547. this.#request.extraInfo = event;
  7548. this.#emitEventsIfReady();
  7549. }
  7550. onResponseReceivedExtraInfoEvent(event) {
  7551. this.#response.extraInfo = event;
  7552. this.#emitEventsIfReady();
  7553. }
  7554. onResponseReceivedEvent(event) {
  7555. this.#response.hasExtraInfo = event.hasExtraInfo;
  7556. this.#response.info = event.response;
  7557. this.#emitEventsIfReady();
  7558. }
  7559. onServedFromCache() {
  7560. this.#servedFromCache = true;
  7561. this.#emitEventsIfReady();
  7562. }
  7563. onLoadingFailedEvent(event) {
  7564. this.#emitEventsIfReady({
  7565. hasFailed: true,
  7566. });
  7567. this.#emitEvent(() => {
  7568. return {
  7569. method: protocol_js_1$6.ChromiumBidi.Network.EventNames.FetchError,
  7570. params: {
  7571. ...this.#getBaseEventParams(),
  7572. errorText: event.errorText,
  7573. },
  7574. };
  7575. });
  7576. }
  7577. /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-failRequest */
  7578. async failRequest(errorReason) {
  7579. (0, assert_js_1.assert)(this.#fetchId, 'Network Interception not set-up.');
  7580. await this.cdpClient.sendCommand('Fetch.failRequest', {
  7581. requestId: this.#fetchId,
  7582. errorReason,
  7583. });
  7584. this.#interceptPhase = undefined;
  7585. }
  7586. onRequestPaused(event) {
  7587. this.#fetchId = event.requestId;
  7588. // CDP https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#event-requestPaused
  7589. if (event.responseStatusCode || event.responseErrorReason) {
  7590. this.#response.paused = event;
  7591. if (this.#isBlockedInPhase("responseStarted" /* Network.InterceptPhase.ResponseStarted */) &&
  7592. // CDP may emit multiple events for a single request
  7593. !this.#emittedEvents[protocol_js_1$6.ChromiumBidi.Network.EventNames.ResponseStarted] &&
  7594. // Continue all response that have not enabled Network domain
  7595. this.#fetchId !== this.id) {
  7596. this.#interceptPhase = "responseStarted" /* Network.InterceptPhase.ResponseStarted */;
  7597. }
  7598. else {
  7599. void this.continueResponse();
  7600. }
  7601. }
  7602. else {
  7603. this.#request.paused = event;
  7604. if (this.#isBlockedInPhase("beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */) &&
  7605. // CDP may emit multiple events for a single request
  7606. !this.#emittedEvents[protocol_js_1$6.ChromiumBidi.Network.EventNames.BeforeRequestSent] &&
  7607. // Continue all requests that have not enabled Network domain
  7608. this.#fetchId !== this.id) {
  7609. this.#interceptPhase = "beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */;
  7610. }
  7611. else {
  7612. void this.continueRequest();
  7613. }
  7614. }
  7615. this.#emitEventsIfReady();
  7616. }
  7617. onAuthRequired(event) {
  7618. this.#fetchId = event.requestId;
  7619. this.#request.auth = event;
  7620. if (this.#isBlockedInPhase("authRequired" /* Network.InterceptPhase.AuthRequired */) &&
  7621. // Continue all auth requests that have not enabled Network domain
  7622. this.#fetchId !== this.id) {
  7623. this.#interceptPhase = "authRequired" /* Network.InterceptPhase.AuthRequired */;
  7624. }
  7625. else {
  7626. void this.continueWithAuth();
  7627. }
  7628. this.#emitEvent(() => {
  7629. return {
  7630. method: protocol_js_1$6.ChromiumBidi.Network.EventNames.AuthRequired,
  7631. params: {
  7632. ...this.#getBaseEventParams("authRequired" /* Network.InterceptPhase.AuthRequired */),
  7633. response: this.#getResponseEventParams(),
  7634. },
  7635. };
  7636. });
  7637. }
  7638. /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-continueRequest */
  7639. async continueRequest({ url, method, headers, postData, } = {}) {
  7640. (0, assert_js_1.assert)(this.#fetchId, 'Network Interception not set-up.');
  7641. await this.cdpClient.sendCommand('Fetch.continueRequest', {
  7642. requestId: this.#fetchId,
  7643. url,
  7644. method,
  7645. headers,
  7646. postData,
  7647. });
  7648. this.#interceptPhase = undefined;
  7649. }
  7650. /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-continueResponse */
  7651. async continueResponse({ responseCode, responsePhrase, responseHeaders, } = {}) {
  7652. (0, assert_js_1.assert)(this.#fetchId, 'Network Interception not set-up.');
  7653. await this.cdpClient.sendCommand('Fetch.continueResponse', {
  7654. requestId: this.#fetchId,
  7655. responseCode,
  7656. responsePhrase,
  7657. responseHeaders,
  7658. });
  7659. this.#interceptPhase = undefined;
  7660. }
  7661. /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-continueWithAuth */
  7662. async continueWithAuth(authChallengeResponse = {
  7663. response: 'Default',
  7664. }) {
  7665. (0, assert_js_1.assert)(this.#fetchId, 'Network Interception not set-up.');
  7666. await this.cdpClient.sendCommand('Fetch.continueWithAuth', {
  7667. requestId: this.#fetchId,
  7668. authChallengeResponse,
  7669. });
  7670. this.#interceptPhase = undefined;
  7671. }
  7672. /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-provideResponse */
  7673. async provideResponse({ responseCode, responsePhrase, responseHeaders, body, }) {
  7674. (0, assert_js_1.assert)(this.#fetchId, 'Network Interception not set-up.');
  7675. await this.cdpClient.sendCommand('Fetch.fulfillRequest', {
  7676. requestId: this.#fetchId,
  7677. responseCode,
  7678. responsePhrase,
  7679. responseHeaders,
  7680. body,
  7681. });
  7682. this.#interceptPhase = undefined;
  7683. }
  7684. get #context() {
  7685. return (this.#response.paused?.frameId ??
  7686. this.#request.info?.frameId ??
  7687. this.#request.paused?.frameId ??
  7688. this.#request.auth?.frameId ??
  7689. null);
  7690. }
  7691. /** Returns the HTTP status code associated with this request if any. */
  7692. get statusCode() {
  7693. return (this.#response.paused?.responseStatusCode ??
  7694. this.#response.extraInfo?.statusCode ??
  7695. this.#response.info?.status);
  7696. }
  7697. #emitEvent(getEvent) {
  7698. let event;
  7699. try {
  7700. event = getEvent();
  7701. }
  7702. catch (error) {
  7703. this.#logger?.(log_js_1$5.LogType.debugError, error);
  7704. return;
  7705. }
  7706. if (this.#isIgnoredEvent() ||
  7707. (this.#emittedEvents[event.method] &&
  7708. // Special case this event can be emitted multiple times
  7709. event.method !== protocol_js_1$6.ChromiumBidi.Network.EventNames.AuthRequired)) {
  7710. return;
  7711. }
  7712. this.#phaseChanged();
  7713. this.#emittedEvents[event.method] = true;
  7714. this.#eventManager.registerEvent(Object.assign(event, {
  7715. type: 'event',
  7716. }), this.#context);
  7717. }
  7718. #getBaseEventParams(phase) {
  7719. const interceptProps = {
  7720. isBlocked: false,
  7721. };
  7722. if (phase) {
  7723. const blockedBy = this.#interceptsInPhase(phase);
  7724. interceptProps.isBlocked = blockedBy.size > 0;
  7725. if (interceptProps.isBlocked) {
  7726. interceptProps.intercepts = [...blockedBy];
  7727. }
  7728. }
  7729. return {
  7730. context: this.#context,
  7731. navigation: this.#getNavigationId(),
  7732. redirectCount: this.#redirectCount,
  7733. request: this.#getRequestData(),
  7734. // Timestamp should be in milliseconds, while CDP provides it in seconds.
  7735. timestamp: Math.round((this.#request.info?.wallTime ?? 0) * 1000),
  7736. // Contains isBlocked and intercepts
  7737. ...interceptProps,
  7738. };
  7739. }
  7740. #getResponseEventParams() {
  7741. // Chromium sends wrong extraInfo events for responses served from cache.
  7742. // See https://github.com/puppeteer/puppeteer/issues/9965 and
  7743. // https://crbug.com/1340398.
  7744. if (this.#response.info?.fromDiskCache) {
  7745. this.#response.extraInfo = undefined;
  7746. }
  7747. // TODO: get headers from Fetch.requestPaused
  7748. const headers = (0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#response.info?.headers);
  7749. // TODO: get headers from Fetch.requestPaused
  7750. const authChallenges = this.#authChallenges(this.#response.info?.headers ?? {});
  7751. return {
  7752. url: this.url,
  7753. protocol: this.#response.info?.protocol ?? '',
  7754. status: this.statusCode ?? -1, // TODO: Throw an exception or use some other status code?
  7755. statusText: this.#response.info?.statusText ||
  7756. this.#response.paused?.responseStatusText ||
  7757. '',
  7758. fromCache: this.#response.info?.fromDiskCache ||
  7759. this.#response.info?.fromPrefetchCache ||
  7760. this.#servedFromCache,
  7761. headers,
  7762. mimeType: this.#response.info?.mimeType || '',
  7763. bytesReceived: this.#response.info?.encodedDataLength || 0,
  7764. headersSize: (0, NetworkUtils_js_1$1.computeHeadersSize)(headers),
  7765. // TODO: consider removing from spec.
  7766. bodySize: 0,
  7767. content: {
  7768. // TODO: consider removing from spec.
  7769. size: 0,
  7770. },
  7771. ...(authChallenges ? { authChallenges } : {}),
  7772. };
  7773. }
  7774. #getNavigationId() {
  7775. if (!this.#request.info ||
  7776. !this.#request.info.loaderId ||
  7777. // When we navigate all CDP network events have `loaderId`
  7778. // CDP's `loaderId` and `requestId` match when
  7779. // that request triggered the loading
  7780. this.#request.info.loaderId !== this.#request.info.requestId) {
  7781. return null;
  7782. }
  7783. return this.#request.info.loaderId;
  7784. }
  7785. #getRequestData() {
  7786. const cookies = this.#request.extraInfo
  7787. ? NetworkRequest.#getCookies(this.#request.extraInfo.associatedCookies)
  7788. : [];
  7789. const headers = (0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#request.info?.request.headers);
  7790. return {
  7791. request: this.#id,
  7792. url: this.url,
  7793. method: this.method,
  7794. headers,
  7795. cookies,
  7796. headersSize: (0, NetworkUtils_js_1$1.computeHeadersSize)(headers),
  7797. // TODO: implement.
  7798. bodySize: 0,
  7799. timings: this.#getTimings(),
  7800. };
  7801. }
  7802. // TODO: implement.
  7803. #getTimings() {
  7804. return {
  7805. timeOrigin: 0,
  7806. requestTime: 0,
  7807. redirectStart: 0,
  7808. redirectEnd: 0,
  7809. fetchStart: 0,
  7810. dnsStart: 0,
  7811. dnsEnd: 0,
  7812. connectStart: 0,
  7813. connectEnd: 0,
  7814. tlsStart: 0,
  7815. requestStart: 0,
  7816. responseStart: 0,
  7817. responseEnd: 0,
  7818. };
  7819. }
  7820. #getBeforeRequestEvent() {
  7821. (0, assert_js_1.assert)(this.#request.info, 'RequestWillBeSentEvent is not set');
  7822. return {
  7823. method: protocol_js_1$6.ChromiumBidi.Network.EventNames.BeforeRequestSent,
  7824. params: {
  7825. ...this.#getBaseEventParams("beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */),
  7826. initiator: {
  7827. type: NetworkRequest.#getInitiatorType(this.#request.info.initiator.type),
  7828. columnNumber: this.#request.info.initiator.columnNumber,
  7829. lineNumber: this.#request.info.initiator.lineNumber,
  7830. stackTrace: this.#request.info.initiator.stack,
  7831. request: this.#request.info.initiator.requestId,
  7832. },
  7833. },
  7834. };
  7835. }
  7836. #getResponseStartedEvent() {
  7837. (0, assert_js_1.assert)(this.#request.info, 'RequestWillBeSentEvent is not set');
  7838. (0, assert_js_1.assert)(
  7839. // The response paused comes before any data for the response
  7840. this.#response.paused || this.#response.info, 'ResponseReceivedEvent is not set');
  7841. return {
  7842. method: protocol_js_1$6.ChromiumBidi.Network.EventNames.ResponseStarted,
  7843. params: {
  7844. ...this.#getBaseEventParams("responseStarted" /* Network.InterceptPhase.ResponseStarted */),
  7845. response: this.#getResponseEventParams(),
  7846. },
  7847. };
  7848. }
  7849. #getResponseReceivedEvent() {
  7850. (0, assert_js_1.assert)(this.#request.info, 'RequestWillBeSentEvent is not set');
  7851. (0, assert_js_1.assert)(this.#response.info, 'ResponseReceivedEvent is not set');
  7852. return {
  7853. method: protocol_js_1$6.ChromiumBidi.Network.EventNames.ResponseCompleted,
  7854. params: {
  7855. ...this.#getBaseEventParams(),
  7856. response: this.#getResponseEventParams(),
  7857. },
  7858. };
  7859. }
  7860. #isIgnoredEvent() {
  7861. const faviconUrl = '/favicon.ico';
  7862. return (this.#request.paused?.request.url.endsWith(faviconUrl) ??
  7863. this.#request.info?.request.url.endsWith(faviconUrl) ??
  7864. false);
  7865. }
  7866. #authChallenges(headers) {
  7867. if (!(this.statusCode === 401 || this.statusCode === 407)) {
  7868. return undefined;
  7869. }
  7870. const headerName = this.statusCode === 401 ? 'WWW-Authenticate' : 'Proxy-Authenticate';
  7871. const authChallenges = [];
  7872. for (const [header, value] of Object.entries(headers)) {
  7873. // TODO: Do a proper match based on https://httpwg.org/specs/rfc9110.html#credentials
  7874. // Or verify this works
  7875. if (header.localeCompare(headerName, undefined, { sensitivity: 'base' }) === 0) {
  7876. authChallenges.push({
  7877. scheme: value.split(' ').at(0) ?? '',
  7878. realm: value.match(REALM_REGEX)?.at(0) ?? '',
  7879. });
  7880. }
  7881. }
  7882. return authChallenges;
  7883. }
  7884. static #getInitiatorType(initiatorType) {
  7885. switch (initiatorType) {
  7886. case 'parser':
  7887. case 'script':
  7888. case 'preflight':
  7889. return initiatorType;
  7890. default:
  7891. return 'other';
  7892. }
  7893. }
  7894. static #getCookies(associatedCookies) {
  7895. return associatedCookies
  7896. .filter(({ blockedReasons }) => {
  7897. return !Array.isArray(blockedReasons) || blockedReasons.length === 0;
  7898. })
  7899. .map(({ cookie }) => (0, NetworkUtils_js_1$1.cdpToBiDiCookie)(cookie));
  7900. }
  7901. }
  7902. NetworkRequest$1.NetworkRequest = NetworkRequest;
  7903. Object.defineProperty(NetworkStorage$1, "__esModule", { value: true });
  7904. NetworkStorage$1.NetworkStorage = void 0;
  7905. const protocol_js_1$5 = protocol;
  7906. const uuid_js_1 = uuid;
  7907. const NetworkRequest_js_1 = NetworkRequest$1;
  7908. const NetworkUtils_js_1 = NetworkUtils;
  7909. /** Stores network and intercept maps. */
  7910. class NetworkStorage {
  7911. #eventManager;
  7912. #logger;
  7913. /**
  7914. * A map from network request ID to Network Request objects.
  7915. * Needed as long as information about requests comes from different events.
  7916. */
  7917. #requests = new Map();
  7918. /** A map from intercept ID to track active network intercepts. */
  7919. #intercepts = new Map();
  7920. constructor(eventManager, browserClient, logger) {
  7921. this.#eventManager = eventManager;
  7922. browserClient.on('Target.detachedFromTarget', ({ sessionId }) => {
  7923. this.disposeRequestMap(sessionId);
  7924. });
  7925. this.#logger = logger;
  7926. }
  7927. /**
  7928. * Gets the network request with the given ID, if any.
  7929. * Otherwise, creates a new network request with the given ID and cdp target.
  7930. */
  7931. #getOrCreateNetworkRequest(id, cdpTarget, redirectCount) {
  7932. let request = this.getRequestById(id);
  7933. if (request) {
  7934. return request;
  7935. }
  7936. request = new NetworkRequest_js_1.NetworkRequest(id, this.#eventManager, this, cdpTarget, redirectCount, this.#logger);
  7937. this.addRequest(request);
  7938. return request;
  7939. }
  7940. onCdpTargetCreated(cdpTarget) {
  7941. const cdpClient = cdpTarget.cdpClient;
  7942. // TODO: Wrap into object
  7943. const listeners = [
  7944. [
  7945. 'Network.requestWillBeSent',
  7946. (params) => {
  7947. const request = this.getRequestById(params.requestId);
  7948. if (request && request.isRedirecting()) {
  7949. request.handleRedirect(params);
  7950. this.deleteRequest(params.requestId);
  7951. this.#getOrCreateNetworkRequest(params.requestId, cdpTarget, request.redirectCount + 1).onRequestWillBeSentEvent(params);
  7952. }
  7953. else {
  7954. this.#getOrCreateNetworkRequest(params.requestId, cdpTarget).onRequestWillBeSentEvent(params);
  7955. }
  7956. },
  7957. ],
  7958. [
  7959. 'Network.requestWillBeSentExtraInfo',
  7960. (params) => {
  7961. this.#getOrCreateNetworkRequest(params.requestId, cdpTarget).onRequestWillBeSentExtraInfoEvent(params);
  7962. },
  7963. ],
  7964. [
  7965. 'Network.responseReceived',
  7966. (params) => {
  7967. this.#getOrCreateNetworkRequest(params.requestId, cdpTarget).onResponseReceivedEvent(params);
  7968. },
  7969. ],
  7970. [
  7971. 'Network.responseReceivedExtraInfo',
  7972. (params) => {
  7973. this.#getOrCreateNetworkRequest(params.requestId, cdpTarget).onResponseReceivedExtraInfoEvent(params);
  7974. },
  7975. ],
  7976. [
  7977. 'Network.requestServedFromCache',
  7978. (params) => {
  7979. this.#getOrCreateNetworkRequest(params.requestId, cdpTarget).onServedFromCache();
  7980. },
  7981. ],
  7982. [
  7983. 'Network.loadingFailed',
  7984. (params) => {
  7985. this.#getOrCreateNetworkRequest(params.requestId, cdpTarget).onLoadingFailedEvent(params);
  7986. },
  7987. ],
  7988. [
  7989. 'Fetch.requestPaused',
  7990. (event) => {
  7991. this.#getOrCreateNetworkRequest(
  7992. // CDP quirk if the Network domain is not present this is undefined
  7993. event.networkId ?? event.requestId, cdpTarget).onRequestPaused(event);
  7994. },
  7995. ],
  7996. [
  7997. 'Fetch.authRequired',
  7998. (event) => {
  7999. let request = this.getRequestByFetchId(event.requestId);
  8000. if (!request) {
  8001. request = this.#getOrCreateNetworkRequest(event.requestId, cdpTarget);
  8002. }
  8003. request.onAuthRequired(event);
  8004. },
  8005. ],
  8006. ];
  8007. for (const [event, listener] of listeners) {
  8008. cdpClient.on(event, listener);
  8009. }
  8010. }
  8011. getInterceptionStages(browsingContextId) {
  8012. const stages = {
  8013. request: false,
  8014. response: false,
  8015. auth: false,
  8016. };
  8017. for (const intercept of this.#intercepts.values()) {
  8018. if (intercept.contexts &&
  8019. !intercept.contexts.includes(browsingContextId)) {
  8020. continue;
  8021. }
  8022. stages.request ||= intercept.phases.includes("beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */);
  8023. stages.response ||= intercept.phases.includes("responseStarted" /* Network.InterceptPhase.ResponseStarted */);
  8024. stages.auth ||= intercept.phases.includes("authRequired" /* Network.InterceptPhase.AuthRequired */);
  8025. }
  8026. return stages;
  8027. }
  8028. getInterceptsForPhase(request, phase) {
  8029. if (request.url === NetworkRequest_js_1.NetworkRequest.unknownParameter) {
  8030. return new Set();
  8031. }
  8032. const intercepts = new Set();
  8033. for (const [interceptId, intercept] of this.#intercepts.entries()) {
  8034. if (!intercept.phases.includes(phase) ||
  8035. (intercept.contexts &&
  8036. !intercept.contexts.includes(request.cdpTarget.topLevelId))) {
  8037. continue;
  8038. }
  8039. if (intercept.urlPatterns.length === 0) {
  8040. intercepts.add(interceptId);
  8041. continue;
  8042. }
  8043. for (const pattern of intercept.urlPatterns) {
  8044. if ((0, NetworkUtils_js_1.matchUrlPattern)(pattern, request.url)) {
  8045. intercepts.add(interceptId);
  8046. break;
  8047. }
  8048. }
  8049. }
  8050. return intercepts;
  8051. }
  8052. disposeRequestMap(sessionId) {
  8053. for (const request of this.#requests.values()) {
  8054. if (request.cdpClient.sessionId === sessionId) {
  8055. this.#requests.delete(request.id);
  8056. }
  8057. }
  8058. }
  8059. /**
  8060. * Adds the given entry to the intercept map.
  8061. * URL patterns are assumed to be parsed.
  8062. *
  8063. * @return The intercept ID.
  8064. */
  8065. addIntercept(value) {
  8066. const interceptId = (0, uuid_js_1.uuidv4)();
  8067. this.#intercepts.set(interceptId, value);
  8068. return interceptId;
  8069. }
  8070. /**
  8071. * Removes the given intercept from the intercept map.
  8072. * Throws NoSuchInterceptException if the intercept does not exist.
  8073. */
  8074. removeIntercept(intercept) {
  8075. if (!this.#intercepts.has(intercept)) {
  8076. throw new protocol_js_1$5.NoSuchInterceptException(`Intercept '${intercept}' does not exist.`);
  8077. }
  8078. this.#intercepts.delete(intercept);
  8079. }
  8080. getRequestById(id) {
  8081. return this.#requests.get(id);
  8082. }
  8083. getRequestByFetchId(fetchId) {
  8084. for (const request of this.#requests.values()) {
  8085. if (request.fetchId === fetchId) {
  8086. return request;
  8087. }
  8088. }
  8089. return;
  8090. }
  8091. addRequest(request) {
  8092. this.#requests.set(request.id, request);
  8093. }
  8094. deleteRequest(id) {
  8095. this.#requests.delete(id);
  8096. }
  8097. }
  8098. NetworkStorage$1.NetworkStorage = NetworkStorage;
  8099. var PreloadScriptStorage$1 = {};
  8100. Object.defineProperty(PreloadScriptStorage$1, "__esModule", { value: true });
  8101. PreloadScriptStorage$1.PreloadScriptStorage = void 0;
  8102. /**
  8103. * Container class for preload scripts.
  8104. */
  8105. class PreloadScriptStorage {
  8106. /** Tracks all BiDi preload scripts. */
  8107. #scripts = new Set();
  8108. /**
  8109. * Finds all entries that match the given filter (OR logic).
  8110. */
  8111. find(filter) {
  8112. if (!filter) {
  8113. return [...this.#scripts];
  8114. }
  8115. return [...this.#scripts].filter((script) => {
  8116. if (filter.id !== undefined && filter.id === script.id) {
  8117. return true;
  8118. }
  8119. if (filter.targetId !== undefined &&
  8120. script.targetIds.has(filter.targetId)) {
  8121. return true;
  8122. }
  8123. if (filter.global !== undefined &&
  8124. // Global scripts have no contexts
  8125. ((filter.global && script.contexts === undefined) ||
  8126. // Non global scripts always have contexts
  8127. (!filter.global && script.contexts !== undefined))) {
  8128. return true;
  8129. }
  8130. return false;
  8131. });
  8132. }
  8133. add(preloadScript) {
  8134. this.#scripts.add(preloadScript);
  8135. }
  8136. /** Deletes all BiDi preload script entries that match the given filter. */
  8137. remove(filter) {
  8138. for (const preloadScript of this.find(filter)) {
  8139. this.#scripts.delete(preloadScript);
  8140. }
  8141. }
  8142. }
  8143. PreloadScriptStorage$1.PreloadScriptStorage = PreloadScriptStorage;
  8144. var RealmStorage$1 = {};
  8145. Object.defineProperty(RealmStorage$1, "__esModule", { value: true });
  8146. RealmStorage$1.RealmStorage = void 0;
  8147. const protocol_js_1$4 = protocol;
  8148. const WindowRealm_js_1 = WindowRealm$1;
  8149. /** Container class for browsing realms. */
  8150. class RealmStorage {
  8151. /** Tracks handles and their realms sent to the client. */
  8152. #knownHandlesToRealmMap = new Map();
  8153. /** Map from realm ID to Realm. */
  8154. #realmMap = new Map();
  8155. get knownHandlesToRealmMap() {
  8156. return this.#knownHandlesToRealmMap;
  8157. }
  8158. addRealm(realm) {
  8159. this.#realmMap.set(realm.realmId, realm);
  8160. }
  8161. /** Finds all realms that match the given filter. */
  8162. findRealms(filter) {
  8163. return Array.from(this.#realmMap.values()).filter((realm) => {
  8164. if (filter.realmId !== undefined && filter.realmId !== realm.realmId) {
  8165. return false;
  8166. }
  8167. if (filter.browsingContextId !== undefined &&
  8168. !realm.associatedBrowsingContexts
  8169. .map((browsingContext) => browsingContext.id)
  8170. .includes(filter.browsingContextId)) {
  8171. return false;
  8172. }
  8173. if (filter.sandbox !== undefined &&
  8174. (!(realm instanceof WindowRealm_js_1.WindowRealm) || filter.sandbox !== realm.sandbox)) {
  8175. return false;
  8176. }
  8177. if (filter.executionContextId !== undefined &&
  8178. filter.executionContextId !== realm.executionContextId) {
  8179. return false;
  8180. }
  8181. if (filter.origin !== undefined && filter.origin !== realm.origin) {
  8182. return false;
  8183. }
  8184. if (filter.type !== undefined && filter.type !== realm.realmType) {
  8185. return false;
  8186. }
  8187. if (filter.cdpSessionId !== undefined &&
  8188. filter.cdpSessionId !== realm.cdpClient.sessionId) {
  8189. return false;
  8190. }
  8191. return true;
  8192. });
  8193. }
  8194. findRealm(filter) {
  8195. const maybeRealms = this.findRealms(filter);
  8196. if (maybeRealms.length !== 1) {
  8197. return undefined;
  8198. }
  8199. return maybeRealms[0];
  8200. }
  8201. /** Gets the only realm that matches the given filter, if any, otherwise throws. */
  8202. getRealm(filter) {
  8203. const maybeRealm = this.findRealm(filter);
  8204. if (maybeRealm === undefined) {
  8205. throw new protocol_js_1$4.NoSuchFrameException(`Realm ${JSON.stringify(filter)} not found`);
  8206. }
  8207. return maybeRealm;
  8208. }
  8209. /** Deletes all realms that match the given filter. */
  8210. deleteRealms(filter) {
  8211. this.findRealms(filter).map((realm) => {
  8212. realm.dispose();
  8213. this.#realmMap.delete(realm.realmId);
  8214. Array.from(this.knownHandlesToRealmMap.entries())
  8215. .filter(([, r]) => r === realm.realmId)
  8216. .map(([handle]) => this.knownHandlesToRealmMap.delete(handle));
  8217. });
  8218. }
  8219. }
  8220. RealmStorage$1.RealmStorage = RealmStorage;
  8221. var EventManager$1 = {};
  8222. var Buffer$2 = {};
  8223. /**
  8224. * Copyright 2022 Google LLC.
  8225. * Copyright (c) Microsoft Corporation.
  8226. *
  8227. * Licensed under the Apache License, Version 2.0 (the "License");
  8228. * you may not use this file except in compliance with the License.
  8229. * You may obtain a copy of the License at
  8230. *
  8231. * http://www.apache.org/licenses/LICENSE-2.0
  8232. *
  8233. * Unless required by applicable law or agreed to in writing, software
  8234. * distributed under the License is distributed on an "AS IS" BASIS,
  8235. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8236. * See the License for the specific language governing permissions and
  8237. * limitations under the License.
  8238. */
  8239. Object.defineProperty(Buffer$2, "__esModule", { value: true });
  8240. Buffer$2.Buffer = void 0;
  8241. /** Implements a FIFO buffer with a fixed size. */
  8242. let Buffer$1 = class Buffer {
  8243. #capacity;
  8244. #entries = [];
  8245. #onItemRemoved;
  8246. /**
  8247. * @param capacity The buffer capacity.
  8248. * @param onItemRemoved Delegate called for each removed element.
  8249. */
  8250. constructor(capacity, onItemRemoved) {
  8251. this.#capacity = capacity;
  8252. this.#onItemRemoved = onItemRemoved;
  8253. }
  8254. get() {
  8255. return this.#entries;
  8256. }
  8257. add(value) {
  8258. this.#entries.push(value);
  8259. while (this.#entries.length > this.#capacity) {
  8260. const item = this.#entries.shift();
  8261. if (item !== undefined) {
  8262. this.#onItemRemoved?.(item);
  8263. }
  8264. }
  8265. }
  8266. };
  8267. Buffer$2.Buffer = Buffer$1;
  8268. var DefaultMap$1 = {};
  8269. /**
  8270. * Copyright 2023 Google LLC.
  8271. * Copyright (c) Microsoft Corporation.
  8272. *
  8273. * Licensed under the Apache License, Version 2.0 (the "License");
  8274. * you may not use this file except in compliance with the License.
  8275. * You may obtain a copy of the License at
  8276. *
  8277. * http://www.apache.org/licenses/LICENSE-2.0
  8278. *
  8279. * Unless required by applicable law or agreed to in writing, software
  8280. * distributed under the License is distributed on an "AS IS" BASIS,
  8281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8282. * See the License for the specific language governing permissions and
  8283. * limitations under the License.
  8284. */
  8285. Object.defineProperty(DefaultMap$1, "__esModule", { value: true });
  8286. DefaultMap$1.DefaultMap = void 0;
  8287. /**
  8288. * A subclass of Map whose functionality is almost the same as its parent
  8289. * except for the fact that DefaultMap never returns undefined. It provides a
  8290. * default value for keys that do not exist.
  8291. */
  8292. class DefaultMap extends Map {
  8293. /** The default value to return whenever a key is not present in the map. */
  8294. #getDefaultValue;
  8295. constructor(getDefaultValue, entries) {
  8296. super(entries);
  8297. this.#getDefaultValue = getDefaultValue;
  8298. }
  8299. get(key) {
  8300. if (!this.has(key)) {
  8301. this.set(key, this.#getDefaultValue(key));
  8302. }
  8303. return super.get(key);
  8304. }
  8305. }
  8306. DefaultMap$1.DefaultMap = DefaultMap;
  8307. var IdWrapper$1 = {};
  8308. /**
  8309. * Copyright 2022 Google LLC.
  8310. * Copyright (c) Microsoft Corporation.
  8311. *
  8312. * Licensed under the Apache License, Version 2.0 (the "License");
  8313. * you may not use this file except in compliance with the License.
  8314. * You may obtain a copy of the License at
  8315. *
  8316. * http://www.apache.org/licenses/LICENSE-2.0
  8317. *
  8318. * Unless required by applicable law or agreed to in writing, software
  8319. * distributed under the License is distributed on an "AS IS" BASIS,
  8320. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8321. * See the License for the specific language governing permissions and
  8322. * limitations under the License.
  8323. */
  8324. Object.defineProperty(IdWrapper$1, "__esModule", { value: true });
  8325. IdWrapper$1.IdWrapper = void 0;
  8326. /**
  8327. * Creates an object with a positive unique incrementing id.
  8328. */
  8329. class IdWrapper {
  8330. static #counter = 0;
  8331. #id;
  8332. constructor() {
  8333. this.#id = ++IdWrapper.#counter;
  8334. }
  8335. get id() {
  8336. return this.#id;
  8337. }
  8338. }
  8339. IdWrapper$1.IdWrapper = IdWrapper;
  8340. var events = {};
  8341. Object.defineProperty(events, "__esModule", { value: true });
  8342. events.assertSupportedEvent = events.isCdpEvent = void 0;
  8343. /**
  8344. * Copyright 2023 Google LLC.
  8345. * Copyright (c) Microsoft Corporation.
  8346. *
  8347. * Licensed under the Apache License, Version 2.0 (the "License");
  8348. * you may not use this file except in compliance with the License.
  8349. * You may obtain a copy of the License at
  8350. *
  8351. * http://www.apache.org/licenses/LICENSE-2.0
  8352. *
  8353. * Unless required by applicable law or agreed to in writing, software
  8354. * distributed under the License is distributed on an "AS IS" BASIS,
  8355. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8356. * See the License for the specific language governing permissions and
  8357. * limitations under the License.
  8358. */
  8359. const protocol_js_1$3 = protocol;
  8360. /**
  8361. * Returns true if the given event is a CDP event.
  8362. * @see https://chromedevtools.github.io/devtools-protocol/
  8363. */
  8364. function isCdpEvent(name) {
  8365. return (name.split('.').at(0)?.startsWith(protocol_js_1$3.ChromiumBidi.BiDiModule.Cdp) ?? false);
  8366. }
  8367. events.isCdpEvent = isCdpEvent;
  8368. /**
  8369. * Asserts that the given event is known to BiDi or BiDi+, or throws otherwise.
  8370. */
  8371. function assertSupportedEvent(name) {
  8372. if (!protocol_js_1$3.ChromiumBidi.EVENT_NAMES.has(name) && !isCdpEvent(name)) {
  8373. throw new protocol_js_1$3.InvalidArgumentException(`Unknown event: ${name}`);
  8374. }
  8375. }
  8376. events.assertSupportedEvent = assertSupportedEvent;
  8377. var SubscriptionManager$1 = {};
  8378. /**
  8379. * Copyright 2022 Google LLC.
  8380. * Copyright (c) Microsoft Corporation.
  8381. *
  8382. * Licensed under the Apache License, Version 2.0 (the "License");
  8383. * you may not use this file except in compliance with the License.
  8384. * You may obtain a copy of the License at
  8385. *
  8386. * http://www.apache.org/licenses/LICENSE-2.0
  8387. *
  8388. * Unless required by applicable law or agreed to in writing, software
  8389. * distributed under the License is distributed on an "AS IS" BASIS,
  8390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8391. * See the License for the specific language governing permissions and
  8392. * limitations under the License.
  8393. */
  8394. Object.defineProperty(SubscriptionManager$1, "__esModule", { value: true });
  8395. SubscriptionManager$1.SubscriptionManager = SubscriptionManager$1.unrollEvents = SubscriptionManager$1.cartesianProduct = void 0;
  8396. const protocol_js_1$2 = protocol;
  8397. const events_js_1$1 = events;
  8398. /**
  8399. * Returns the cartesian product of the given arrays.
  8400. *
  8401. * Example:
  8402. * cartesian([1, 2], ['a', 'b']); => [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
  8403. */
  8404. function cartesianProduct(...a) {
  8405. return a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e].flat())));
  8406. }
  8407. SubscriptionManager$1.cartesianProduct = cartesianProduct;
  8408. /** Expands "AllEvents" events into atomic events. */
  8409. function unrollEvents(events) {
  8410. const allEvents = new Set();
  8411. function addEvents(events) {
  8412. for (const event of events) {
  8413. allEvents.add(event);
  8414. }
  8415. }
  8416. for (const event of events) {
  8417. switch (event) {
  8418. case protocol_js_1$2.ChromiumBidi.BiDiModule.BrowsingContext:
  8419. addEvents(Object.values(protocol_js_1$2.ChromiumBidi.BrowsingContext.EventNames));
  8420. break;
  8421. case protocol_js_1$2.ChromiumBidi.BiDiModule.Log:
  8422. addEvents(Object.values(protocol_js_1$2.ChromiumBidi.Log.EventNames));
  8423. break;
  8424. case protocol_js_1$2.ChromiumBidi.BiDiModule.Network:
  8425. addEvents(Object.values(protocol_js_1$2.ChromiumBidi.Network.EventNames));
  8426. break;
  8427. case protocol_js_1$2.ChromiumBidi.BiDiModule.Script:
  8428. addEvents(Object.values(protocol_js_1$2.ChromiumBidi.Script.EventNames));
  8429. break;
  8430. default:
  8431. allEvents.add(event);
  8432. }
  8433. }
  8434. return [...allEvents.values()];
  8435. }
  8436. SubscriptionManager$1.unrollEvents = unrollEvents;
  8437. class SubscriptionManager {
  8438. #subscriptionPriority = 0;
  8439. // BrowsingContext `null` means the event has subscription across all the
  8440. // browsing contexts.
  8441. // Channel `null` means no `channel` should be added.
  8442. #channelToContextToEventMap = new Map();
  8443. #browsingContextStorage;
  8444. constructor(browsingContextStorage) {
  8445. this.#browsingContextStorage = browsingContextStorage;
  8446. }
  8447. getChannelsSubscribedToEvent(eventMethod, contextId) {
  8448. const prioritiesAndChannels = Array.from(this.#channelToContextToEventMap.keys())
  8449. .map((channel) => ({
  8450. priority: this.#getEventSubscriptionPriorityForChannel(eventMethod, contextId, channel),
  8451. channel,
  8452. }))
  8453. .filter(({ priority }) => priority !== null);
  8454. // Sort channels by priority.
  8455. return prioritiesAndChannels
  8456. .sort((a, b) => a.priority - b.priority)
  8457. .map(({ channel }) => channel);
  8458. }
  8459. #getEventSubscriptionPriorityForChannel(eventMethod, contextId, channel) {
  8460. const contextToEventMap = this.#channelToContextToEventMap.get(channel);
  8461. if (contextToEventMap === undefined) {
  8462. return null;
  8463. }
  8464. const maybeTopLevelContextId = this.#browsingContextStorage.findTopLevelContextId(contextId);
  8465. // `null` covers global subscription.
  8466. const relevantContexts = [...new Set([null, maybeTopLevelContextId])];
  8467. // Get all the subscription priorities.
  8468. const priorities = relevantContexts
  8469. .map((context) => {
  8470. // Get the priority for exact event name
  8471. const priority = contextToEventMap.get(context)?.get(eventMethod);
  8472. // For CDP we can't provide specific event name when subscribing
  8473. // to the module directly.
  8474. // Because of that we need to see event `cdp` exits in the map.
  8475. if ((0, events_js_1$1.isCdpEvent)(eventMethod)) {
  8476. const cdpPriority = contextToEventMap
  8477. .get(context)
  8478. ?.get(protocol_js_1$2.ChromiumBidi.BiDiModule.Cdp);
  8479. // If we subscribe to the event directly and `cdp` module as well
  8480. // priority will be different we take minimal priority
  8481. return priority && cdpPriority
  8482. ? Math.min(priority, cdpPriority)
  8483. : // At this point we know that we have subscribed
  8484. // to only one of the two
  8485. priority ?? cdpPriority;
  8486. }
  8487. return priority;
  8488. })
  8489. .filter((p) => p !== undefined);
  8490. if (priorities.length === 0) {
  8491. // Not subscribed, return null.
  8492. return null;
  8493. }
  8494. // Return minimal priority.
  8495. return Math.min(...priorities);
  8496. }
  8497. /**
  8498. * @param module BiDi+ module
  8499. * @param contextId `null` == globally subscribed
  8500. *
  8501. * @returns
  8502. */
  8503. isSubscribedTo(moduleOrEvent, contextId = null) {
  8504. const topLevelContext = this.#browsingContextStorage.findTopLevelContextId(contextId);
  8505. for (const browserContextToEventMap of this.#channelToContextToEventMap.values()) {
  8506. for (const [id, eventMap] of browserContextToEventMap.entries()) {
  8507. // Not subscribed to this context or globally
  8508. if (topLevelContext !== id && id !== null) {
  8509. continue;
  8510. }
  8511. for (const event of eventMap.keys()) {
  8512. // This also covers the `cdp` case where
  8513. // we don't unroll the event names
  8514. if (
  8515. // Event explicitly subscribed
  8516. event === moduleOrEvent ||
  8517. // Event subscribed via module
  8518. event === moduleOrEvent.split('.').at(0) ||
  8519. // Event explicitly subscribed compared to module
  8520. event.split('.').at(0) === moduleOrEvent) {
  8521. return true;
  8522. }
  8523. }
  8524. }
  8525. }
  8526. return false;
  8527. }
  8528. subscribe(event, contextId, channel) {
  8529. // All the subscriptions are handled on the top-level contexts.
  8530. contextId = this.#browsingContextStorage.findTopLevelContextId(contextId);
  8531. // Check if subscribed event is a whole module
  8532. switch (event) {
  8533. case protocol_js_1$2.ChromiumBidi.BiDiModule.BrowsingContext:
  8534. Object.values(protocol_js_1$2.ChromiumBidi.BrowsingContext.EventNames).map((specificEvent) => this.subscribe(specificEvent, contextId, channel));
  8535. return;
  8536. case protocol_js_1$2.ChromiumBidi.BiDiModule.Log:
  8537. Object.values(protocol_js_1$2.ChromiumBidi.Log.EventNames).map((specificEvent) => this.subscribe(specificEvent, contextId, channel));
  8538. return;
  8539. case protocol_js_1$2.ChromiumBidi.BiDiModule.Network:
  8540. Object.values(protocol_js_1$2.ChromiumBidi.Network.EventNames).map((specificEvent) => this.subscribe(specificEvent, contextId, channel));
  8541. return;
  8542. case protocol_js_1$2.ChromiumBidi.BiDiModule.Script:
  8543. Object.values(protocol_js_1$2.ChromiumBidi.Script.EventNames).map((specificEvent) => this.subscribe(specificEvent, contextId, channel));
  8544. return;
  8545. // Intentionally left empty.
  8546. }
  8547. if (!this.#channelToContextToEventMap.has(channel)) {
  8548. this.#channelToContextToEventMap.set(channel, new Map());
  8549. }
  8550. const contextToEventMap = this.#channelToContextToEventMap.get(channel);
  8551. if (!contextToEventMap.has(contextId)) {
  8552. contextToEventMap.set(contextId, new Map());
  8553. }
  8554. const eventMap = contextToEventMap.get(contextId);
  8555. // Do not re-subscribe to events to keep the priority.
  8556. if (eventMap.has(event)) {
  8557. return;
  8558. }
  8559. eventMap.set(event, this.#subscriptionPriority++);
  8560. }
  8561. /**
  8562. * Unsubscribes atomically from all events in the given contexts and channel.
  8563. */
  8564. unsubscribeAll(events, contextIds, channel) {
  8565. // Assert all contexts are known.
  8566. for (const contextId of contextIds) {
  8567. if (contextId !== null) {
  8568. this.#browsingContextStorage.getContext(contextId);
  8569. }
  8570. }
  8571. const eventContextPairs = cartesianProduct(unrollEvents(events), contextIds);
  8572. // Assert all unsubscriptions are valid.
  8573. // If any of the unsubscriptions are invalid, do not unsubscribe from anything.
  8574. eventContextPairs
  8575. .map(([event, contextId]) => this.#checkUnsubscribe(event, contextId, channel))
  8576. .forEach((unsubscribe) => unsubscribe());
  8577. }
  8578. /**
  8579. * Unsubscribes from the event in the given context and channel.
  8580. * Syntactic sugar for "unsubscribeAll".
  8581. */
  8582. unsubscribe(eventName, contextId, channel) {
  8583. this.unsubscribeAll([eventName], [contextId], channel);
  8584. }
  8585. #checkUnsubscribe(event, contextId, channel) {
  8586. // All the subscriptions are handled on the top-level contexts.
  8587. contextId = this.#browsingContextStorage.findTopLevelContextId(contextId);
  8588. if (!this.#channelToContextToEventMap.has(channel)) {
  8589. throw new protocol_js_1$2.InvalidArgumentException(`Cannot unsubscribe from ${event}, ${contextId === null ? 'null' : contextId}. No subscription found.`);
  8590. }
  8591. const contextToEventMap = this.#channelToContextToEventMap.get(channel);
  8592. if (!contextToEventMap.has(contextId)) {
  8593. throw new protocol_js_1$2.InvalidArgumentException(`Cannot unsubscribe from ${event}, ${contextId === null ? 'null' : contextId}. No subscription found.`);
  8594. }
  8595. const eventMap = contextToEventMap.get(contextId);
  8596. if (!eventMap.has(event)) {
  8597. throw new protocol_js_1$2.InvalidArgumentException(`Cannot unsubscribe from ${event}, ${contextId === null ? 'null' : contextId}. No subscription found.`);
  8598. }
  8599. return () => {
  8600. eventMap.delete(event);
  8601. // Clean up maps if empty.
  8602. if (eventMap.size === 0) {
  8603. contextToEventMap.delete(event);
  8604. }
  8605. if (contextToEventMap.size === 0) {
  8606. this.#channelToContextToEventMap.delete(channel);
  8607. }
  8608. };
  8609. }
  8610. }
  8611. SubscriptionManager$1.SubscriptionManager = SubscriptionManager;
  8612. /**
  8613. * Copyright 2022 Google LLC.
  8614. * Copyright (c) Microsoft Corporation.
  8615. *
  8616. * Licensed under the Apache License, Version 2.0 (the "License");
  8617. * you may not use this file except in compliance with the License.
  8618. * You may obtain a copy of the License at
  8619. *
  8620. * http://www.apache.org/licenses/LICENSE-2.0
  8621. *
  8622. * Unless required by applicable law or agreed to in writing, software
  8623. * distributed under the License is distributed on an "AS IS" BASIS,
  8624. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8625. * See the License for the specific language governing permissions and
  8626. * limitations under the License.
  8627. */
  8628. Object.defineProperty(EventManager$1, "__esModule", { value: true });
  8629. EventManager$1.EventManager = void 0;
  8630. const protocol_js_1$1 = protocol;
  8631. const Buffer_js_1 = Buffer$2;
  8632. const DefaultMap_js_1 = DefaultMap$1;
  8633. const EventEmitter_js_1$2 = EventEmitter$1;
  8634. const IdWrapper_js_1 = IdWrapper$1;
  8635. const OutgoingMessage_js_1 = OutgoingMessage$1;
  8636. const events_js_1 = events;
  8637. const SubscriptionManager_js_1 = SubscriptionManager$1;
  8638. class EventWrapper {
  8639. #idWrapper = new IdWrapper_js_1.IdWrapper();
  8640. #contextId;
  8641. #event;
  8642. constructor(event, contextId) {
  8643. this.#event = event;
  8644. this.#contextId = contextId;
  8645. }
  8646. get id() {
  8647. return this.#idWrapper.id;
  8648. }
  8649. get contextId() {
  8650. return this.#contextId;
  8651. }
  8652. get event() {
  8653. return this.#event;
  8654. }
  8655. }
  8656. /**
  8657. * Maps event name to a desired buffer length.
  8658. */
  8659. const eventBufferLength = new Map([[protocol_js_1$1.ChromiumBidi.Log.EventNames.LogEntryAdded, 100]]);
  8660. class EventManager extends EventEmitter_js_1$2.EventEmitter {
  8661. /**
  8662. * Maps event name to a set of contexts where this event already happened.
  8663. * Needed for getting buffered events from all the contexts in case of
  8664. * subscripting to all contexts.
  8665. */
  8666. #eventToContextsMap = new DefaultMap_js_1.DefaultMap(() => new Set());
  8667. /**
  8668. * Maps `eventName` + `browsingContext` to buffer. Used to get buffered events
  8669. * during subscription. Channel-agnostic.
  8670. */
  8671. #eventBuffers = new Map();
  8672. /**
  8673. * Maps `eventName` + `browsingContext` + `channel` to last sent event id.
  8674. * Used to avoid sending duplicated events when user
  8675. * subscribes -> unsubscribes -> subscribes.
  8676. */
  8677. #lastMessageSent = new Map();
  8678. #subscriptionManager;
  8679. #browsingContextStorage;
  8680. constructor(browsingContextStorage) {
  8681. super();
  8682. this.#browsingContextStorage = browsingContextStorage;
  8683. this.#subscriptionManager = new SubscriptionManager_js_1.SubscriptionManager(browsingContextStorage);
  8684. }
  8685. get subscriptionManager() {
  8686. return this.#subscriptionManager;
  8687. }
  8688. /**
  8689. * Returns consistent key to be used to access value maps.
  8690. */
  8691. static #getMapKey(eventName, browsingContext, channel) {
  8692. return JSON.stringify({ eventName, browsingContext, channel });
  8693. }
  8694. registerEvent(event, contextId) {
  8695. this.registerPromiseEvent(Promise.resolve({
  8696. kind: 'success',
  8697. value: event,
  8698. }), contextId, event.method);
  8699. }
  8700. registerPromiseEvent(event, contextId, eventName) {
  8701. const eventWrapper = new EventWrapper(event, contextId);
  8702. const sortedChannels = this.#subscriptionManager.getChannelsSubscribedToEvent(eventName, contextId);
  8703. this.#bufferEvent(eventWrapper, eventName);
  8704. // Send events to channels in the subscription priority.
  8705. for (const channel of sortedChannels) {
  8706. this.emit("event" /* EventManagerEvents.Event */, {
  8707. message: OutgoingMessage_js_1.OutgoingMessage.createFromPromise(event, channel),
  8708. event: eventName,
  8709. });
  8710. this.#markEventSent(eventWrapper, channel, eventName);
  8711. }
  8712. }
  8713. async subscribe(eventNames, contextIds, channel) {
  8714. for (const name of eventNames) {
  8715. (0, events_js_1.assertSupportedEvent)(name);
  8716. }
  8717. // First check if all the contexts are known.
  8718. for (const contextId of contextIds) {
  8719. if (contextId !== null) {
  8720. // Assert the context is known. Throw exception otherwise.
  8721. this.#browsingContextStorage.getContext(contextId);
  8722. }
  8723. }
  8724. for (const eventName of eventNames) {
  8725. for (const contextId of contextIds) {
  8726. this.#subscriptionManager.subscribe(eventName, contextId, channel);
  8727. for (const eventWrapper of this.#getBufferedEvents(eventName, contextId, channel)) {
  8728. // The order of the events is important.
  8729. this.emit("event" /* EventManagerEvents.Event */, {
  8730. message: OutgoingMessage_js_1.OutgoingMessage.createFromPromise(eventWrapper.event, channel),
  8731. event: eventName,
  8732. });
  8733. this.#markEventSent(eventWrapper, channel, eventName);
  8734. }
  8735. }
  8736. }
  8737. await this.toggleModulesIfNeeded();
  8738. }
  8739. async unsubscribe(eventNames, contextIds, channel) {
  8740. for (const name of eventNames) {
  8741. (0, events_js_1.assertSupportedEvent)(name);
  8742. }
  8743. this.#subscriptionManager.unsubscribeAll(eventNames, contextIds, channel);
  8744. await this.toggleModulesIfNeeded();
  8745. }
  8746. async toggleModulesIfNeeded() {
  8747. // TODO(1): Only update changed subscribers
  8748. // TODO(2): Enable for Worker Targets
  8749. await Promise.all(this.#browsingContextStorage.getAllContexts().map(async (context) => {
  8750. return await context.toggleModulesIfNeeded();
  8751. }));
  8752. }
  8753. /**
  8754. * If the event is buffer-able, put it in the buffer.
  8755. */
  8756. #bufferEvent(eventWrapper, eventName) {
  8757. if (!eventBufferLength.has(eventName)) {
  8758. // Do nothing if the event is no buffer-able.
  8759. return;
  8760. }
  8761. const bufferMapKey = EventManager.#getMapKey(eventName, eventWrapper.contextId);
  8762. if (!this.#eventBuffers.has(bufferMapKey)) {
  8763. this.#eventBuffers.set(bufferMapKey, new Buffer_js_1.Buffer(eventBufferLength.get(eventName)));
  8764. }
  8765. this.#eventBuffers.get(bufferMapKey).add(eventWrapper);
  8766. // Add the context to the list of contexts having `eventName` events.
  8767. this.#eventToContextsMap.get(eventName).add(eventWrapper.contextId);
  8768. }
  8769. /**
  8770. * If the event is buffer-able, mark it as sent to the given contextId and channel.
  8771. */
  8772. #markEventSent(eventWrapper, channel, eventName) {
  8773. if (!eventBufferLength.has(eventName)) {
  8774. // Do nothing if the event is no buffer-able.
  8775. return;
  8776. }
  8777. const lastSentMapKey = EventManager.#getMapKey(eventName, eventWrapper.contextId, channel);
  8778. this.#lastMessageSent.set(lastSentMapKey, Math.max(this.#lastMessageSent.get(lastSentMapKey) ?? 0, eventWrapper.id));
  8779. }
  8780. /**
  8781. * Returns events which are buffered and not yet sent to the given channel events.
  8782. */
  8783. #getBufferedEvents(eventName, contextId, channel) {
  8784. const bufferMapKey = EventManager.#getMapKey(eventName, contextId);
  8785. const lastSentMapKey = EventManager.#getMapKey(eventName, contextId, channel);
  8786. const lastSentMessageId = this.#lastMessageSent.get(lastSentMapKey) ?? -Infinity;
  8787. const result = this.#eventBuffers
  8788. .get(bufferMapKey)
  8789. ?.get()
  8790. .filter((wrapper) => wrapper.id > lastSentMessageId) ?? [];
  8791. if (contextId === null) {
  8792. // For global subscriptions, events buffered in each context should be sent back.
  8793. Array.from(this.#eventToContextsMap.get(eventName).keys())
  8794. .filter((_contextId) =>
  8795. // Events without context are already in the result.
  8796. _contextId !== null &&
  8797. // Events from deleted contexts should not be sent.
  8798. this.#browsingContextStorage.hasContext(_contextId))
  8799. .map((_contextId) => this.#getBufferedEvents(eventName, _contextId, channel))
  8800. .forEach((events) => result.push(...events));
  8801. }
  8802. return result.sort((e1, e2) => e1.id - e2.id);
  8803. }
  8804. }
  8805. EventManager$1.EventManager = EventManager;
  8806. /**
  8807. * Copyright 2021 Google LLC.
  8808. * Copyright (c) Microsoft Corporation.
  8809. *
  8810. * Licensed under the Apache License, Version 2.0 (the "License");
  8811. * you may not use this file except in compliance with the License.
  8812. * You may obtain a copy of the License at
  8813. *
  8814. * http://www.apache.org/licenses/LICENSE-2.0
  8815. *
  8816. * Unless required by applicable law or agreed to in writing, software
  8817. * distributed under the License is distributed on an "AS IS" BASIS,
  8818. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8819. * See the License for the specific language governing permissions and
  8820. * limitations under the License.
  8821. */
  8822. Object.defineProperty(BidiServer$1, "__esModule", { value: true });
  8823. BidiServer$1.BidiServer = void 0;
  8824. const EventEmitter_js_1$1 = EventEmitter$1;
  8825. const log_js_1$4 = log$1;
  8826. const ProcessingQueue_js_1 = ProcessingQueue$1;
  8827. const CommandProcessor_js_1 = CommandProcessor$1;
  8828. const CdpTargetManager_js_1 = CdpTargetManager$1;
  8829. const BrowsingContextStorage_js_1 = BrowsingContextStorage$1;
  8830. const NetworkStorage_js_1 = NetworkStorage$1;
  8831. const PreloadScriptStorage_js_1 = PreloadScriptStorage$1;
  8832. const RealmStorage_js_1 = RealmStorage$1;
  8833. const EventManager_js_1 = EventManager$1;
  8834. class BidiServer extends EventEmitter_js_1$1.EventEmitter {
  8835. #messageQueue;
  8836. #transport;
  8837. #commandProcessor;
  8838. #eventManager;
  8839. #browsingContextStorage = new BrowsingContextStorage_js_1.BrowsingContextStorage();
  8840. #realmStorage = new RealmStorage_js_1.RealmStorage();
  8841. #preloadScriptStorage = new PreloadScriptStorage_js_1.PreloadScriptStorage();
  8842. #logger;
  8843. #handleIncomingMessage = (message) => {
  8844. void this.#commandProcessor.processCommand(message).catch((error) => {
  8845. this.#logger?.(log_js_1$4.LogType.debugError, error);
  8846. });
  8847. };
  8848. #processOutgoingMessage = async (messageEntry) => {
  8849. const message = messageEntry.message;
  8850. if (messageEntry.channel !== null) {
  8851. message['channel'] = messageEntry.channel;
  8852. }
  8853. await this.#transport.sendMessage(message);
  8854. };
  8855. constructor(bidiTransport, cdpConnection, browserCdpClient, selfTargetId, defaultUserContextId, options, parser, logger) {
  8856. super();
  8857. this.#logger = logger;
  8858. this.#messageQueue = new ProcessingQueue_js_1.ProcessingQueue(this.#processOutgoingMessage, this.#logger);
  8859. this.#transport = bidiTransport;
  8860. this.#transport.setOnMessage(this.#handleIncomingMessage);
  8861. this.#eventManager = new EventManager_js_1.EventManager(this.#browsingContextStorage);
  8862. const networkStorage = new NetworkStorage_js_1.NetworkStorage(this.#eventManager, browserCdpClient, logger);
  8863. new CdpTargetManager_js_1.CdpTargetManager(cdpConnection, browserCdpClient, selfTargetId, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, networkStorage, this.#preloadScriptStorage, options?.acceptInsecureCerts ?? false, defaultUserContextId, logger);
  8864. this.#commandProcessor = new CommandProcessor_js_1.CommandProcessor(cdpConnection, browserCdpClient, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, this.#preloadScriptStorage, networkStorage, parser, this.#logger);
  8865. this.#eventManager.on("event" /* EventManagerEvents.Event */, ({ message, event }) => {
  8866. this.emitOutgoingMessage(message, event);
  8867. });
  8868. this.#commandProcessor.on("response" /* CommandProcessorEvents.Response */, ({ message, event }) => {
  8869. this.emitOutgoingMessage(message, event);
  8870. });
  8871. }
  8872. /**
  8873. * Creates and starts BiDi Mapper instance.
  8874. */
  8875. static async createAndStart(bidiTransport, cdpConnection, browserCdpClient, selfTargetId, options, parser, logger) {
  8876. // The default context is not exposed in Target.getBrowserContexts but can
  8877. // be observed via Target.getTargets. To determine the default browser
  8878. // context, we check which one is mentioned in Target.getTargets and not in
  8879. // Target.getBrowserContexts.
  8880. const [{ browserContextIds }, { targetInfos }] = await Promise.all([
  8881. browserCdpClient.sendCommand('Target.getBrowserContexts'),
  8882. browserCdpClient.sendCommand('Target.getTargets'),
  8883. ]);
  8884. let defaultUserContextId = 'default';
  8885. for (const info of targetInfos) {
  8886. if (info.browserContextId &&
  8887. !browserContextIds.includes(info.browserContextId)) {
  8888. defaultUserContextId = info.browserContextId;
  8889. break;
  8890. }
  8891. }
  8892. const server = new BidiServer(bidiTransport, cdpConnection, browserCdpClient, selfTargetId, defaultUserContextId, options, parser, logger);
  8893. // Needed to get events about new targets.
  8894. await browserCdpClient.sendCommand('Target.setDiscoverTargets', {
  8895. discover: true,
  8896. });
  8897. // Needed to automatically attach to new targets.
  8898. await browserCdpClient.sendCommand('Target.setAutoAttach', {
  8899. autoAttach: true,
  8900. waitForDebuggerOnStart: true,
  8901. flatten: true,
  8902. });
  8903. await server.#topLevelContextsLoaded();
  8904. return server;
  8905. }
  8906. /**
  8907. * Sends BiDi message.
  8908. */
  8909. emitOutgoingMessage(messageEntry, event) {
  8910. this.#messageQueue.add(messageEntry, event);
  8911. }
  8912. close() {
  8913. this.#transport.close();
  8914. }
  8915. async #topLevelContextsLoaded() {
  8916. await Promise.all(this.#browsingContextStorage
  8917. .getTopLevelContexts()
  8918. .map((c) => c.lifecycleLoaded()));
  8919. }
  8920. }
  8921. BidiServer$1.BidiServer = BidiServer;
  8922. (function (exports) {
  8923. /**
  8924. * Copyright 2022 Google LLC.
  8925. * Copyright (c) Microsoft Corporation.
  8926. *
  8927. * Licensed under the Apache License, Version 2.0 (the "License");
  8928. * you may not use this file except in compliance with the License.
  8929. * You may obtain a copy of the License at
  8930. *
  8931. * http://www.apache.org/licenses/LICENSE-2.0
  8932. *
  8933. * Unless required by applicable law or agreed to in writing, software
  8934. * distributed under the License is distributed on an "AS IS" BASIS,
  8935. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8936. * See the License for the specific language governing permissions and
  8937. * limitations under the License.
  8938. */
  8939. Object.defineProperty(exports, "__esModule", { value: true });
  8940. exports.OutgoingMessage = exports.EventEmitter = exports.BidiServer = void 0;
  8941. /**
  8942. * @fileoverview The entry point to the BiDi Mapper namespace.
  8943. * Other modules should only access exports defined in this file.
  8944. * XXX: Add ESlint rule for this (https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-restricted-paths.md)
  8945. */
  8946. var BidiServer_js_1 = BidiServer$1;
  8947. Object.defineProperty(exports, "BidiServer", { enumerable: true, get: function () { return BidiServer_js_1.BidiServer; } });
  8948. var EventEmitter_js_1 = EventEmitter$1;
  8949. Object.defineProperty(exports, "EventEmitter", { enumerable: true, get: function () { return EventEmitter_js_1.EventEmitter; } });
  8950. var OutgoingMessage_js_1 = OutgoingMessage$1;
  8951. Object.defineProperty(exports, "OutgoingMessage", { enumerable: true, get: function () { return OutgoingMessage_js_1.OutgoingMessage; } });
  8952. } (BidiMapper));
  8953. var CdpConnection = {};
  8954. var CdpClient = {};
  8955. /**
  8956. * Copyright 2021 Google LLC.
  8957. * Copyright (c) Microsoft Corporation.
  8958. *
  8959. * Licensed under the Apache License, Version 2.0 (the "License");
  8960. * you may not use this file except in compliance with the License.
  8961. * You may obtain a copy of the License at
  8962. *
  8963. * http://www.apache.org/licenses/LICENSE-2.0
  8964. *
  8965. * Unless required by applicable law or agreed to in writing, software
  8966. * distributed under the License is distributed on an "AS IS" BASIS,
  8967. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8968. * See the License for the specific language governing permissions and
  8969. * limitations under the License.
  8970. */
  8971. Object.defineProperty(CdpClient, "__esModule", { value: true });
  8972. CdpClient.MapperCdpClient = CdpClient.CloseError = void 0;
  8973. const EventEmitter_js_1 = EventEmitter$1;
  8974. /** A error that will be thrown if/when the connection is closed. */
  8975. class CloseError extends Error {
  8976. }
  8977. CdpClient.CloseError = CloseError;
  8978. /** Represents a high-level CDP connection to the browser. */
  8979. class MapperCdpClient extends EventEmitter_js_1.EventEmitter {
  8980. #cdpConnection;
  8981. #sessionId;
  8982. constructor(cdpConnection, sessionId) {
  8983. super();
  8984. this.#cdpConnection = cdpConnection;
  8985. this.#sessionId = sessionId;
  8986. }
  8987. get sessionId() {
  8988. return this.#sessionId;
  8989. }
  8990. sendCommand(method, ...params) {
  8991. return this.#cdpConnection.sendCommand(method, params[0], this.#sessionId);
  8992. }
  8993. isCloseError(error) {
  8994. return error instanceof CloseError;
  8995. }
  8996. }
  8997. CdpClient.MapperCdpClient = MapperCdpClient;
  8998. Object.defineProperty(CdpConnection, "__esModule", { value: true });
  8999. CdpConnection.MapperCdpConnection = void 0;
  9000. const log_js_1$3 = log$1;
  9001. const CdpClient_js_1 = CdpClient;
  9002. /**
  9003. * Represents a high-level CDP connection to the browser backend.
  9004. *
  9005. * Manages all CdpClients (each backed by a Session ID) instance for each active
  9006. * CDP session.
  9007. */
  9008. class MapperCdpConnection {
  9009. static LOGGER_PREFIX_RECV = `${log_js_1$3.LogType.cdp}:RECV ◂`;
  9010. static LOGGER_PREFIX_SEND = `${log_js_1$3.LogType.cdp}:SEND ▸`;
  9011. #mainBrowserCdpClient;
  9012. #transport;
  9013. /** Map from session ID to CdpClient.
  9014. * `undefined` points to the main browser session. */
  9015. #sessionCdpClients = new Map();
  9016. #commandCallbacks = new Map();
  9017. #logger;
  9018. #nextId = 0;
  9019. constructor(transport, logger) {
  9020. this.#transport = transport;
  9021. this.#logger = logger;
  9022. this.#transport.setOnMessage(this.#onMessage);
  9023. // Create default Browser CDP Session.
  9024. this.#mainBrowserCdpClient = this.#createCdpClient(undefined);
  9025. }
  9026. /** Closes the connection to the browser. */
  9027. close() {
  9028. this.#transport.close();
  9029. for (const [, { reject, error }] of this.#commandCallbacks) {
  9030. reject(error);
  9031. }
  9032. this.#commandCallbacks.clear();
  9033. this.#sessionCdpClients.clear();
  9034. }
  9035. async createBrowserSession() {
  9036. const { sessionId } = await this.#mainBrowserCdpClient.sendCommand('Target.attachToBrowserTarget');
  9037. return this.#createCdpClient(sessionId);
  9038. }
  9039. /**
  9040. * Gets a CdpClient instance attached to the given session ID,
  9041. * or null if the session is not attached.
  9042. */
  9043. getCdpClient(sessionId) {
  9044. const cdpClient = this.#sessionCdpClients.get(sessionId);
  9045. if (!cdpClient) {
  9046. throw new Error(`Unknown CDP session ID: ${sessionId}`);
  9047. }
  9048. return cdpClient;
  9049. }
  9050. sendCommand(method, params, sessionId) {
  9051. return new Promise((resolve, reject) => {
  9052. const id = this.#nextId++;
  9053. this.#commandCallbacks.set(id, {
  9054. resolve,
  9055. reject,
  9056. error: new CdpClient_js_1.CloseError(`${method} ${JSON.stringify(params)} ${sessionId ?? ''} call rejected because the connection has been closed.`),
  9057. });
  9058. const cdpMessage = { id, method, params };
  9059. if (sessionId) {
  9060. cdpMessage.sessionId = sessionId;
  9061. }
  9062. void this.#transport
  9063. .sendMessage(JSON.stringify(cdpMessage))
  9064. ?.catch((error) => {
  9065. this.#logger?.(log_js_1$3.LogType.debugError, error);
  9066. this.#transport.close();
  9067. });
  9068. this.#logger?.(MapperCdpConnection.LOGGER_PREFIX_SEND, cdpMessage);
  9069. });
  9070. }
  9071. #onMessage = (json) => {
  9072. const message = JSON.parse(json);
  9073. this.#logger?.(MapperCdpConnection.LOGGER_PREFIX_RECV, message);
  9074. // Update client map if a session is attached
  9075. // Listen for these events on every session.
  9076. if (message.method === 'Target.attachedToTarget') {
  9077. const { sessionId } = message.params;
  9078. this.#createCdpClient(sessionId);
  9079. }
  9080. if (message.id !== undefined) {
  9081. // Handle command response.
  9082. const callbacks = this.#commandCallbacks.get(message.id);
  9083. this.#commandCallbacks.delete(message.id);
  9084. if (callbacks) {
  9085. if (message.result) {
  9086. callbacks.resolve(message.result);
  9087. }
  9088. else if (message.error) {
  9089. callbacks.reject(message.error);
  9090. }
  9091. }
  9092. }
  9093. else if (message.method) {
  9094. const client = this.#sessionCdpClients.get(message.sessionId ?? undefined);
  9095. client?.emit(message.method, message.params || {});
  9096. // Update client map if a session is detached
  9097. // But emit on that session
  9098. if (message.method === 'Target.detachedFromTarget') {
  9099. const { sessionId } = message.params;
  9100. const client = this.#sessionCdpClients.get(sessionId);
  9101. if (client) {
  9102. this.#sessionCdpClients.delete(sessionId);
  9103. client.removeAllListeners();
  9104. }
  9105. }
  9106. }
  9107. };
  9108. /**
  9109. * Creates a new CdpClient instance for the given session ID.
  9110. * @param sessionId either a string, or undefined for the main browser session.
  9111. * The main browser session is used only to create new browser sessions.
  9112. * @private
  9113. */
  9114. #createCdpClient(sessionId) {
  9115. const cdpClient = new CdpClient_js_1.MapperCdpClient(this, sessionId);
  9116. this.#sessionCdpClients.set(sessionId, cdpClient);
  9117. return cdpClient;
  9118. }
  9119. }
  9120. CdpConnection.MapperCdpConnection = MapperCdpConnection;
  9121. var BidiParser$1 = {};
  9122. var protocolParser = {};
  9123. var lib = {};
  9124. var external = {};
  9125. var errors = {};
  9126. var en = {};
  9127. var util = {};
  9128. (function (exports) {
  9129. Object.defineProperty(exports, "__esModule", { value: true });
  9130. exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0;
  9131. var util;
  9132. (function (util) {
  9133. util.assertEqual = (val) => val;
  9134. function assertIs(_arg) { }
  9135. util.assertIs = assertIs;
  9136. function assertNever(_x) {
  9137. throw new Error();
  9138. }
  9139. util.assertNever = assertNever;
  9140. util.arrayToEnum = (items) => {
  9141. const obj = {};
  9142. for (const item of items) {
  9143. obj[item] = item;
  9144. }
  9145. return obj;
  9146. };
  9147. util.getValidEnumValues = (obj) => {
  9148. const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
  9149. const filtered = {};
  9150. for (const k of validKeys) {
  9151. filtered[k] = obj[k];
  9152. }
  9153. return util.objectValues(filtered);
  9154. };
  9155. util.objectValues = (obj) => {
  9156. return util.objectKeys(obj).map(function (e) {
  9157. return obj[e];
  9158. });
  9159. };
  9160. util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
  9161. ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
  9162. : (object) => {
  9163. const keys = [];
  9164. for (const key in object) {
  9165. if (Object.prototype.hasOwnProperty.call(object, key)) {
  9166. keys.push(key);
  9167. }
  9168. }
  9169. return keys;
  9170. };
  9171. util.find = (arr, checker) => {
  9172. for (const item of arr) {
  9173. if (checker(item))
  9174. return item;
  9175. }
  9176. return undefined;
  9177. };
  9178. util.isInteger = typeof Number.isInteger === "function"
  9179. ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
  9180. : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
  9181. function joinValues(array, separator = " | ") {
  9182. return array
  9183. .map((val) => (typeof val === "string" ? `'${val}'` : val))
  9184. .join(separator);
  9185. }
  9186. util.joinValues = joinValues;
  9187. util.jsonStringifyReplacer = (_, value) => {
  9188. if (typeof value === "bigint") {
  9189. return value.toString();
  9190. }
  9191. return value;
  9192. };
  9193. })(util = exports.util || (exports.util = {}));
  9194. (function (objectUtil) {
  9195. objectUtil.mergeShapes = (first, second) => {
  9196. return {
  9197. ...first,
  9198. ...second, // second overwrites first
  9199. };
  9200. };
  9201. })(exports.objectUtil || (exports.objectUtil = {}));
  9202. exports.ZodParsedType = util.arrayToEnum([
  9203. "string",
  9204. "nan",
  9205. "number",
  9206. "integer",
  9207. "float",
  9208. "boolean",
  9209. "date",
  9210. "bigint",
  9211. "symbol",
  9212. "function",
  9213. "undefined",
  9214. "null",
  9215. "array",
  9216. "object",
  9217. "unknown",
  9218. "promise",
  9219. "void",
  9220. "never",
  9221. "map",
  9222. "set",
  9223. ]);
  9224. const getParsedType = (data) => {
  9225. const t = typeof data;
  9226. switch (t) {
  9227. case "undefined":
  9228. return exports.ZodParsedType.undefined;
  9229. case "string":
  9230. return exports.ZodParsedType.string;
  9231. case "number":
  9232. return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number;
  9233. case "boolean":
  9234. return exports.ZodParsedType.boolean;
  9235. case "function":
  9236. return exports.ZodParsedType.function;
  9237. case "bigint":
  9238. return exports.ZodParsedType.bigint;
  9239. case "symbol":
  9240. return exports.ZodParsedType.symbol;
  9241. case "object":
  9242. if (Array.isArray(data)) {
  9243. return exports.ZodParsedType.array;
  9244. }
  9245. if (data === null) {
  9246. return exports.ZodParsedType.null;
  9247. }
  9248. if (data.then &&
  9249. typeof data.then === "function" &&
  9250. data.catch &&
  9251. typeof data.catch === "function") {
  9252. return exports.ZodParsedType.promise;
  9253. }
  9254. if (typeof Map !== "undefined" && data instanceof Map) {
  9255. return exports.ZodParsedType.map;
  9256. }
  9257. if (typeof Set !== "undefined" && data instanceof Set) {
  9258. return exports.ZodParsedType.set;
  9259. }
  9260. if (typeof Date !== "undefined" && data instanceof Date) {
  9261. return exports.ZodParsedType.date;
  9262. }
  9263. return exports.ZodParsedType.object;
  9264. default:
  9265. return exports.ZodParsedType.unknown;
  9266. }
  9267. };
  9268. exports.getParsedType = getParsedType;
  9269. } (util));
  9270. var ZodError$1 = {};
  9271. Object.defineProperty(ZodError$1, "__esModule", { value: true });
  9272. ZodError$1.ZodError = ZodError$1.quotelessJson = ZodError$1.ZodIssueCode = void 0;
  9273. const util_1$1 = util;
  9274. ZodError$1.ZodIssueCode = util_1$1.util.arrayToEnum([
  9275. "invalid_type",
  9276. "invalid_literal",
  9277. "custom",
  9278. "invalid_union",
  9279. "invalid_union_discriminator",
  9280. "invalid_enum_value",
  9281. "unrecognized_keys",
  9282. "invalid_arguments",
  9283. "invalid_return_type",
  9284. "invalid_date",
  9285. "invalid_string",
  9286. "too_small",
  9287. "too_big",
  9288. "invalid_intersection_types",
  9289. "not_multiple_of",
  9290. "not_finite",
  9291. ]);
  9292. const quotelessJson = (obj) => {
  9293. const json = JSON.stringify(obj, null, 2);
  9294. return json.replace(/"([^"]+)":/g, "$1:");
  9295. };
  9296. ZodError$1.quotelessJson = quotelessJson;
  9297. class ZodError extends Error {
  9298. constructor(issues) {
  9299. super();
  9300. this.issues = [];
  9301. this.addIssue = (sub) => {
  9302. this.issues = [...this.issues, sub];
  9303. };
  9304. this.addIssues = (subs = []) => {
  9305. this.issues = [...this.issues, ...subs];
  9306. };
  9307. const actualProto = new.target.prototype;
  9308. if (Object.setPrototypeOf) {
  9309. // eslint-disable-next-line ban/ban
  9310. Object.setPrototypeOf(this, actualProto);
  9311. }
  9312. else {
  9313. this.__proto__ = actualProto;
  9314. }
  9315. this.name = "ZodError";
  9316. this.issues = issues;
  9317. }
  9318. get errors() {
  9319. return this.issues;
  9320. }
  9321. format(_mapper) {
  9322. const mapper = _mapper ||
  9323. function (issue) {
  9324. return issue.message;
  9325. };
  9326. const fieldErrors = { _errors: [] };
  9327. const processError = (error) => {
  9328. for (const issue of error.issues) {
  9329. if (issue.code === "invalid_union") {
  9330. issue.unionErrors.map(processError);
  9331. }
  9332. else if (issue.code === "invalid_return_type") {
  9333. processError(issue.returnTypeError);
  9334. }
  9335. else if (issue.code === "invalid_arguments") {
  9336. processError(issue.argumentsError);
  9337. }
  9338. else if (issue.path.length === 0) {
  9339. fieldErrors._errors.push(mapper(issue));
  9340. }
  9341. else {
  9342. let curr = fieldErrors;
  9343. let i = 0;
  9344. while (i < issue.path.length) {
  9345. const el = issue.path[i];
  9346. const terminal = i === issue.path.length - 1;
  9347. if (!terminal) {
  9348. curr[el] = curr[el] || { _errors: [] };
  9349. // if (typeof el === "string") {
  9350. // curr[el] = curr[el] || { _errors: [] };
  9351. // } else if (typeof el === "number") {
  9352. // const errorArray: any = [];
  9353. // errorArray._errors = [];
  9354. // curr[el] = curr[el] || errorArray;
  9355. // }
  9356. }
  9357. else {
  9358. curr[el] = curr[el] || { _errors: [] };
  9359. curr[el]._errors.push(mapper(issue));
  9360. }
  9361. curr = curr[el];
  9362. i++;
  9363. }
  9364. }
  9365. }
  9366. };
  9367. processError(this);
  9368. return fieldErrors;
  9369. }
  9370. toString() {
  9371. return this.message;
  9372. }
  9373. get message() {
  9374. return JSON.stringify(this.issues, util_1$1.util.jsonStringifyReplacer, 2);
  9375. }
  9376. get isEmpty() {
  9377. return this.issues.length === 0;
  9378. }
  9379. flatten(mapper = (issue) => issue.message) {
  9380. const fieldErrors = {};
  9381. const formErrors = [];
  9382. for (const sub of this.issues) {
  9383. if (sub.path.length > 0) {
  9384. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
  9385. fieldErrors[sub.path[0]].push(mapper(sub));
  9386. }
  9387. else {
  9388. formErrors.push(mapper(sub));
  9389. }
  9390. }
  9391. return { formErrors, fieldErrors };
  9392. }
  9393. get formErrors() {
  9394. return this.flatten();
  9395. }
  9396. }
  9397. ZodError$1.ZodError = ZodError;
  9398. ZodError.create = (issues) => {
  9399. const error = new ZodError(issues);
  9400. return error;
  9401. };
  9402. Object.defineProperty(en, "__esModule", { value: true });
  9403. const util_1 = util;
  9404. const ZodError_1 = ZodError$1;
  9405. const errorMap = (issue, _ctx) => {
  9406. let message;
  9407. switch (issue.code) {
  9408. case ZodError_1.ZodIssueCode.invalid_type:
  9409. if (issue.received === util_1.ZodParsedType.undefined) {
  9410. message = "Required";
  9411. }
  9412. else {
  9413. message = `Expected ${issue.expected}, received ${issue.received}`;
  9414. }
  9415. break;
  9416. case ZodError_1.ZodIssueCode.invalid_literal:
  9417. message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`;
  9418. break;
  9419. case ZodError_1.ZodIssueCode.unrecognized_keys:
  9420. message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`;
  9421. break;
  9422. case ZodError_1.ZodIssueCode.invalid_union:
  9423. message = `Invalid input`;
  9424. break;
  9425. case ZodError_1.ZodIssueCode.invalid_union_discriminator:
  9426. message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`;
  9427. break;
  9428. case ZodError_1.ZodIssueCode.invalid_enum_value:
  9429. message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`;
  9430. break;
  9431. case ZodError_1.ZodIssueCode.invalid_arguments:
  9432. message = `Invalid function arguments`;
  9433. break;
  9434. case ZodError_1.ZodIssueCode.invalid_return_type:
  9435. message = `Invalid function return type`;
  9436. break;
  9437. case ZodError_1.ZodIssueCode.invalid_date:
  9438. message = `Invalid date`;
  9439. break;
  9440. case ZodError_1.ZodIssueCode.invalid_string:
  9441. if (typeof issue.validation === "object") {
  9442. if ("includes" in issue.validation) {
  9443. message = `Invalid input: must include "${issue.validation.includes}"`;
  9444. if (typeof issue.validation.position === "number") {
  9445. message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
  9446. }
  9447. }
  9448. else if ("startsWith" in issue.validation) {
  9449. message = `Invalid input: must start with "${issue.validation.startsWith}"`;
  9450. }
  9451. else if ("endsWith" in issue.validation) {
  9452. message = `Invalid input: must end with "${issue.validation.endsWith}"`;
  9453. }
  9454. else {
  9455. util_1.util.assertNever(issue.validation);
  9456. }
  9457. }
  9458. else if (issue.validation !== "regex") {
  9459. message = `Invalid ${issue.validation}`;
  9460. }
  9461. else {
  9462. message = "Invalid";
  9463. }
  9464. break;
  9465. case ZodError_1.ZodIssueCode.too_small:
  9466. if (issue.type === "array")
  9467. message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
  9468. else if (issue.type === "string")
  9469. message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
  9470. else if (issue.type === "number")
  9471. message = `Number must be ${issue.exact
  9472. ? `exactly equal to `
  9473. : issue.inclusive
  9474. ? `greater than or equal to `
  9475. : `greater than `}${issue.minimum}`;
  9476. else if (issue.type === "date")
  9477. message = `Date must be ${issue.exact
  9478. ? `exactly equal to `
  9479. : issue.inclusive
  9480. ? `greater than or equal to `
  9481. : `greater than `}${new Date(Number(issue.minimum))}`;
  9482. else
  9483. message = "Invalid input";
  9484. break;
  9485. case ZodError_1.ZodIssueCode.too_big:
  9486. if (issue.type === "array")
  9487. message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
  9488. else if (issue.type === "string")
  9489. message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
  9490. else if (issue.type === "number")
  9491. message = `Number must be ${issue.exact
  9492. ? `exactly`
  9493. : issue.inclusive
  9494. ? `less than or equal to`
  9495. : `less than`} ${issue.maximum}`;
  9496. else if (issue.type === "bigint")
  9497. message = `BigInt must be ${issue.exact
  9498. ? `exactly`
  9499. : issue.inclusive
  9500. ? `less than or equal to`
  9501. : `less than`} ${issue.maximum}`;
  9502. else if (issue.type === "date")
  9503. message = `Date must be ${issue.exact
  9504. ? `exactly`
  9505. : issue.inclusive
  9506. ? `smaller than or equal to`
  9507. : `smaller than`} ${new Date(Number(issue.maximum))}`;
  9508. else
  9509. message = "Invalid input";
  9510. break;
  9511. case ZodError_1.ZodIssueCode.custom:
  9512. message = `Invalid input`;
  9513. break;
  9514. case ZodError_1.ZodIssueCode.invalid_intersection_types:
  9515. message = `Intersection results could not be merged`;
  9516. break;
  9517. case ZodError_1.ZodIssueCode.not_multiple_of:
  9518. message = `Number must be a multiple of ${issue.multipleOf}`;
  9519. break;
  9520. case ZodError_1.ZodIssueCode.not_finite:
  9521. message = "Number must be finite";
  9522. break;
  9523. default:
  9524. message = _ctx.defaultError;
  9525. util_1.util.assertNever(issue);
  9526. }
  9527. return { message };
  9528. };
  9529. en.default = errorMap;
  9530. var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  9531. return (mod && mod.__esModule) ? mod : { "default": mod };
  9532. };
  9533. Object.defineProperty(errors, "__esModule", { value: true });
  9534. errors.getErrorMap = errors.setErrorMap = errors.defaultErrorMap = void 0;
  9535. const en_1 = __importDefault$1(en);
  9536. errors.defaultErrorMap = en_1.default;
  9537. let overrideErrorMap = en_1.default;
  9538. function setErrorMap(map) {
  9539. overrideErrorMap = map;
  9540. }
  9541. errors.setErrorMap = setErrorMap;
  9542. function getErrorMap() {
  9543. return overrideErrorMap;
  9544. }
  9545. errors.getErrorMap = getErrorMap;
  9546. var parseUtil = {};
  9547. (function (exports) {
  9548. var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  9549. return (mod && mod.__esModule) ? mod : { "default": mod };
  9550. };
  9551. Object.defineProperty(exports, "__esModule", { value: true });
  9552. exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0;
  9553. const errors_1 = errors;
  9554. const en_1 = __importDefault(en);
  9555. const makeIssue = (params) => {
  9556. const { data, path, errorMaps, issueData } = params;
  9557. const fullPath = [...path, ...(issueData.path || [])];
  9558. const fullIssue = {
  9559. ...issueData,
  9560. path: fullPath,
  9561. };
  9562. let errorMessage = "";
  9563. const maps = errorMaps
  9564. .filter((m) => !!m)
  9565. .slice()
  9566. .reverse();
  9567. for (const map of maps) {
  9568. errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  9569. }
  9570. return {
  9571. ...issueData,
  9572. path: fullPath,
  9573. message: issueData.message || errorMessage,
  9574. };
  9575. };
  9576. exports.makeIssue = makeIssue;
  9577. exports.EMPTY_PATH = [];
  9578. function addIssueToContext(ctx, issueData) {
  9579. const issue = (0, exports.makeIssue)({
  9580. issueData: issueData,
  9581. data: ctx.data,
  9582. path: ctx.path,
  9583. errorMaps: [
  9584. ctx.common.contextualErrorMap,
  9585. ctx.schemaErrorMap,
  9586. (0, errors_1.getErrorMap)(),
  9587. en_1.default, // then global default map
  9588. ].filter((x) => !!x),
  9589. });
  9590. ctx.common.issues.push(issue);
  9591. }
  9592. exports.addIssueToContext = addIssueToContext;
  9593. class ParseStatus {
  9594. constructor() {
  9595. this.value = "valid";
  9596. }
  9597. dirty() {
  9598. if (this.value === "valid")
  9599. this.value = "dirty";
  9600. }
  9601. abort() {
  9602. if (this.value !== "aborted")
  9603. this.value = "aborted";
  9604. }
  9605. static mergeArray(status, results) {
  9606. const arrayValue = [];
  9607. for (const s of results) {
  9608. if (s.status === "aborted")
  9609. return exports.INVALID;
  9610. if (s.status === "dirty")
  9611. status.dirty();
  9612. arrayValue.push(s.value);
  9613. }
  9614. return { status: status.value, value: arrayValue };
  9615. }
  9616. static async mergeObjectAsync(status, pairs) {
  9617. const syncPairs = [];
  9618. for (const pair of pairs) {
  9619. syncPairs.push({
  9620. key: await pair.key,
  9621. value: await pair.value,
  9622. });
  9623. }
  9624. return ParseStatus.mergeObjectSync(status, syncPairs);
  9625. }
  9626. static mergeObjectSync(status, pairs) {
  9627. const finalObject = {};
  9628. for (const pair of pairs) {
  9629. const { key, value } = pair;
  9630. if (key.status === "aborted")
  9631. return exports.INVALID;
  9632. if (value.status === "aborted")
  9633. return exports.INVALID;
  9634. if (key.status === "dirty")
  9635. status.dirty();
  9636. if (value.status === "dirty")
  9637. status.dirty();
  9638. if (key.value !== "__proto__" &&
  9639. (typeof value.value !== "undefined" || pair.alwaysSet)) {
  9640. finalObject[key.value] = value.value;
  9641. }
  9642. }
  9643. return { status: status.value, value: finalObject };
  9644. }
  9645. }
  9646. exports.ParseStatus = ParseStatus;
  9647. exports.INVALID = Object.freeze({
  9648. status: "aborted",
  9649. });
  9650. const DIRTY = (value) => ({ status: "dirty", value });
  9651. exports.DIRTY = DIRTY;
  9652. const OK = (value) => ({ status: "valid", value });
  9653. exports.OK = OK;
  9654. const isAborted = (x) => x.status === "aborted";
  9655. exports.isAborted = isAborted;
  9656. const isDirty = (x) => x.status === "dirty";
  9657. exports.isDirty = isDirty;
  9658. const isValid = (x) => x.status === "valid";
  9659. exports.isValid = isValid;
  9660. const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
  9661. exports.isAsync = isAsync;
  9662. } (parseUtil));
  9663. var typeAliases = {};
  9664. Object.defineProperty(typeAliases, "__esModule", { value: true });
  9665. var types = {};
  9666. var errorUtil = {};
  9667. (function (exports) {
  9668. Object.defineProperty(exports, "__esModule", { value: true });
  9669. exports.errorUtil = void 0;
  9670. (function (errorUtil) {
  9671. errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  9672. errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
  9673. })(exports.errorUtil || (exports.errorUtil = {}));
  9674. } (errorUtil));
  9675. (function (exports) {
  9676. Object.defineProperty(exports, "__esModule", { value: true });
  9677. exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
  9678. exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = exports.discriminatedUnion = void 0;
  9679. const errors_1 = errors;
  9680. const errorUtil_1 = errorUtil;
  9681. const parseUtil_1 = parseUtil;
  9682. const util_1 = util;
  9683. const ZodError_1 = ZodError$1;
  9684. class ParseInputLazyPath {
  9685. constructor(parent, value, path, key) {
  9686. this._cachedPath = [];
  9687. this.parent = parent;
  9688. this.data = value;
  9689. this._path = path;
  9690. this._key = key;
  9691. }
  9692. get path() {
  9693. if (!this._cachedPath.length) {
  9694. if (this._key instanceof Array) {
  9695. this._cachedPath.push(...this._path, ...this._key);
  9696. }
  9697. else {
  9698. this._cachedPath.push(...this._path, this._key);
  9699. }
  9700. }
  9701. return this._cachedPath;
  9702. }
  9703. }
  9704. const handleResult = (ctx, result) => {
  9705. if ((0, parseUtil_1.isValid)(result)) {
  9706. return { success: true, data: result.value };
  9707. }
  9708. else {
  9709. if (!ctx.common.issues.length) {
  9710. throw new Error("Validation failed but no issues detected.");
  9711. }
  9712. return {
  9713. success: false,
  9714. get error() {
  9715. if (this._error)
  9716. return this._error;
  9717. const error = new ZodError_1.ZodError(ctx.common.issues);
  9718. this._error = error;
  9719. return this._error;
  9720. },
  9721. };
  9722. }
  9723. };
  9724. function processCreateParams(params) {
  9725. if (!params)
  9726. return {};
  9727. const { errorMap, invalid_type_error, required_error, description } = params;
  9728. if (errorMap && (invalid_type_error || required_error)) {
  9729. throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  9730. }
  9731. if (errorMap)
  9732. return { errorMap: errorMap, description };
  9733. const customMap = (iss, ctx) => {
  9734. if (iss.code !== "invalid_type")
  9735. return { message: ctx.defaultError };
  9736. if (typeof ctx.data === "undefined") {
  9737. return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
  9738. }
  9739. return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
  9740. };
  9741. return { errorMap: customMap, description };
  9742. }
  9743. class ZodType {
  9744. constructor(def) {
  9745. /** Alias of safeParseAsync */
  9746. this.spa = this.safeParseAsync;
  9747. this._def = def;
  9748. this.parse = this.parse.bind(this);
  9749. this.safeParse = this.safeParse.bind(this);
  9750. this.parseAsync = this.parseAsync.bind(this);
  9751. this.safeParseAsync = this.safeParseAsync.bind(this);
  9752. this.spa = this.spa.bind(this);
  9753. this.refine = this.refine.bind(this);
  9754. this.refinement = this.refinement.bind(this);
  9755. this.superRefine = this.superRefine.bind(this);
  9756. this.optional = this.optional.bind(this);
  9757. this.nullable = this.nullable.bind(this);
  9758. this.nullish = this.nullish.bind(this);
  9759. this.array = this.array.bind(this);
  9760. this.promise = this.promise.bind(this);
  9761. this.or = this.or.bind(this);
  9762. this.and = this.and.bind(this);
  9763. this.transform = this.transform.bind(this);
  9764. this.brand = this.brand.bind(this);
  9765. this.default = this.default.bind(this);
  9766. this.catch = this.catch.bind(this);
  9767. this.describe = this.describe.bind(this);
  9768. this.pipe = this.pipe.bind(this);
  9769. this.readonly = this.readonly.bind(this);
  9770. this.isNullable = this.isNullable.bind(this);
  9771. this.isOptional = this.isOptional.bind(this);
  9772. }
  9773. get description() {
  9774. return this._def.description;
  9775. }
  9776. _getType(input) {
  9777. return (0, util_1.getParsedType)(input.data);
  9778. }
  9779. _getOrReturnCtx(input, ctx) {
  9780. return (ctx || {
  9781. common: input.parent.common,
  9782. data: input.data,
  9783. parsedType: (0, util_1.getParsedType)(input.data),
  9784. schemaErrorMap: this._def.errorMap,
  9785. path: input.path,
  9786. parent: input.parent,
  9787. });
  9788. }
  9789. _processInputParams(input) {
  9790. return {
  9791. status: new parseUtil_1.ParseStatus(),
  9792. ctx: {
  9793. common: input.parent.common,
  9794. data: input.data,
  9795. parsedType: (0, util_1.getParsedType)(input.data),
  9796. schemaErrorMap: this._def.errorMap,
  9797. path: input.path,
  9798. parent: input.parent,
  9799. },
  9800. };
  9801. }
  9802. _parseSync(input) {
  9803. const result = this._parse(input);
  9804. if ((0, parseUtil_1.isAsync)(result)) {
  9805. throw new Error("Synchronous parse encountered promise.");
  9806. }
  9807. return result;
  9808. }
  9809. _parseAsync(input) {
  9810. const result = this._parse(input);
  9811. return Promise.resolve(result);
  9812. }
  9813. parse(data, params) {
  9814. const result = this.safeParse(data, params);
  9815. if (result.success)
  9816. return result.data;
  9817. throw result.error;
  9818. }
  9819. safeParse(data, params) {
  9820. var _a;
  9821. const ctx = {
  9822. common: {
  9823. issues: [],
  9824. async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
  9825. contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
  9826. },
  9827. path: (params === null || params === void 0 ? void 0 : params.path) || [],
  9828. schemaErrorMap: this._def.errorMap,
  9829. parent: null,
  9830. data,
  9831. parsedType: (0, util_1.getParsedType)(data),
  9832. };
  9833. const result = this._parseSync({ data, path: ctx.path, parent: ctx });
  9834. return handleResult(ctx, result);
  9835. }
  9836. async parseAsync(data, params) {
  9837. const result = await this.safeParseAsync(data, params);
  9838. if (result.success)
  9839. return result.data;
  9840. throw result.error;
  9841. }
  9842. async safeParseAsync(data, params) {
  9843. const ctx = {
  9844. common: {
  9845. issues: [],
  9846. contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
  9847. async: true,
  9848. },
  9849. path: (params === null || params === void 0 ? void 0 : params.path) || [],
  9850. schemaErrorMap: this._def.errorMap,
  9851. parent: null,
  9852. data,
  9853. parsedType: (0, util_1.getParsedType)(data),
  9854. };
  9855. const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
  9856. const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult)
  9857. ? maybeAsyncResult
  9858. : Promise.resolve(maybeAsyncResult));
  9859. return handleResult(ctx, result);
  9860. }
  9861. refine(check, message) {
  9862. const getIssueProperties = (val) => {
  9863. if (typeof message === "string" || typeof message === "undefined") {
  9864. return { message };
  9865. }
  9866. else if (typeof message === "function") {
  9867. return message(val);
  9868. }
  9869. else {
  9870. return message;
  9871. }
  9872. };
  9873. return this._refinement((val, ctx) => {
  9874. const result = check(val);
  9875. const setError = () => ctx.addIssue({
  9876. code: ZodError_1.ZodIssueCode.custom,
  9877. ...getIssueProperties(val),
  9878. });
  9879. if (typeof Promise !== "undefined" && result instanceof Promise) {
  9880. return result.then((data) => {
  9881. if (!data) {
  9882. setError();
  9883. return false;
  9884. }
  9885. else {
  9886. return true;
  9887. }
  9888. });
  9889. }
  9890. if (!result) {
  9891. setError();
  9892. return false;
  9893. }
  9894. else {
  9895. return true;
  9896. }
  9897. });
  9898. }
  9899. refinement(check, refinementData) {
  9900. return this._refinement((val, ctx) => {
  9901. if (!check(val)) {
  9902. ctx.addIssue(typeof refinementData === "function"
  9903. ? refinementData(val, ctx)
  9904. : refinementData);
  9905. return false;
  9906. }
  9907. else {
  9908. return true;
  9909. }
  9910. });
  9911. }
  9912. _refinement(refinement) {
  9913. return new ZodEffects({
  9914. schema: this,
  9915. typeName: ZodFirstPartyTypeKind.ZodEffects,
  9916. effect: { type: "refinement", refinement },
  9917. });
  9918. }
  9919. superRefine(refinement) {
  9920. return this._refinement(refinement);
  9921. }
  9922. optional() {
  9923. return ZodOptional.create(this, this._def);
  9924. }
  9925. nullable() {
  9926. return ZodNullable.create(this, this._def);
  9927. }
  9928. nullish() {
  9929. return this.nullable().optional();
  9930. }
  9931. array() {
  9932. return ZodArray.create(this, this._def);
  9933. }
  9934. promise() {
  9935. return ZodPromise.create(this, this._def);
  9936. }
  9937. or(option) {
  9938. return ZodUnion.create([this, option], this._def);
  9939. }
  9940. and(incoming) {
  9941. return ZodIntersection.create(this, incoming, this._def);
  9942. }
  9943. transform(transform) {
  9944. return new ZodEffects({
  9945. ...processCreateParams(this._def),
  9946. schema: this,
  9947. typeName: ZodFirstPartyTypeKind.ZodEffects,
  9948. effect: { type: "transform", transform },
  9949. });
  9950. }
  9951. default(def) {
  9952. const defaultValueFunc = typeof def === "function" ? def : () => def;
  9953. return new ZodDefault({
  9954. ...processCreateParams(this._def),
  9955. innerType: this,
  9956. defaultValue: defaultValueFunc,
  9957. typeName: ZodFirstPartyTypeKind.ZodDefault,
  9958. });
  9959. }
  9960. brand() {
  9961. return new ZodBranded({
  9962. typeName: ZodFirstPartyTypeKind.ZodBranded,
  9963. type: this,
  9964. ...processCreateParams(this._def),
  9965. });
  9966. }
  9967. catch(def) {
  9968. const catchValueFunc = typeof def === "function" ? def : () => def;
  9969. return new ZodCatch({
  9970. ...processCreateParams(this._def),
  9971. innerType: this,
  9972. catchValue: catchValueFunc,
  9973. typeName: ZodFirstPartyTypeKind.ZodCatch,
  9974. });
  9975. }
  9976. describe(description) {
  9977. const This = this.constructor;
  9978. return new This({
  9979. ...this._def,
  9980. description,
  9981. });
  9982. }
  9983. pipe(target) {
  9984. return ZodPipeline.create(this, target);
  9985. }
  9986. readonly() {
  9987. return ZodReadonly.create(this);
  9988. }
  9989. isOptional() {
  9990. return this.safeParse(undefined).success;
  9991. }
  9992. isNullable() {
  9993. return this.safeParse(null).success;
  9994. }
  9995. }
  9996. exports.ZodType = ZodType;
  9997. exports.Schema = ZodType;
  9998. exports.ZodSchema = ZodType;
  9999. const cuidRegex = /^c[^\s-]{8,}$/i;
  10000. const cuid2Regex = /^[a-z][a-z0-9]*$/;
  10001. const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
  10002. // const uuidRegex =
  10003. // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
  10004. const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
  10005. // from https://stackoverflow.com/a/46181/1550155
  10006. // old version: too slow, didn't support unicode
  10007. // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
  10008. //old email regex
  10009. // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
  10010. // eslint-disable-next-line
  10011. // const emailRegex =
  10012. // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
  10013. // const emailRegex =
  10014. // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  10015. // const emailRegex =
  10016. // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
  10017. const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
  10018. // const emailRegex =
  10019. // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
  10020. // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
  10021. const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
  10022. let emojiRegex;
  10023. const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
  10024. const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
  10025. // Adapted from https://stackoverflow.com/a/3143231
  10026. const datetimeRegex = (args) => {
  10027. if (args.precision) {
  10028. if (args.offset) {
  10029. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  10030. }
  10031. else {
  10032. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
  10033. }
  10034. }
  10035. else if (args.precision === 0) {
  10036. if (args.offset) {
  10037. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  10038. }
  10039. else {
  10040. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
  10041. }
  10042. }
  10043. else {
  10044. if (args.offset) {
  10045. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  10046. }
  10047. else {
  10048. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
  10049. }
  10050. }
  10051. };
  10052. function isValidIP(ip, version) {
  10053. if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
  10054. return true;
  10055. }
  10056. if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
  10057. return true;
  10058. }
  10059. return false;
  10060. }
  10061. class ZodString extends ZodType {
  10062. _parse(input) {
  10063. if (this._def.coerce) {
  10064. input.data = String(input.data);
  10065. }
  10066. const parsedType = this._getType(input);
  10067. if (parsedType !== util_1.ZodParsedType.string) {
  10068. const ctx = this._getOrReturnCtx(input);
  10069. (0, parseUtil_1.addIssueToContext)(ctx, {
  10070. code: ZodError_1.ZodIssueCode.invalid_type,
  10071. expected: util_1.ZodParsedType.string,
  10072. received: ctx.parsedType,
  10073. }
  10074. //
  10075. );
  10076. return parseUtil_1.INVALID;
  10077. }
  10078. const status = new parseUtil_1.ParseStatus();
  10079. let ctx = undefined;
  10080. for (const check of this._def.checks) {
  10081. if (check.kind === "min") {
  10082. if (input.data.length < check.value) {
  10083. ctx = this._getOrReturnCtx(input, ctx);
  10084. (0, parseUtil_1.addIssueToContext)(ctx, {
  10085. code: ZodError_1.ZodIssueCode.too_small,
  10086. minimum: check.value,
  10087. type: "string",
  10088. inclusive: true,
  10089. exact: false,
  10090. message: check.message,
  10091. });
  10092. status.dirty();
  10093. }
  10094. }
  10095. else if (check.kind === "max") {
  10096. if (input.data.length > check.value) {
  10097. ctx = this._getOrReturnCtx(input, ctx);
  10098. (0, parseUtil_1.addIssueToContext)(ctx, {
  10099. code: ZodError_1.ZodIssueCode.too_big,
  10100. maximum: check.value,
  10101. type: "string",
  10102. inclusive: true,
  10103. exact: false,
  10104. message: check.message,
  10105. });
  10106. status.dirty();
  10107. }
  10108. }
  10109. else if (check.kind === "length") {
  10110. const tooBig = input.data.length > check.value;
  10111. const tooSmall = input.data.length < check.value;
  10112. if (tooBig || tooSmall) {
  10113. ctx = this._getOrReturnCtx(input, ctx);
  10114. if (tooBig) {
  10115. (0, parseUtil_1.addIssueToContext)(ctx, {
  10116. code: ZodError_1.ZodIssueCode.too_big,
  10117. maximum: check.value,
  10118. type: "string",
  10119. inclusive: true,
  10120. exact: true,
  10121. message: check.message,
  10122. });
  10123. }
  10124. else if (tooSmall) {
  10125. (0, parseUtil_1.addIssueToContext)(ctx, {
  10126. code: ZodError_1.ZodIssueCode.too_small,
  10127. minimum: check.value,
  10128. type: "string",
  10129. inclusive: true,
  10130. exact: true,
  10131. message: check.message,
  10132. });
  10133. }
  10134. status.dirty();
  10135. }
  10136. }
  10137. else if (check.kind === "email") {
  10138. if (!emailRegex.test(input.data)) {
  10139. ctx = this._getOrReturnCtx(input, ctx);
  10140. (0, parseUtil_1.addIssueToContext)(ctx, {
  10141. validation: "email",
  10142. code: ZodError_1.ZodIssueCode.invalid_string,
  10143. message: check.message,
  10144. });
  10145. status.dirty();
  10146. }
  10147. }
  10148. else if (check.kind === "emoji") {
  10149. if (!emojiRegex) {
  10150. emojiRegex = new RegExp(_emojiRegex, "u");
  10151. }
  10152. if (!emojiRegex.test(input.data)) {
  10153. ctx = this._getOrReturnCtx(input, ctx);
  10154. (0, parseUtil_1.addIssueToContext)(ctx, {
  10155. validation: "emoji",
  10156. code: ZodError_1.ZodIssueCode.invalid_string,
  10157. message: check.message,
  10158. });
  10159. status.dirty();
  10160. }
  10161. }
  10162. else if (check.kind === "uuid") {
  10163. if (!uuidRegex.test(input.data)) {
  10164. ctx = this._getOrReturnCtx(input, ctx);
  10165. (0, parseUtil_1.addIssueToContext)(ctx, {
  10166. validation: "uuid",
  10167. code: ZodError_1.ZodIssueCode.invalid_string,
  10168. message: check.message,
  10169. });
  10170. status.dirty();
  10171. }
  10172. }
  10173. else if (check.kind === "cuid") {
  10174. if (!cuidRegex.test(input.data)) {
  10175. ctx = this._getOrReturnCtx(input, ctx);
  10176. (0, parseUtil_1.addIssueToContext)(ctx, {
  10177. validation: "cuid",
  10178. code: ZodError_1.ZodIssueCode.invalid_string,
  10179. message: check.message,
  10180. });
  10181. status.dirty();
  10182. }
  10183. }
  10184. else if (check.kind === "cuid2") {
  10185. if (!cuid2Regex.test(input.data)) {
  10186. ctx = this._getOrReturnCtx(input, ctx);
  10187. (0, parseUtil_1.addIssueToContext)(ctx, {
  10188. validation: "cuid2",
  10189. code: ZodError_1.ZodIssueCode.invalid_string,
  10190. message: check.message,
  10191. });
  10192. status.dirty();
  10193. }
  10194. }
  10195. else if (check.kind === "ulid") {
  10196. if (!ulidRegex.test(input.data)) {
  10197. ctx = this._getOrReturnCtx(input, ctx);
  10198. (0, parseUtil_1.addIssueToContext)(ctx, {
  10199. validation: "ulid",
  10200. code: ZodError_1.ZodIssueCode.invalid_string,
  10201. message: check.message,
  10202. });
  10203. status.dirty();
  10204. }
  10205. }
  10206. else if (check.kind === "url") {
  10207. try {
  10208. new URL(input.data);
  10209. }
  10210. catch (_a) {
  10211. ctx = this._getOrReturnCtx(input, ctx);
  10212. (0, parseUtil_1.addIssueToContext)(ctx, {
  10213. validation: "url",
  10214. code: ZodError_1.ZodIssueCode.invalid_string,
  10215. message: check.message,
  10216. });
  10217. status.dirty();
  10218. }
  10219. }
  10220. else if (check.kind === "regex") {
  10221. check.regex.lastIndex = 0;
  10222. const testResult = check.regex.test(input.data);
  10223. if (!testResult) {
  10224. ctx = this._getOrReturnCtx(input, ctx);
  10225. (0, parseUtil_1.addIssueToContext)(ctx, {
  10226. validation: "regex",
  10227. code: ZodError_1.ZodIssueCode.invalid_string,
  10228. message: check.message,
  10229. });
  10230. status.dirty();
  10231. }
  10232. }
  10233. else if (check.kind === "trim") {
  10234. input.data = input.data.trim();
  10235. }
  10236. else if (check.kind === "includes") {
  10237. if (!input.data.includes(check.value, check.position)) {
  10238. ctx = this._getOrReturnCtx(input, ctx);
  10239. (0, parseUtil_1.addIssueToContext)(ctx, {
  10240. code: ZodError_1.ZodIssueCode.invalid_string,
  10241. validation: { includes: check.value, position: check.position },
  10242. message: check.message,
  10243. });
  10244. status.dirty();
  10245. }
  10246. }
  10247. else if (check.kind === "toLowerCase") {
  10248. input.data = input.data.toLowerCase();
  10249. }
  10250. else if (check.kind === "toUpperCase") {
  10251. input.data = input.data.toUpperCase();
  10252. }
  10253. else if (check.kind === "startsWith") {
  10254. if (!input.data.startsWith(check.value)) {
  10255. ctx = this._getOrReturnCtx(input, ctx);
  10256. (0, parseUtil_1.addIssueToContext)(ctx, {
  10257. code: ZodError_1.ZodIssueCode.invalid_string,
  10258. validation: { startsWith: check.value },
  10259. message: check.message,
  10260. });
  10261. status.dirty();
  10262. }
  10263. }
  10264. else if (check.kind === "endsWith") {
  10265. if (!input.data.endsWith(check.value)) {
  10266. ctx = this._getOrReturnCtx(input, ctx);
  10267. (0, parseUtil_1.addIssueToContext)(ctx, {
  10268. code: ZodError_1.ZodIssueCode.invalid_string,
  10269. validation: { endsWith: check.value },
  10270. message: check.message,
  10271. });
  10272. status.dirty();
  10273. }
  10274. }
  10275. else if (check.kind === "datetime") {
  10276. const regex = datetimeRegex(check);
  10277. if (!regex.test(input.data)) {
  10278. ctx = this._getOrReturnCtx(input, ctx);
  10279. (0, parseUtil_1.addIssueToContext)(ctx, {
  10280. code: ZodError_1.ZodIssueCode.invalid_string,
  10281. validation: "datetime",
  10282. message: check.message,
  10283. });
  10284. status.dirty();
  10285. }
  10286. }
  10287. else if (check.kind === "ip") {
  10288. if (!isValidIP(input.data, check.version)) {
  10289. ctx = this._getOrReturnCtx(input, ctx);
  10290. (0, parseUtil_1.addIssueToContext)(ctx, {
  10291. validation: "ip",
  10292. code: ZodError_1.ZodIssueCode.invalid_string,
  10293. message: check.message,
  10294. });
  10295. status.dirty();
  10296. }
  10297. }
  10298. else {
  10299. util_1.util.assertNever(check);
  10300. }
  10301. }
  10302. return { status: status.value, value: input.data };
  10303. }
  10304. _regex(regex, validation, message) {
  10305. return this.refinement((data) => regex.test(data), {
  10306. validation,
  10307. code: ZodError_1.ZodIssueCode.invalid_string,
  10308. ...errorUtil_1.errorUtil.errToObj(message),
  10309. });
  10310. }
  10311. _addCheck(check) {
  10312. return new ZodString({
  10313. ...this._def,
  10314. checks: [...this._def.checks, check],
  10315. });
  10316. }
  10317. email(message) {
  10318. return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) });
  10319. }
  10320. url(message) {
  10321. return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) });
  10322. }
  10323. emoji(message) {
  10324. return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) });
  10325. }
  10326. uuid(message) {
  10327. return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) });
  10328. }
  10329. cuid(message) {
  10330. return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) });
  10331. }
  10332. cuid2(message) {
  10333. return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) });
  10334. }
  10335. ulid(message) {
  10336. return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) });
  10337. }
  10338. ip(options) {
  10339. return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) });
  10340. }
  10341. datetime(options) {
  10342. var _a;
  10343. if (typeof options === "string") {
  10344. return this._addCheck({
  10345. kind: "datetime",
  10346. precision: null,
  10347. offset: false,
  10348. message: options,
  10349. });
  10350. }
  10351. return this._addCheck({
  10352. kind: "datetime",
  10353. precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
  10354. offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
  10355. ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
  10356. });
  10357. }
  10358. regex(regex, message) {
  10359. return this._addCheck({
  10360. kind: "regex",
  10361. regex: regex,
  10362. ...errorUtil_1.errorUtil.errToObj(message),
  10363. });
  10364. }
  10365. includes(value, options) {
  10366. return this._addCheck({
  10367. kind: "includes",
  10368. value: value,
  10369. position: options === null || options === void 0 ? void 0 : options.position,
  10370. ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
  10371. });
  10372. }
  10373. startsWith(value, message) {
  10374. return this._addCheck({
  10375. kind: "startsWith",
  10376. value: value,
  10377. ...errorUtil_1.errorUtil.errToObj(message),
  10378. });
  10379. }
  10380. endsWith(value, message) {
  10381. return this._addCheck({
  10382. kind: "endsWith",
  10383. value: value,
  10384. ...errorUtil_1.errorUtil.errToObj(message),
  10385. });
  10386. }
  10387. min(minLength, message) {
  10388. return this._addCheck({
  10389. kind: "min",
  10390. value: minLength,
  10391. ...errorUtil_1.errorUtil.errToObj(message),
  10392. });
  10393. }
  10394. max(maxLength, message) {
  10395. return this._addCheck({
  10396. kind: "max",
  10397. value: maxLength,
  10398. ...errorUtil_1.errorUtil.errToObj(message),
  10399. });
  10400. }
  10401. length(len, message) {
  10402. return this._addCheck({
  10403. kind: "length",
  10404. value: len,
  10405. ...errorUtil_1.errorUtil.errToObj(message),
  10406. });
  10407. }
  10408. /**
  10409. * @deprecated Use z.string().min(1) instead.
  10410. * @see {@link ZodString.min}
  10411. */
  10412. nonempty(message) {
  10413. return this.min(1, errorUtil_1.errorUtil.errToObj(message));
  10414. }
  10415. trim() {
  10416. return new ZodString({
  10417. ...this._def,
  10418. checks: [...this._def.checks, { kind: "trim" }],
  10419. });
  10420. }
  10421. toLowerCase() {
  10422. return new ZodString({
  10423. ...this._def,
  10424. checks: [...this._def.checks, { kind: "toLowerCase" }],
  10425. });
  10426. }
  10427. toUpperCase() {
  10428. return new ZodString({
  10429. ...this._def,
  10430. checks: [...this._def.checks, { kind: "toUpperCase" }],
  10431. });
  10432. }
  10433. get isDatetime() {
  10434. return !!this._def.checks.find((ch) => ch.kind === "datetime");
  10435. }
  10436. get isEmail() {
  10437. return !!this._def.checks.find((ch) => ch.kind === "email");
  10438. }
  10439. get isURL() {
  10440. return !!this._def.checks.find((ch) => ch.kind === "url");
  10441. }
  10442. get isEmoji() {
  10443. return !!this._def.checks.find((ch) => ch.kind === "emoji");
  10444. }
  10445. get isUUID() {
  10446. return !!this._def.checks.find((ch) => ch.kind === "uuid");
  10447. }
  10448. get isCUID() {
  10449. return !!this._def.checks.find((ch) => ch.kind === "cuid");
  10450. }
  10451. get isCUID2() {
  10452. return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  10453. }
  10454. get isULID() {
  10455. return !!this._def.checks.find((ch) => ch.kind === "ulid");
  10456. }
  10457. get isIP() {
  10458. return !!this._def.checks.find((ch) => ch.kind === "ip");
  10459. }
  10460. get minLength() {
  10461. let min = null;
  10462. for (const ch of this._def.checks) {
  10463. if (ch.kind === "min") {
  10464. if (min === null || ch.value > min)
  10465. min = ch.value;
  10466. }
  10467. }
  10468. return min;
  10469. }
  10470. get maxLength() {
  10471. let max = null;
  10472. for (const ch of this._def.checks) {
  10473. if (ch.kind === "max") {
  10474. if (max === null || ch.value < max)
  10475. max = ch.value;
  10476. }
  10477. }
  10478. return max;
  10479. }
  10480. }
  10481. exports.ZodString = ZodString;
  10482. ZodString.create = (params) => {
  10483. var _a;
  10484. return new ZodString({
  10485. checks: [],
  10486. typeName: ZodFirstPartyTypeKind.ZodString,
  10487. coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
  10488. ...processCreateParams(params),
  10489. });
  10490. };
  10491. // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
  10492. function floatSafeRemainder(val, step) {
  10493. const valDecCount = (val.toString().split(".")[1] || "").length;
  10494. const stepDecCount = (step.toString().split(".")[1] || "").length;
  10495. const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  10496. const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  10497. const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  10498. return (valInt % stepInt) / Math.pow(10, decCount);
  10499. }
  10500. class ZodNumber extends ZodType {
  10501. constructor() {
  10502. super(...arguments);
  10503. this.min = this.gte;
  10504. this.max = this.lte;
  10505. this.step = this.multipleOf;
  10506. }
  10507. _parse(input) {
  10508. if (this._def.coerce) {
  10509. input.data = Number(input.data);
  10510. }
  10511. const parsedType = this._getType(input);
  10512. if (parsedType !== util_1.ZodParsedType.number) {
  10513. const ctx = this._getOrReturnCtx(input);
  10514. (0, parseUtil_1.addIssueToContext)(ctx, {
  10515. code: ZodError_1.ZodIssueCode.invalid_type,
  10516. expected: util_1.ZodParsedType.number,
  10517. received: ctx.parsedType,
  10518. });
  10519. return parseUtil_1.INVALID;
  10520. }
  10521. let ctx = undefined;
  10522. const status = new parseUtil_1.ParseStatus();
  10523. for (const check of this._def.checks) {
  10524. if (check.kind === "int") {
  10525. if (!util_1.util.isInteger(input.data)) {
  10526. ctx = this._getOrReturnCtx(input, ctx);
  10527. (0, parseUtil_1.addIssueToContext)(ctx, {
  10528. code: ZodError_1.ZodIssueCode.invalid_type,
  10529. expected: "integer",
  10530. received: "float",
  10531. message: check.message,
  10532. });
  10533. status.dirty();
  10534. }
  10535. }
  10536. else if (check.kind === "min") {
  10537. const tooSmall = check.inclusive
  10538. ? input.data < check.value
  10539. : input.data <= check.value;
  10540. if (tooSmall) {
  10541. ctx = this._getOrReturnCtx(input, ctx);
  10542. (0, parseUtil_1.addIssueToContext)(ctx, {
  10543. code: ZodError_1.ZodIssueCode.too_small,
  10544. minimum: check.value,
  10545. type: "number",
  10546. inclusive: check.inclusive,
  10547. exact: false,
  10548. message: check.message,
  10549. });
  10550. status.dirty();
  10551. }
  10552. }
  10553. else if (check.kind === "max") {
  10554. const tooBig = check.inclusive
  10555. ? input.data > check.value
  10556. : input.data >= check.value;
  10557. if (tooBig) {
  10558. ctx = this._getOrReturnCtx(input, ctx);
  10559. (0, parseUtil_1.addIssueToContext)(ctx, {
  10560. code: ZodError_1.ZodIssueCode.too_big,
  10561. maximum: check.value,
  10562. type: "number",
  10563. inclusive: check.inclusive,
  10564. exact: false,
  10565. message: check.message,
  10566. });
  10567. status.dirty();
  10568. }
  10569. }
  10570. else if (check.kind === "multipleOf") {
  10571. if (floatSafeRemainder(input.data, check.value) !== 0) {
  10572. ctx = this._getOrReturnCtx(input, ctx);
  10573. (0, parseUtil_1.addIssueToContext)(ctx, {
  10574. code: ZodError_1.ZodIssueCode.not_multiple_of,
  10575. multipleOf: check.value,
  10576. message: check.message,
  10577. });
  10578. status.dirty();
  10579. }
  10580. }
  10581. else if (check.kind === "finite") {
  10582. if (!Number.isFinite(input.data)) {
  10583. ctx = this._getOrReturnCtx(input, ctx);
  10584. (0, parseUtil_1.addIssueToContext)(ctx, {
  10585. code: ZodError_1.ZodIssueCode.not_finite,
  10586. message: check.message,
  10587. });
  10588. status.dirty();
  10589. }
  10590. }
  10591. else {
  10592. util_1.util.assertNever(check);
  10593. }
  10594. }
  10595. return { status: status.value, value: input.data };
  10596. }
  10597. gte(value, message) {
  10598. return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message));
  10599. }
  10600. gt(value, message) {
  10601. return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message));
  10602. }
  10603. lte(value, message) {
  10604. return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message));
  10605. }
  10606. lt(value, message) {
  10607. return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message));
  10608. }
  10609. setLimit(kind, value, inclusive, message) {
  10610. return new ZodNumber({
  10611. ...this._def,
  10612. checks: [
  10613. ...this._def.checks,
  10614. {
  10615. kind,
  10616. value,
  10617. inclusive,
  10618. message: errorUtil_1.errorUtil.toString(message),
  10619. },
  10620. ],
  10621. });
  10622. }
  10623. _addCheck(check) {
  10624. return new ZodNumber({
  10625. ...this._def,
  10626. checks: [...this._def.checks, check],
  10627. });
  10628. }
  10629. int(message) {
  10630. return this._addCheck({
  10631. kind: "int",
  10632. message: errorUtil_1.errorUtil.toString(message),
  10633. });
  10634. }
  10635. positive(message) {
  10636. return this._addCheck({
  10637. kind: "min",
  10638. value: 0,
  10639. inclusive: false,
  10640. message: errorUtil_1.errorUtil.toString(message),
  10641. });
  10642. }
  10643. negative(message) {
  10644. return this._addCheck({
  10645. kind: "max",
  10646. value: 0,
  10647. inclusive: false,
  10648. message: errorUtil_1.errorUtil.toString(message),
  10649. });
  10650. }
  10651. nonpositive(message) {
  10652. return this._addCheck({
  10653. kind: "max",
  10654. value: 0,
  10655. inclusive: true,
  10656. message: errorUtil_1.errorUtil.toString(message),
  10657. });
  10658. }
  10659. nonnegative(message) {
  10660. return this._addCheck({
  10661. kind: "min",
  10662. value: 0,
  10663. inclusive: true,
  10664. message: errorUtil_1.errorUtil.toString(message),
  10665. });
  10666. }
  10667. multipleOf(value, message) {
  10668. return this._addCheck({
  10669. kind: "multipleOf",
  10670. value: value,
  10671. message: errorUtil_1.errorUtil.toString(message),
  10672. });
  10673. }
  10674. finite(message) {
  10675. return this._addCheck({
  10676. kind: "finite",
  10677. message: errorUtil_1.errorUtil.toString(message),
  10678. });
  10679. }
  10680. safe(message) {
  10681. return this._addCheck({
  10682. kind: "min",
  10683. inclusive: true,
  10684. value: Number.MIN_SAFE_INTEGER,
  10685. message: errorUtil_1.errorUtil.toString(message),
  10686. })._addCheck({
  10687. kind: "max",
  10688. inclusive: true,
  10689. value: Number.MAX_SAFE_INTEGER,
  10690. message: errorUtil_1.errorUtil.toString(message),
  10691. });
  10692. }
  10693. get minValue() {
  10694. let min = null;
  10695. for (const ch of this._def.checks) {
  10696. if (ch.kind === "min") {
  10697. if (min === null || ch.value > min)
  10698. min = ch.value;
  10699. }
  10700. }
  10701. return min;
  10702. }
  10703. get maxValue() {
  10704. let max = null;
  10705. for (const ch of this._def.checks) {
  10706. if (ch.kind === "max") {
  10707. if (max === null || ch.value < max)
  10708. max = ch.value;
  10709. }
  10710. }
  10711. return max;
  10712. }
  10713. get isInt() {
  10714. return !!this._def.checks.find((ch) => ch.kind === "int" ||
  10715. (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value)));
  10716. }
  10717. get isFinite() {
  10718. let max = null, min = null;
  10719. for (const ch of this._def.checks) {
  10720. if (ch.kind === "finite" ||
  10721. ch.kind === "int" ||
  10722. ch.kind === "multipleOf") {
  10723. return true;
  10724. }
  10725. else if (ch.kind === "min") {
  10726. if (min === null || ch.value > min)
  10727. min = ch.value;
  10728. }
  10729. else if (ch.kind === "max") {
  10730. if (max === null || ch.value < max)
  10731. max = ch.value;
  10732. }
  10733. }
  10734. return Number.isFinite(min) && Number.isFinite(max);
  10735. }
  10736. }
  10737. exports.ZodNumber = ZodNumber;
  10738. ZodNumber.create = (params) => {
  10739. return new ZodNumber({
  10740. checks: [],
  10741. typeName: ZodFirstPartyTypeKind.ZodNumber,
  10742. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  10743. ...processCreateParams(params),
  10744. });
  10745. };
  10746. class ZodBigInt extends ZodType {
  10747. constructor() {
  10748. super(...arguments);
  10749. this.min = this.gte;
  10750. this.max = this.lte;
  10751. }
  10752. _parse(input) {
  10753. if (this._def.coerce) {
  10754. input.data = BigInt(input.data);
  10755. }
  10756. const parsedType = this._getType(input);
  10757. if (parsedType !== util_1.ZodParsedType.bigint) {
  10758. const ctx = this._getOrReturnCtx(input);
  10759. (0, parseUtil_1.addIssueToContext)(ctx, {
  10760. code: ZodError_1.ZodIssueCode.invalid_type,
  10761. expected: util_1.ZodParsedType.bigint,
  10762. received: ctx.parsedType,
  10763. });
  10764. return parseUtil_1.INVALID;
  10765. }
  10766. let ctx = undefined;
  10767. const status = new parseUtil_1.ParseStatus();
  10768. for (const check of this._def.checks) {
  10769. if (check.kind === "min") {
  10770. const tooSmall = check.inclusive
  10771. ? input.data < check.value
  10772. : input.data <= check.value;
  10773. if (tooSmall) {
  10774. ctx = this._getOrReturnCtx(input, ctx);
  10775. (0, parseUtil_1.addIssueToContext)(ctx, {
  10776. code: ZodError_1.ZodIssueCode.too_small,
  10777. type: "bigint",
  10778. minimum: check.value,
  10779. inclusive: check.inclusive,
  10780. message: check.message,
  10781. });
  10782. status.dirty();
  10783. }
  10784. }
  10785. else if (check.kind === "max") {
  10786. const tooBig = check.inclusive
  10787. ? input.data > check.value
  10788. : input.data >= check.value;
  10789. if (tooBig) {
  10790. ctx = this._getOrReturnCtx(input, ctx);
  10791. (0, parseUtil_1.addIssueToContext)(ctx, {
  10792. code: ZodError_1.ZodIssueCode.too_big,
  10793. type: "bigint",
  10794. maximum: check.value,
  10795. inclusive: check.inclusive,
  10796. message: check.message,
  10797. });
  10798. status.dirty();
  10799. }
  10800. }
  10801. else if (check.kind === "multipleOf") {
  10802. if (input.data % check.value !== BigInt(0)) {
  10803. ctx = this._getOrReturnCtx(input, ctx);
  10804. (0, parseUtil_1.addIssueToContext)(ctx, {
  10805. code: ZodError_1.ZodIssueCode.not_multiple_of,
  10806. multipleOf: check.value,
  10807. message: check.message,
  10808. });
  10809. status.dirty();
  10810. }
  10811. }
  10812. else {
  10813. util_1.util.assertNever(check);
  10814. }
  10815. }
  10816. return { status: status.value, value: input.data };
  10817. }
  10818. gte(value, message) {
  10819. return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message));
  10820. }
  10821. gt(value, message) {
  10822. return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message));
  10823. }
  10824. lte(value, message) {
  10825. return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message));
  10826. }
  10827. lt(value, message) {
  10828. return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message));
  10829. }
  10830. setLimit(kind, value, inclusive, message) {
  10831. return new ZodBigInt({
  10832. ...this._def,
  10833. checks: [
  10834. ...this._def.checks,
  10835. {
  10836. kind,
  10837. value,
  10838. inclusive,
  10839. message: errorUtil_1.errorUtil.toString(message),
  10840. },
  10841. ],
  10842. });
  10843. }
  10844. _addCheck(check) {
  10845. return new ZodBigInt({
  10846. ...this._def,
  10847. checks: [...this._def.checks, check],
  10848. });
  10849. }
  10850. positive(message) {
  10851. return this._addCheck({
  10852. kind: "min",
  10853. value: BigInt(0),
  10854. inclusive: false,
  10855. message: errorUtil_1.errorUtil.toString(message),
  10856. });
  10857. }
  10858. negative(message) {
  10859. return this._addCheck({
  10860. kind: "max",
  10861. value: BigInt(0),
  10862. inclusive: false,
  10863. message: errorUtil_1.errorUtil.toString(message),
  10864. });
  10865. }
  10866. nonpositive(message) {
  10867. return this._addCheck({
  10868. kind: "max",
  10869. value: BigInt(0),
  10870. inclusive: true,
  10871. message: errorUtil_1.errorUtil.toString(message),
  10872. });
  10873. }
  10874. nonnegative(message) {
  10875. return this._addCheck({
  10876. kind: "min",
  10877. value: BigInt(0),
  10878. inclusive: true,
  10879. message: errorUtil_1.errorUtil.toString(message),
  10880. });
  10881. }
  10882. multipleOf(value, message) {
  10883. return this._addCheck({
  10884. kind: "multipleOf",
  10885. value,
  10886. message: errorUtil_1.errorUtil.toString(message),
  10887. });
  10888. }
  10889. get minValue() {
  10890. let min = null;
  10891. for (const ch of this._def.checks) {
  10892. if (ch.kind === "min") {
  10893. if (min === null || ch.value > min)
  10894. min = ch.value;
  10895. }
  10896. }
  10897. return min;
  10898. }
  10899. get maxValue() {
  10900. let max = null;
  10901. for (const ch of this._def.checks) {
  10902. if (ch.kind === "max") {
  10903. if (max === null || ch.value < max)
  10904. max = ch.value;
  10905. }
  10906. }
  10907. return max;
  10908. }
  10909. }
  10910. exports.ZodBigInt = ZodBigInt;
  10911. ZodBigInt.create = (params) => {
  10912. var _a;
  10913. return new ZodBigInt({
  10914. checks: [],
  10915. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  10916. coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
  10917. ...processCreateParams(params),
  10918. });
  10919. };
  10920. class ZodBoolean extends ZodType {
  10921. _parse(input) {
  10922. if (this._def.coerce) {
  10923. input.data = Boolean(input.data);
  10924. }
  10925. const parsedType = this._getType(input);
  10926. if (parsedType !== util_1.ZodParsedType.boolean) {
  10927. const ctx = this._getOrReturnCtx(input);
  10928. (0, parseUtil_1.addIssueToContext)(ctx, {
  10929. code: ZodError_1.ZodIssueCode.invalid_type,
  10930. expected: util_1.ZodParsedType.boolean,
  10931. received: ctx.parsedType,
  10932. });
  10933. return parseUtil_1.INVALID;
  10934. }
  10935. return (0, parseUtil_1.OK)(input.data);
  10936. }
  10937. }
  10938. exports.ZodBoolean = ZodBoolean;
  10939. ZodBoolean.create = (params) => {
  10940. return new ZodBoolean({
  10941. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  10942. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  10943. ...processCreateParams(params),
  10944. });
  10945. };
  10946. class ZodDate extends ZodType {
  10947. _parse(input) {
  10948. if (this._def.coerce) {
  10949. input.data = new Date(input.data);
  10950. }
  10951. const parsedType = this._getType(input);
  10952. if (parsedType !== util_1.ZodParsedType.date) {
  10953. const ctx = this._getOrReturnCtx(input);
  10954. (0, parseUtil_1.addIssueToContext)(ctx, {
  10955. code: ZodError_1.ZodIssueCode.invalid_type,
  10956. expected: util_1.ZodParsedType.date,
  10957. received: ctx.parsedType,
  10958. });
  10959. return parseUtil_1.INVALID;
  10960. }
  10961. if (isNaN(input.data.getTime())) {
  10962. const ctx = this._getOrReturnCtx(input);
  10963. (0, parseUtil_1.addIssueToContext)(ctx, {
  10964. code: ZodError_1.ZodIssueCode.invalid_date,
  10965. });
  10966. return parseUtil_1.INVALID;
  10967. }
  10968. const status = new parseUtil_1.ParseStatus();
  10969. let ctx = undefined;
  10970. for (const check of this._def.checks) {
  10971. if (check.kind === "min") {
  10972. if (input.data.getTime() < check.value) {
  10973. ctx = this._getOrReturnCtx(input, ctx);
  10974. (0, parseUtil_1.addIssueToContext)(ctx, {
  10975. code: ZodError_1.ZodIssueCode.too_small,
  10976. message: check.message,
  10977. inclusive: true,
  10978. exact: false,
  10979. minimum: check.value,
  10980. type: "date",
  10981. });
  10982. status.dirty();
  10983. }
  10984. }
  10985. else if (check.kind === "max") {
  10986. if (input.data.getTime() > check.value) {
  10987. ctx = this._getOrReturnCtx(input, ctx);
  10988. (0, parseUtil_1.addIssueToContext)(ctx, {
  10989. code: ZodError_1.ZodIssueCode.too_big,
  10990. message: check.message,
  10991. inclusive: true,
  10992. exact: false,
  10993. maximum: check.value,
  10994. type: "date",
  10995. });
  10996. status.dirty();
  10997. }
  10998. }
  10999. else {
  11000. util_1.util.assertNever(check);
  11001. }
  11002. }
  11003. return {
  11004. status: status.value,
  11005. value: new Date(input.data.getTime()),
  11006. };
  11007. }
  11008. _addCheck(check) {
  11009. return new ZodDate({
  11010. ...this._def,
  11011. checks: [...this._def.checks, check],
  11012. });
  11013. }
  11014. min(minDate, message) {
  11015. return this._addCheck({
  11016. kind: "min",
  11017. value: minDate.getTime(),
  11018. message: errorUtil_1.errorUtil.toString(message),
  11019. });
  11020. }
  11021. max(maxDate, message) {
  11022. return this._addCheck({
  11023. kind: "max",
  11024. value: maxDate.getTime(),
  11025. message: errorUtil_1.errorUtil.toString(message),
  11026. });
  11027. }
  11028. get minDate() {
  11029. let min = null;
  11030. for (const ch of this._def.checks) {
  11031. if (ch.kind === "min") {
  11032. if (min === null || ch.value > min)
  11033. min = ch.value;
  11034. }
  11035. }
  11036. return min != null ? new Date(min) : null;
  11037. }
  11038. get maxDate() {
  11039. let max = null;
  11040. for (const ch of this._def.checks) {
  11041. if (ch.kind === "max") {
  11042. if (max === null || ch.value < max)
  11043. max = ch.value;
  11044. }
  11045. }
  11046. return max != null ? new Date(max) : null;
  11047. }
  11048. }
  11049. exports.ZodDate = ZodDate;
  11050. ZodDate.create = (params) => {
  11051. return new ZodDate({
  11052. checks: [],
  11053. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  11054. typeName: ZodFirstPartyTypeKind.ZodDate,
  11055. ...processCreateParams(params),
  11056. });
  11057. };
  11058. class ZodSymbol extends ZodType {
  11059. _parse(input) {
  11060. const parsedType = this._getType(input);
  11061. if (parsedType !== util_1.ZodParsedType.symbol) {
  11062. const ctx = this._getOrReturnCtx(input);
  11063. (0, parseUtil_1.addIssueToContext)(ctx, {
  11064. code: ZodError_1.ZodIssueCode.invalid_type,
  11065. expected: util_1.ZodParsedType.symbol,
  11066. received: ctx.parsedType,
  11067. });
  11068. return parseUtil_1.INVALID;
  11069. }
  11070. return (0, parseUtil_1.OK)(input.data);
  11071. }
  11072. }
  11073. exports.ZodSymbol = ZodSymbol;
  11074. ZodSymbol.create = (params) => {
  11075. return new ZodSymbol({
  11076. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  11077. ...processCreateParams(params),
  11078. });
  11079. };
  11080. class ZodUndefined extends ZodType {
  11081. _parse(input) {
  11082. const parsedType = this._getType(input);
  11083. if (parsedType !== util_1.ZodParsedType.undefined) {
  11084. const ctx = this._getOrReturnCtx(input);
  11085. (0, parseUtil_1.addIssueToContext)(ctx, {
  11086. code: ZodError_1.ZodIssueCode.invalid_type,
  11087. expected: util_1.ZodParsedType.undefined,
  11088. received: ctx.parsedType,
  11089. });
  11090. return parseUtil_1.INVALID;
  11091. }
  11092. return (0, parseUtil_1.OK)(input.data);
  11093. }
  11094. }
  11095. exports.ZodUndefined = ZodUndefined;
  11096. ZodUndefined.create = (params) => {
  11097. return new ZodUndefined({
  11098. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  11099. ...processCreateParams(params),
  11100. });
  11101. };
  11102. class ZodNull extends ZodType {
  11103. _parse(input) {
  11104. const parsedType = this._getType(input);
  11105. if (parsedType !== util_1.ZodParsedType.null) {
  11106. const ctx = this._getOrReturnCtx(input);
  11107. (0, parseUtil_1.addIssueToContext)(ctx, {
  11108. code: ZodError_1.ZodIssueCode.invalid_type,
  11109. expected: util_1.ZodParsedType.null,
  11110. received: ctx.parsedType,
  11111. });
  11112. return parseUtil_1.INVALID;
  11113. }
  11114. return (0, parseUtil_1.OK)(input.data);
  11115. }
  11116. }
  11117. exports.ZodNull = ZodNull;
  11118. ZodNull.create = (params) => {
  11119. return new ZodNull({
  11120. typeName: ZodFirstPartyTypeKind.ZodNull,
  11121. ...processCreateParams(params),
  11122. });
  11123. };
  11124. class ZodAny extends ZodType {
  11125. constructor() {
  11126. super(...arguments);
  11127. // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
  11128. this._any = true;
  11129. }
  11130. _parse(input) {
  11131. return (0, parseUtil_1.OK)(input.data);
  11132. }
  11133. }
  11134. exports.ZodAny = ZodAny;
  11135. ZodAny.create = (params) => {
  11136. return new ZodAny({
  11137. typeName: ZodFirstPartyTypeKind.ZodAny,
  11138. ...processCreateParams(params),
  11139. });
  11140. };
  11141. class ZodUnknown extends ZodType {
  11142. constructor() {
  11143. super(...arguments);
  11144. // required
  11145. this._unknown = true;
  11146. }
  11147. _parse(input) {
  11148. return (0, parseUtil_1.OK)(input.data);
  11149. }
  11150. }
  11151. exports.ZodUnknown = ZodUnknown;
  11152. ZodUnknown.create = (params) => {
  11153. return new ZodUnknown({
  11154. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  11155. ...processCreateParams(params),
  11156. });
  11157. };
  11158. class ZodNever extends ZodType {
  11159. _parse(input) {
  11160. const ctx = this._getOrReturnCtx(input);
  11161. (0, parseUtil_1.addIssueToContext)(ctx, {
  11162. code: ZodError_1.ZodIssueCode.invalid_type,
  11163. expected: util_1.ZodParsedType.never,
  11164. received: ctx.parsedType,
  11165. });
  11166. return parseUtil_1.INVALID;
  11167. }
  11168. }
  11169. exports.ZodNever = ZodNever;
  11170. ZodNever.create = (params) => {
  11171. return new ZodNever({
  11172. typeName: ZodFirstPartyTypeKind.ZodNever,
  11173. ...processCreateParams(params),
  11174. });
  11175. };
  11176. class ZodVoid extends ZodType {
  11177. _parse(input) {
  11178. const parsedType = this._getType(input);
  11179. if (parsedType !== util_1.ZodParsedType.undefined) {
  11180. const ctx = this._getOrReturnCtx(input);
  11181. (0, parseUtil_1.addIssueToContext)(ctx, {
  11182. code: ZodError_1.ZodIssueCode.invalid_type,
  11183. expected: util_1.ZodParsedType.void,
  11184. received: ctx.parsedType,
  11185. });
  11186. return parseUtil_1.INVALID;
  11187. }
  11188. return (0, parseUtil_1.OK)(input.data);
  11189. }
  11190. }
  11191. exports.ZodVoid = ZodVoid;
  11192. ZodVoid.create = (params) => {
  11193. return new ZodVoid({
  11194. typeName: ZodFirstPartyTypeKind.ZodVoid,
  11195. ...processCreateParams(params),
  11196. });
  11197. };
  11198. class ZodArray extends ZodType {
  11199. _parse(input) {
  11200. const { ctx, status } = this._processInputParams(input);
  11201. const def = this._def;
  11202. if (ctx.parsedType !== util_1.ZodParsedType.array) {
  11203. (0, parseUtil_1.addIssueToContext)(ctx, {
  11204. code: ZodError_1.ZodIssueCode.invalid_type,
  11205. expected: util_1.ZodParsedType.array,
  11206. received: ctx.parsedType,
  11207. });
  11208. return parseUtil_1.INVALID;
  11209. }
  11210. if (def.exactLength !== null) {
  11211. const tooBig = ctx.data.length > def.exactLength.value;
  11212. const tooSmall = ctx.data.length < def.exactLength.value;
  11213. if (tooBig || tooSmall) {
  11214. (0, parseUtil_1.addIssueToContext)(ctx, {
  11215. code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small,
  11216. minimum: (tooSmall ? def.exactLength.value : undefined),
  11217. maximum: (tooBig ? def.exactLength.value : undefined),
  11218. type: "array",
  11219. inclusive: true,
  11220. exact: true,
  11221. message: def.exactLength.message,
  11222. });
  11223. status.dirty();
  11224. }
  11225. }
  11226. if (def.minLength !== null) {
  11227. if (ctx.data.length < def.minLength.value) {
  11228. (0, parseUtil_1.addIssueToContext)(ctx, {
  11229. code: ZodError_1.ZodIssueCode.too_small,
  11230. minimum: def.minLength.value,
  11231. type: "array",
  11232. inclusive: true,
  11233. exact: false,
  11234. message: def.minLength.message,
  11235. });
  11236. status.dirty();
  11237. }
  11238. }
  11239. if (def.maxLength !== null) {
  11240. if (ctx.data.length > def.maxLength.value) {
  11241. (0, parseUtil_1.addIssueToContext)(ctx, {
  11242. code: ZodError_1.ZodIssueCode.too_big,
  11243. maximum: def.maxLength.value,
  11244. type: "array",
  11245. inclusive: true,
  11246. exact: false,
  11247. message: def.maxLength.message,
  11248. });
  11249. status.dirty();
  11250. }
  11251. }
  11252. if (ctx.common.async) {
  11253. return Promise.all([...ctx.data].map((item, i) => {
  11254. return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  11255. })).then((result) => {
  11256. return parseUtil_1.ParseStatus.mergeArray(status, result);
  11257. });
  11258. }
  11259. const result = [...ctx.data].map((item, i) => {
  11260. return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  11261. });
  11262. return parseUtil_1.ParseStatus.mergeArray(status, result);
  11263. }
  11264. get element() {
  11265. return this._def.type;
  11266. }
  11267. min(minLength, message) {
  11268. return new ZodArray({
  11269. ...this._def,
  11270. minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) },
  11271. });
  11272. }
  11273. max(maxLength, message) {
  11274. return new ZodArray({
  11275. ...this._def,
  11276. maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) },
  11277. });
  11278. }
  11279. length(len, message) {
  11280. return new ZodArray({
  11281. ...this._def,
  11282. exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) },
  11283. });
  11284. }
  11285. nonempty(message) {
  11286. return this.min(1, message);
  11287. }
  11288. }
  11289. exports.ZodArray = ZodArray;
  11290. ZodArray.create = (schema, params) => {
  11291. return new ZodArray({
  11292. type: schema,
  11293. minLength: null,
  11294. maxLength: null,
  11295. exactLength: null,
  11296. typeName: ZodFirstPartyTypeKind.ZodArray,
  11297. ...processCreateParams(params),
  11298. });
  11299. };
  11300. function deepPartialify(schema) {
  11301. if (schema instanceof ZodObject) {
  11302. const newShape = {};
  11303. for (const key in schema.shape) {
  11304. const fieldSchema = schema.shape[key];
  11305. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
  11306. }
  11307. return new ZodObject({
  11308. ...schema._def,
  11309. shape: () => newShape,
  11310. });
  11311. }
  11312. else if (schema instanceof ZodArray) {
  11313. return new ZodArray({
  11314. ...schema._def,
  11315. type: deepPartialify(schema.element),
  11316. });
  11317. }
  11318. else if (schema instanceof ZodOptional) {
  11319. return ZodOptional.create(deepPartialify(schema.unwrap()));
  11320. }
  11321. else if (schema instanceof ZodNullable) {
  11322. return ZodNullable.create(deepPartialify(schema.unwrap()));
  11323. }
  11324. else if (schema instanceof ZodTuple) {
  11325. return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  11326. }
  11327. else {
  11328. return schema;
  11329. }
  11330. }
  11331. class ZodObject extends ZodType {
  11332. constructor() {
  11333. super(...arguments);
  11334. this._cached = null;
  11335. /**
  11336. * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
  11337. * If you want to pass through unknown properties, use `.passthrough()` instead.
  11338. */
  11339. this.nonstrict = this.passthrough;
  11340. // extend<
  11341. // Augmentation extends ZodRawShape,
  11342. // NewOutput extends util.flatten<{
  11343. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  11344. // ? Augmentation[k]["_output"]
  11345. // : k extends keyof Output
  11346. // ? Output[k]
  11347. // : never;
  11348. // }>,
  11349. // NewInput extends util.flatten<{
  11350. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  11351. // ? Augmentation[k]["_input"]
  11352. // : k extends keyof Input
  11353. // ? Input[k]
  11354. // : never;
  11355. // }>
  11356. // >(
  11357. // augmentation: Augmentation
  11358. // ): ZodObject<
  11359. // extendShape<T, Augmentation>,
  11360. // UnknownKeys,
  11361. // Catchall,
  11362. // NewOutput,
  11363. // NewInput
  11364. // > {
  11365. // return new ZodObject({
  11366. // ...this._def,
  11367. // shape: () => ({
  11368. // ...this._def.shape(),
  11369. // ...augmentation,
  11370. // }),
  11371. // }) as any;
  11372. // }
  11373. /**
  11374. * @deprecated Use `.extend` instead
  11375. * */
  11376. this.augment = this.extend;
  11377. }
  11378. _getCached() {
  11379. if (this._cached !== null)
  11380. return this._cached;
  11381. const shape = this._def.shape();
  11382. const keys = util_1.util.objectKeys(shape);
  11383. return (this._cached = { shape, keys });
  11384. }
  11385. _parse(input) {
  11386. const parsedType = this._getType(input);
  11387. if (parsedType !== util_1.ZodParsedType.object) {
  11388. const ctx = this._getOrReturnCtx(input);
  11389. (0, parseUtil_1.addIssueToContext)(ctx, {
  11390. code: ZodError_1.ZodIssueCode.invalid_type,
  11391. expected: util_1.ZodParsedType.object,
  11392. received: ctx.parsedType,
  11393. });
  11394. return parseUtil_1.INVALID;
  11395. }
  11396. const { status, ctx } = this._processInputParams(input);
  11397. const { shape, keys: shapeKeys } = this._getCached();
  11398. const extraKeys = [];
  11399. if (!(this._def.catchall instanceof ZodNever &&
  11400. this._def.unknownKeys === "strip")) {
  11401. for (const key in ctx.data) {
  11402. if (!shapeKeys.includes(key)) {
  11403. extraKeys.push(key);
  11404. }
  11405. }
  11406. }
  11407. const pairs = [];
  11408. for (const key of shapeKeys) {
  11409. const keyValidator = shape[key];
  11410. const value = ctx.data[key];
  11411. pairs.push({
  11412. key: { status: "valid", value: key },
  11413. value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
  11414. alwaysSet: key in ctx.data,
  11415. });
  11416. }
  11417. if (this._def.catchall instanceof ZodNever) {
  11418. const unknownKeys = this._def.unknownKeys;
  11419. if (unknownKeys === "passthrough") {
  11420. for (const key of extraKeys) {
  11421. pairs.push({
  11422. key: { status: "valid", value: key },
  11423. value: { status: "valid", value: ctx.data[key] },
  11424. });
  11425. }
  11426. }
  11427. else if (unknownKeys === "strict") {
  11428. if (extraKeys.length > 0) {
  11429. (0, parseUtil_1.addIssueToContext)(ctx, {
  11430. code: ZodError_1.ZodIssueCode.unrecognized_keys,
  11431. keys: extraKeys,
  11432. });
  11433. status.dirty();
  11434. }
  11435. }
  11436. else if (unknownKeys === "strip") ;
  11437. else {
  11438. throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
  11439. }
  11440. }
  11441. else {
  11442. // run catchall validation
  11443. const catchall = this._def.catchall;
  11444. for (const key of extraKeys) {
  11445. const value = ctx.data[key];
  11446. pairs.push({
  11447. key: { status: "valid", value: key },
  11448. value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
  11449. ),
  11450. alwaysSet: key in ctx.data,
  11451. });
  11452. }
  11453. }
  11454. if (ctx.common.async) {
  11455. return Promise.resolve()
  11456. .then(async () => {
  11457. const syncPairs = [];
  11458. for (const pair of pairs) {
  11459. const key = await pair.key;
  11460. syncPairs.push({
  11461. key,
  11462. value: await pair.value,
  11463. alwaysSet: pair.alwaysSet,
  11464. });
  11465. }
  11466. return syncPairs;
  11467. })
  11468. .then((syncPairs) => {
  11469. return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs);
  11470. });
  11471. }
  11472. else {
  11473. return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs);
  11474. }
  11475. }
  11476. get shape() {
  11477. return this._def.shape();
  11478. }
  11479. strict(message) {
  11480. errorUtil_1.errorUtil.errToObj;
  11481. return new ZodObject({
  11482. ...this._def,
  11483. unknownKeys: "strict",
  11484. ...(message !== undefined
  11485. ? {
  11486. errorMap: (issue, ctx) => {
  11487. var _a, _b, _c, _d;
  11488. const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
  11489. if (issue.code === "unrecognized_keys")
  11490. return {
  11491. message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
  11492. };
  11493. return {
  11494. message: defaultError,
  11495. };
  11496. },
  11497. }
  11498. : {}),
  11499. });
  11500. }
  11501. strip() {
  11502. return new ZodObject({
  11503. ...this._def,
  11504. unknownKeys: "strip",
  11505. });
  11506. }
  11507. passthrough() {
  11508. return new ZodObject({
  11509. ...this._def,
  11510. unknownKeys: "passthrough",
  11511. });
  11512. }
  11513. // const AugmentFactory =
  11514. // <Def extends ZodObjectDef>(def: Def) =>
  11515. // <Augmentation extends ZodRawShape>(
  11516. // augmentation: Augmentation
  11517. // ): ZodObject<
  11518. // extendShape<ReturnType<Def["shape"]>, Augmentation>,
  11519. // Def["unknownKeys"],
  11520. // Def["catchall"]
  11521. // > => {
  11522. // return new ZodObject({
  11523. // ...def,
  11524. // shape: () => ({
  11525. // ...def.shape(),
  11526. // ...augmentation,
  11527. // }),
  11528. // }) as any;
  11529. // };
  11530. extend(augmentation) {
  11531. return new ZodObject({
  11532. ...this._def,
  11533. shape: () => ({
  11534. ...this._def.shape(),
  11535. ...augmentation,
  11536. }),
  11537. });
  11538. }
  11539. /**
  11540. * Prior to zod@1.0.12 there was a bug in the
  11541. * inferred type of merged objects. Please
  11542. * upgrade if you are experiencing issues.
  11543. */
  11544. merge(merging) {
  11545. const merged = new ZodObject({
  11546. unknownKeys: merging._def.unknownKeys,
  11547. catchall: merging._def.catchall,
  11548. shape: () => ({
  11549. ...this._def.shape(),
  11550. ...merging._def.shape(),
  11551. }),
  11552. typeName: ZodFirstPartyTypeKind.ZodObject,
  11553. });
  11554. return merged;
  11555. }
  11556. // merge<
  11557. // Incoming extends AnyZodObject,
  11558. // Augmentation extends Incoming["shape"],
  11559. // NewOutput extends {
  11560. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  11561. // ? Augmentation[k]["_output"]
  11562. // : k extends keyof Output
  11563. // ? Output[k]
  11564. // : never;
  11565. // },
  11566. // NewInput extends {
  11567. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  11568. // ? Augmentation[k]["_input"]
  11569. // : k extends keyof Input
  11570. // ? Input[k]
  11571. // : never;
  11572. // }
  11573. // >(
  11574. // merging: Incoming
  11575. // ): ZodObject<
  11576. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  11577. // Incoming["_def"]["unknownKeys"],
  11578. // Incoming["_def"]["catchall"],
  11579. // NewOutput,
  11580. // NewInput
  11581. // > {
  11582. // const merged: any = new ZodObject({
  11583. // unknownKeys: merging._def.unknownKeys,
  11584. // catchall: merging._def.catchall,
  11585. // shape: () =>
  11586. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  11587. // typeName: ZodFirstPartyTypeKind.ZodObject,
  11588. // }) as any;
  11589. // return merged;
  11590. // }
  11591. setKey(key, schema) {
  11592. return this.augment({ [key]: schema });
  11593. }
  11594. // merge<Incoming extends AnyZodObject>(
  11595. // merging: Incoming
  11596. // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  11597. // ZodObject<
  11598. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  11599. // Incoming["_def"]["unknownKeys"],
  11600. // Incoming["_def"]["catchall"]
  11601. // > {
  11602. // // const mergedShape = objectUtil.mergeShapes(
  11603. // // this._def.shape(),
  11604. // // merging._def.shape()
  11605. // // );
  11606. // const merged: any = new ZodObject({
  11607. // unknownKeys: merging._def.unknownKeys,
  11608. // catchall: merging._def.catchall,
  11609. // shape: () =>
  11610. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  11611. // typeName: ZodFirstPartyTypeKind.ZodObject,
  11612. // }) as any;
  11613. // return merged;
  11614. // }
  11615. catchall(index) {
  11616. return new ZodObject({
  11617. ...this._def,
  11618. catchall: index,
  11619. });
  11620. }
  11621. pick(mask) {
  11622. const shape = {};
  11623. util_1.util.objectKeys(mask).forEach((key) => {
  11624. if (mask[key] && this.shape[key]) {
  11625. shape[key] = this.shape[key];
  11626. }
  11627. });
  11628. return new ZodObject({
  11629. ...this._def,
  11630. shape: () => shape,
  11631. });
  11632. }
  11633. omit(mask) {
  11634. const shape = {};
  11635. util_1.util.objectKeys(this.shape).forEach((key) => {
  11636. if (!mask[key]) {
  11637. shape[key] = this.shape[key];
  11638. }
  11639. });
  11640. return new ZodObject({
  11641. ...this._def,
  11642. shape: () => shape,
  11643. });
  11644. }
  11645. /**
  11646. * @deprecated
  11647. */
  11648. deepPartial() {
  11649. return deepPartialify(this);
  11650. }
  11651. partial(mask) {
  11652. const newShape = {};
  11653. util_1.util.objectKeys(this.shape).forEach((key) => {
  11654. const fieldSchema = this.shape[key];
  11655. if (mask && !mask[key]) {
  11656. newShape[key] = fieldSchema;
  11657. }
  11658. else {
  11659. newShape[key] = fieldSchema.optional();
  11660. }
  11661. });
  11662. return new ZodObject({
  11663. ...this._def,
  11664. shape: () => newShape,
  11665. });
  11666. }
  11667. required(mask) {
  11668. const newShape = {};
  11669. util_1.util.objectKeys(this.shape).forEach((key) => {
  11670. if (mask && !mask[key]) {
  11671. newShape[key] = this.shape[key];
  11672. }
  11673. else {
  11674. const fieldSchema = this.shape[key];
  11675. let newField = fieldSchema;
  11676. while (newField instanceof ZodOptional) {
  11677. newField = newField._def.innerType;
  11678. }
  11679. newShape[key] = newField;
  11680. }
  11681. });
  11682. return new ZodObject({
  11683. ...this._def,
  11684. shape: () => newShape,
  11685. });
  11686. }
  11687. keyof() {
  11688. return createZodEnum(util_1.util.objectKeys(this.shape));
  11689. }
  11690. }
  11691. exports.ZodObject = ZodObject;
  11692. ZodObject.create = (shape, params) => {
  11693. return new ZodObject({
  11694. shape: () => shape,
  11695. unknownKeys: "strip",
  11696. catchall: ZodNever.create(),
  11697. typeName: ZodFirstPartyTypeKind.ZodObject,
  11698. ...processCreateParams(params),
  11699. });
  11700. };
  11701. ZodObject.strictCreate = (shape, params) => {
  11702. return new ZodObject({
  11703. shape: () => shape,
  11704. unknownKeys: "strict",
  11705. catchall: ZodNever.create(),
  11706. typeName: ZodFirstPartyTypeKind.ZodObject,
  11707. ...processCreateParams(params),
  11708. });
  11709. };
  11710. ZodObject.lazycreate = (shape, params) => {
  11711. return new ZodObject({
  11712. shape,
  11713. unknownKeys: "strip",
  11714. catchall: ZodNever.create(),
  11715. typeName: ZodFirstPartyTypeKind.ZodObject,
  11716. ...processCreateParams(params),
  11717. });
  11718. };
  11719. class ZodUnion extends ZodType {
  11720. _parse(input) {
  11721. const { ctx } = this._processInputParams(input);
  11722. const options = this._def.options;
  11723. function handleResults(results) {
  11724. // return first issue-free validation if it exists
  11725. for (const result of results) {
  11726. if (result.result.status === "valid") {
  11727. return result.result;
  11728. }
  11729. }
  11730. for (const result of results) {
  11731. if (result.result.status === "dirty") {
  11732. // add issues from dirty option
  11733. ctx.common.issues.push(...result.ctx.common.issues);
  11734. return result.result;
  11735. }
  11736. }
  11737. // return invalid
  11738. const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues));
  11739. (0, parseUtil_1.addIssueToContext)(ctx, {
  11740. code: ZodError_1.ZodIssueCode.invalid_union,
  11741. unionErrors,
  11742. });
  11743. return parseUtil_1.INVALID;
  11744. }
  11745. if (ctx.common.async) {
  11746. return Promise.all(options.map(async (option) => {
  11747. const childCtx = {
  11748. ...ctx,
  11749. common: {
  11750. ...ctx.common,
  11751. issues: [],
  11752. },
  11753. parent: null,
  11754. };
  11755. return {
  11756. result: await option._parseAsync({
  11757. data: ctx.data,
  11758. path: ctx.path,
  11759. parent: childCtx,
  11760. }),
  11761. ctx: childCtx,
  11762. };
  11763. })).then(handleResults);
  11764. }
  11765. else {
  11766. let dirty = undefined;
  11767. const issues = [];
  11768. for (const option of options) {
  11769. const childCtx = {
  11770. ...ctx,
  11771. common: {
  11772. ...ctx.common,
  11773. issues: [],
  11774. },
  11775. parent: null,
  11776. };
  11777. const result = option._parseSync({
  11778. data: ctx.data,
  11779. path: ctx.path,
  11780. parent: childCtx,
  11781. });
  11782. if (result.status === "valid") {
  11783. return result;
  11784. }
  11785. else if (result.status === "dirty" && !dirty) {
  11786. dirty = { result, ctx: childCtx };
  11787. }
  11788. if (childCtx.common.issues.length) {
  11789. issues.push(childCtx.common.issues);
  11790. }
  11791. }
  11792. if (dirty) {
  11793. ctx.common.issues.push(...dirty.ctx.common.issues);
  11794. return dirty.result;
  11795. }
  11796. const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues));
  11797. (0, parseUtil_1.addIssueToContext)(ctx, {
  11798. code: ZodError_1.ZodIssueCode.invalid_union,
  11799. unionErrors,
  11800. });
  11801. return parseUtil_1.INVALID;
  11802. }
  11803. }
  11804. get options() {
  11805. return this._def.options;
  11806. }
  11807. }
  11808. exports.ZodUnion = ZodUnion;
  11809. ZodUnion.create = (types, params) => {
  11810. return new ZodUnion({
  11811. options: types,
  11812. typeName: ZodFirstPartyTypeKind.ZodUnion,
  11813. ...processCreateParams(params),
  11814. });
  11815. };
  11816. /////////////////////////////////////////////////////
  11817. /////////////////////////////////////////////////////
  11818. ////////// //////////
  11819. ////////// ZodDiscriminatedUnion //////////
  11820. ////////// //////////
  11821. /////////////////////////////////////////////////////
  11822. /////////////////////////////////////////////////////
  11823. const getDiscriminator = (type) => {
  11824. if (type instanceof ZodLazy) {
  11825. return getDiscriminator(type.schema);
  11826. }
  11827. else if (type instanceof ZodEffects) {
  11828. return getDiscriminator(type.innerType());
  11829. }
  11830. else if (type instanceof ZodLiteral) {
  11831. return [type.value];
  11832. }
  11833. else if (type instanceof ZodEnum) {
  11834. return type.options;
  11835. }
  11836. else if (type instanceof ZodNativeEnum) {
  11837. // eslint-disable-next-line ban/ban
  11838. return Object.keys(type.enum);
  11839. }
  11840. else if (type instanceof ZodDefault) {
  11841. return getDiscriminator(type._def.innerType);
  11842. }
  11843. else if (type instanceof ZodUndefined) {
  11844. return [undefined];
  11845. }
  11846. else if (type instanceof ZodNull) {
  11847. return [null];
  11848. }
  11849. else {
  11850. return null;
  11851. }
  11852. };
  11853. class ZodDiscriminatedUnion extends ZodType {
  11854. _parse(input) {
  11855. const { ctx } = this._processInputParams(input);
  11856. if (ctx.parsedType !== util_1.ZodParsedType.object) {
  11857. (0, parseUtil_1.addIssueToContext)(ctx, {
  11858. code: ZodError_1.ZodIssueCode.invalid_type,
  11859. expected: util_1.ZodParsedType.object,
  11860. received: ctx.parsedType,
  11861. });
  11862. return parseUtil_1.INVALID;
  11863. }
  11864. const discriminator = this.discriminator;
  11865. const discriminatorValue = ctx.data[discriminator];
  11866. const option = this.optionsMap.get(discriminatorValue);
  11867. if (!option) {
  11868. (0, parseUtil_1.addIssueToContext)(ctx, {
  11869. code: ZodError_1.ZodIssueCode.invalid_union_discriminator,
  11870. options: Array.from(this.optionsMap.keys()),
  11871. path: [discriminator],
  11872. });
  11873. return parseUtil_1.INVALID;
  11874. }
  11875. if (ctx.common.async) {
  11876. return option._parseAsync({
  11877. data: ctx.data,
  11878. path: ctx.path,
  11879. parent: ctx,
  11880. });
  11881. }
  11882. else {
  11883. return option._parseSync({
  11884. data: ctx.data,
  11885. path: ctx.path,
  11886. parent: ctx,
  11887. });
  11888. }
  11889. }
  11890. get discriminator() {
  11891. return this._def.discriminator;
  11892. }
  11893. get options() {
  11894. return this._def.options;
  11895. }
  11896. get optionsMap() {
  11897. return this._def.optionsMap;
  11898. }
  11899. /**
  11900. * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
  11901. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
  11902. * have a different value for each object in the union.
  11903. * @param discriminator the name of the discriminator property
  11904. * @param types an array of object schemas
  11905. * @param params
  11906. */
  11907. static create(discriminator, options, params) {
  11908. // Get all the valid discriminator values
  11909. const optionsMap = new Map();
  11910. // try {
  11911. for (const type of options) {
  11912. const discriminatorValues = getDiscriminator(type.shape[discriminator]);
  11913. if (!discriminatorValues) {
  11914. throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
  11915. }
  11916. for (const value of discriminatorValues) {
  11917. if (optionsMap.has(value)) {
  11918. throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
  11919. }
  11920. optionsMap.set(value, type);
  11921. }
  11922. }
  11923. return new ZodDiscriminatedUnion({
  11924. typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  11925. discriminator,
  11926. options,
  11927. optionsMap,
  11928. ...processCreateParams(params),
  11929. });
  11930. }
  11931. }
  11932. exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion;
  11933. function mergeValues(a, b) {
  11934. const aType = (0, util_1.getParsedType)(a);
  11935. const bType = (0, util_1.getParsedType)(b);
  11936. if (a === b) {
  11937. return { valid: true, data: a };
  11938. }
  11939. else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) {
  11940. const bKeys = util_1.util.objectKeys(b);
  11941. const sharedKeys = util_1.util
  11942. .objectKeys(a)
  11943. .filter((key) => bKeys.indexOf(key) !== -1);
  11944. const newObj = { ...a, ...b };
  11945. for (const key of sharedKeys) {
  11946. const sharedValue = mergeValues(a[key], b[key]);
  11947. if (!sharedValue.valid) {
  11948. return { valid: false };
  11949. }
  11950. newObj[key] = sharedValue.data;
  11951. }
  11952. return { valid: true, data: newObj };
  11953. }
  11954. else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) {
  11955. if (a.length !== b.length) {
  11956. return { valid: false };
  11957. }
  11958. const newArray = [];
  11959. for (let index = 0; index < a.length; index++) {
  11960. const itemA = a[index];
  11961. const itemB = b[index];
  11962. const sharedValue = mergeValues(itemA, itemB);
  11963. if (!sharedValue.valid) {
  11964. return { valid: false };
  11965. }
  11966. newArray.push(sharedValue.data);
  11967. }
  11968. return { valid: true, data: newArray };
  11969. }
  11970. else if (aType === util_1.ZodParsedType.date &&
  11971. bType === util_1.ZodParsedType.date &&
  11972. +a === +b) {
  11973. return { valid: true, data: a };
  11974. }
  11975. else {
  11976. return { valid: false };
  11977. }
  11978. }
  11979. class ZodIntersection extends ZodType {
  11980. _parse(input) {
  11981. const { status, ctx } = this._processInputParams(input);
  11982. const handleParsed = (parsedLeft, parsedRight) => {
  11983. if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) {
  11984. return parseUtil_1.INVALID;
  11985. }
  11986. const merged = mergeValues(parsedLeft.value, parsedRight.value);
  11987. if (!merged.valid) {
  11988. (0, parseUtil_1.addIssueToContext)(ctx, {
  11989. code: ZodError_1.ZodIssueCode.invalid_intersection_types,
  11990. });
  11991. return parseUtil_1.INVALID;
  11992. }
  11993. if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) {
  11994. status.dirty();
  11995. }
  11996. return { status: status.value, value: merged.data };
  11997. };
  11998. if (ctx.common.async) {
  11999. return Promise.all([
  12000. this._def.left._parseAsync({
  12001. data: ctx.data,
  12002. path: ctx.path,
  12003. parent: ctx,
  12004. }),
  12005. this._def.right._parseAsync({
  12006. data: ctx.data,
  12007. path: ctx.path,
  12008. parent: ctx,
  12009. }),
  12010. ]).then(([left, right]) => handleParsed(left, right));
  12011. }
  12012. else {
  12013. return handleParsed(this._def.left._parseSync({
  12014. data: ctx.data,
  12015. path: ctx.path,
  12016. parent: ctx,
  12017. }), this._def.right._parseSync({
  12018. data: ctx.data,
  12019. path: ctx.path,
  12020. parent: ctx,
  12021. }));
  12022. }
  12023. }
  12024. }
  12025. exports.ZodIntersection = ZodIntersection;
  12026. ZodIntersection.create = (left, right, params) => {
  12027. return new ZodIntersection({
  12028. left: left,
  12029. right: right,
  12030. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  12031. ...processCreateParams(params),
  12032. });
  12033. };
  12034. class ZodTuple extends ZodType {
  12035. _parse(input) {
  12036. const { status, ctx } = this._processInputParams(input);
  12037. if (ctx.parsedType !== util_1.ZodParsedType.array) {
  12038. (0, parseUtil_1.addIssueToContext)(ctx, {
  12039. code: ZodError_1.ZodIssueCode.invalid_type,
  12040. expected: util_1.ZodParsedType.array,
  12041. received: ctx.parsedType,
  12042. });
  12043. return parseUtil_1.INVALID;
  12044. }
  12045. if (ctx.data.length < this._def.items.length) {
  12046. (0, parseUtil_1.addIssueToContext)(ctx, {
  12047. code: ZodError_1.ZodIssueCode.too_small,
  12048. minimum: this._def.items.length,
  12049. inclusive: true,
  12050. exact: false,
  12051. type: "array",
  12052. });
  12053. return parseUtil_1.INVALID;
  12054. }
  12055. const rest = this._def.rest;
  12056. if (!rest && ctx.data.length > this._def.items.length) {
  12057. (0, parseUtil_1.addIssueToContext)(ctx, {
  12058. code: ZodError_1.ZodIssueCode.too_big,
  12059. maximum: this._def.items.length,
  12060. inclusive: true,
  12061. exact: false,
  12062. type: "array",
  12063. });
  12064. status.dirty();
  12065. }
  12066. const items = [...ctx.data]
  12067. .map((item, itemIndex) => {
  12068. const schema = this._def.items[itemIndex] || this._def.rest;
  12069. if (!schema)
  12070. return null;
  12071. return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
  12072. })
  12073. .filter((x) => !!x); // filter nulls
  12074. if (ctx.common.async) {
  12075. return Promise.all(items).then((results) => {
  12076. return parseUtil_1.ParseStatus.mergeArray(status, results);
  12077. });
  12078. }
  12079. else {
  12080. return parseUtil_1.ParseStatus.mergeArray(status, items);
  12081. }
  12082. }
  12083. get items() {
  12084. return this._def.items;
  12085. }
  12086. rest(rest) {
  12087. return new ZodTuple({
  12088. ...this._def,
  12089. rest,
  12090. });
  12091. }
  12092. }
  12093. exports.ZodTuple = ZodTuple;
  12094. ZodTuple.create = (schemas, params) => {
  12095. if (!Array.isArray(schemas)) {
  12096. throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  12097. }
  12098. return new ZodTuple({
  12099. items: schemas,
  12100. typeName: ZodFirstPartyTypeKind.ZodTuple,
  12101. rest: null,
  12102. ...processCreateParams(params),
  12103. });
  12104. };
  12105. class ZodRecord extends ZodType {
  12106. get keySchema() {
  12107. return this._def.keyType;
  12108. }
  12109. get valueSchema() {
  12110. return this._def.valueType;
  12111. }
  12112. _parse(input) {
  12113. const { status, ctx } = this._processInputParams(input);
  12114. if (ctx.parsedType !== util_1.ZodParsedType.object) {
  12115. (0, parseUtil_1.addIssueToContext)(ctx, {
  12116. code: ZodError_1.ZodIssueCode.invalid_type,
  12117. expected: util_1.ZodParsedType.object,
  12118. received: ctx.parsedType,
  12119. });
  12120. return parseUtil_1.INVALID;
  12121. }
  12122. const pairs = [];
  12123. const keyType = this._def.keyType;
  12124. const valueType = this._def.valueType;
  12125. for (const key in ctx.data) {
  12126. pairs.push({
  12127. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
  12128. value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
  12129. });
  12130. }
  12131. if (ctx.common.async) {
  12132. return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs);
  12133. }
  12134. else {
  12135. return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs);
  12136. }
  12137. }
  12138. get element() {
  12139. return this._def.valueType;
  12140. }
  12141. static create(first, second, third) {
  12142. if (second instanceof ZodType) {
  12143. return new ZodRecord({
  12144. keyType: first,
  12145. valueType: second,
  12146. typeName: ZodFirstPartyTypeKind.ZodRecord,
  12147. ...processCreateParams(third),
  12148. });
  12149. }
  12150. return new ZodRecord({
  12151. keyType: ZodString.create(),
  12152. valueType: first,
  12153. typeName: ZodFirstPartyTypeKind.ZodRecord,
  12154. ...processCreateParams(second),
  12155. });
  12156. }
  12157. }
  12158. exports.ZodRecord = ZodRecord;
  12159. class ZodMap extends ZodType {
  12160. get keySchema() {
  12161. return this._def.keyType;
  12162. }
  12163. get valueSchema() {
  12164. return this._def.valueType;
  12165. }
  12166. _parse(input) {
  12167. const { status, ctx } = this._processInputParams(input);
  12168. if (ctx.parsedType !== util_1.ZodParsedType.map) {
  12169. (0, parseUtil_1.addIssueToContext)(ctx, {
  12170. code: ZodError_1.ZodIssueCode.invalid_type,
  12171. expected: util_1.ZodParsedType.map,
  12172. received: ctx.parsedType,
  12173. });
  12174. return parseUtil_1.INVALID;
  12175. }
  12176. const keyType = this._def.keyType;
  12177. const valueType = this._def.valueType;
  12178. const pairs = [...ctx.data.entries()].map(([key, value], index) => {
  12179. return {
  12180. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
  12181. value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
  12182. };
  12183. });
  12184. if (ctx.common.async) {
  12185. const finalMap = new Map();
  12186. return Promise.resolve().then(async () => {
  12187. for (const pair of pairs) {
  12188. const key = await pair.key;
  12189. const value = await pair.value;
  12190. if (key.status === "aborted" || value.status === "aborted") {
  12191. return parseUtil_1.INVALID;
  12192. }
  12193. if (key.status === "dirty" || value.status === "dirty") {
  12194. status.dirty();
  12195. }
  12196. finalMap.set(key.value, value.value);
  12197. }
  12198. return { status: status.value, value: finalMap };
  12199. });
  12200. }
  12201. else {
  12202. const finalMap = new Map();
  12203. for (const pair of pairs) {
  12204. const key = pair.key;
  12205. const value = pair.value;
  12206. if (key.status === "aborted" || value.status === "aborted") {
  12207. return parseUtil_1.INVALID;
  12208. }
  12209. if (key.status === "dirty" || value.status === "dirty") {
  12210. status.dirty();
  12211. }
  12212. finalMap.set(key.value, value.value);
  12213. }
  12214. return { status: status.value, value: finalMap };
  12215. }
  12216. }
  12217. }
  12218. exports.ZodMap = ZodMap;
  12219. ZodMap.create = (keyType, valueType, params) => {
  12220. return new ZodMap({
  12221. valueType,
  12222. keyType,
  12223. typeName: ZodFirstPartyTypeKind.ZodMap,
  12224. ...processCreateParams(params),
  12225. });
  12226. };
  12227. class ZodSet extends ZodType {
  12228. _parse(input) {
  12229. const { status, ctx } = this._processInputParams(input);
  12230. if (ctx.parsedType !== util_1.ZodParsedType.set) {
  12231. (0, parseUtil_1.addIssueToContext)(ctx, {
  12232. code: ZodError_1.ZodIssueCode.invalid_type,
  12233. expected: util_1.ZodParsedType.set,
  12234. received: ctx.parsedType,
  12235. });
  12236. return parseUtil_1.INVALID;
  12237. }
  12238. const def = this._def;
  12239. if (def.minSize !== null) {
  12240. if (ctx.data.size < def.minSize.value) {
  12241. (0, parseUtil_1.addIssueToContext)(ctx, {
  12242. code: ZodError_1.ZodIssueCode.too_small,
  12243. minimum: def.minSize.value,
  12244. type: "set",
  12245. inclusive: true,
  12246. exact: false,
  12247. message: def.minSize.message,
  12248. });
  12249. status.dirty();
  12250. }
  12251. }
  12252. if (def.maxSize !== null) {
  12253. if (ctx.data.size > def.maxSize.value) {
  12254. (0, parseUtil_1.addIssueToContext)(ctx, {
  12255. code: ZodError_1.ZodIssueCode.too_big,
  12256. maximum: def.maxSize.value,
  12257. type: "set",
  12258. inclusive: true,
  12259. exact: false,
  12260. message: def.maxSize.message,
  12261. });
  12262. status.dirty();
  12263. }
  12264. }
  12265. const valueType = this._def.valueType;
  12266. function finalizeSet(elements) {
  12267. const parsedSet = new Set();
  12268. for (const element of elements) {
  12269. if (element.status === "aborted")
  12270. return parseUtil_1.INVALID;
  12271. if (element.status === "dirty")
  12272. status.dirty();
  12273. parsedSet.add(element.value);
  12274. }
  12275. return { status: status.value, value: parsedSet };
  12276. }
  12277. const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
  12278. if (ctx.common.async) {
  12279. return Promise.all(elements).then((elements) => finalizeSet(elements));
  12280. }
  12281. else {
  12282. return finalizeSet(elements);
  12283. }
  12284. }
  12285. min(minSize, message) {
  12286. return new ZodSet({
  12287. ...this._def,
  12288. minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) },
  12289. });
  12290. }
  12291. max(maxSize, message) {
  12292. return new ZodSet({
  12293. ...this._def,
  12294. maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) },
  12295. });
  12296. }
  12297. size(size, message) {
  12298. return this.min(size, message).max(size, message);
  12299. }
  12300. nonempty(message) {
  12301. return this.min(1, message);
  12302. }
  12303. }
  12304. exports.ZodSet = ZodSet;
  12305. ZodSet.create = (valueType, params) => {
  12306. return new ZodSet({
  12307. valueType,
  12308. minSize: null,
  12309. maxSize: null,
  12310. typeName: ZodFirstPartyTypeKind.ZodSet,
  12311. ...processCreateParams(params),
  12312. });
  12313. };
  12314. class ZodFunction extends ZodType {
  12315. constructor() {
  12316. super(...arguments);
  12317. this.validate = this.implement;
  12318. }
  12319. _parse(input) {
  12320. const { ctx } = this._processInputParams(input);
  12321. if (ctx.parsedType !== util_1.ZodParsedType.function) {
  12322. (0, parseUtil_1.addIssueToContext)(ctx, {
  12323. code: ZodError_1.ZodIssueCode.invalid_type,
  12324. expected: util_1.ZodParsedType.function,
  12325. received: ctx.parsedType,
  12326. });
  12327. return parseUtil_1.INVALID;
  12328. }
  12329. function makeArgsIssue(args, error) {
  12330. return (0, parseUtil_1.makeIssue)({
  12331. data: args,
  12332. path: ctx.path,
  12333. errorMaps: [
  12334. ctx.common.contextualErrorMap,
  12335. ctx.schemaErrorMap,
  12336. (0, errors_1.getErrorMap)(),
  12337. errors_1.defaultErrorMap,
  12338. ].filter((x) => !!x),
  12339. issueData: {
  12340. code: ZodError_1.ZodIssueCode.invalid_arguments,
  12341. argumentsError: error,
  12342. },
  12343. });
  12344. }
  12345. function makeReturnsIssue(returns, error) {
  12346. return (0, parseUtil_1.makeIssue)({
  12347. data: returns,
  12348. path: ctx.path,
  12349. errorMaps: [
  12350. ctx.common.contextualErrorMap,
  12351. ctx.schemaErrorMap,
  12352. (0, errors_1.getErrorMap)(),
  12353. errors_1.defaultErrorMap,
  12354. ].filter((x) => !!x),
  12355. issueData: {
  12356. code: ZodError_1.ZodIssueCode.invalid_return_type,
  12357. returnTypeError: error,
  12358. },
  12359. });
  12360. }
  12361. const params = { errorMap: ctx.common.contextualErrorMap };
  12362. const fn = ctx.data;
  12363. if (this._def.returns instanceof ZodPromise) {
  12364. // Would love a way to avoid disabling this rule, but we need
  12365. // an alias (using an arrow function was what caused 2651).
  12366. // eslint-disable-next-line @typescript-eslint/no-this-alias
  12367. const me = this;
  12368. return (0, parseUtil_1.OK)(async function (...args) {
  12369. const error = new ZodError_1.ZodError([]);
  12370. const parsedArgs = await me._def.args
  12371. .parseAsync(args, params)
  12372. .catch((e) => {
  12373. error.addIssue(makeArgsIssue(args, e));
  12374. throw error;
  12375. });
  12376. const result = await Reflect.apply(fn, this, parsedArgs);
  12377. const parsedReturns = await me._def.returns._def.type
  12378. .parseAsync(result, params)
  12379. .catch((e) => {
  12380. error.addIssue(makeReturnsIssue(result, e));
  12381. throw error;
  12382. });
  12383. return parsedReturns;
  12384. });
  12385. }
  12386. else {
  12387. // Would love a way to avoid disabling this rule, but we need
  12388. // an alias (using an arrow function was what caused 2651).
  12389. // eslint-disable-next-line @typescript-eslint/no-this-alias
  12390. const me = this;
  12391. return (0, parseUtil_1.OK)(function (...args) {
  12392. const parsedArgs = me._def.args.safeParse(args, params);
  12393. if (!parsedArgs.success) {
  12394. throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]);
  12395. }
  12396. const result = Reflect.apply(fn, this, parsedArgs.data);
  12397. const parsedReturns = me._def.returns.safeParse(result, params);
  12398. if (!parsedReturns.success) {
  12399. throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]);
  12400. }
  12401. return parsedReturns.data;
  12402. });
  12403. }
  12404. }
  12405. parameters() {
  12406. return this._def.args;
  12407. }
  12408. returnType() {
  12409. return this._def.returns;
  12410. }
  12411. args(...items) {
  12412. return new ZodFunction({
  12413. ...this._def,
  12414. args: ZodTuple.create(items).rest(ZodUnknown.create()),
  12415. });
  12416. }
  12417. returns(returnType) {
  12418. return new ZodFunction({
  12419. ...this._def,
  12420. returns: returnType,
  12421. });
  12422. }
  12423. implement(func) {
  12424. const validatedFunc = this.parse(func);
  12425. return validatedFunc;
  12426. }
  12427. strictImplement(func) {
  12428. const validatedFunc = this.parse(func);
  12429. return validatedFunc;
  12430. }
  12431. static create(args, returns, params) {
  12432. return new ZodFunction({
  12433. args: (args
  12434. ? args
  12435. : ZodTuple.create([]).rest(ZodUnknown.create())),
  12436. returns: returns || ZodUnknown.create(),
  12437. typeName: ZodFirstPartyTypeKind.ZodFunction,
  12438. ...processCreateParams(params),
  12439. });
  12440. }
  12441. }
  12442. exports.ZodFunction = ZodFunction;
  12443. class ZodLazy extends ZodType {
  12444. get schema() {
  12445. return this._def.getter();
  12446. }
  12447. _parse(input) {
  12448. const { ctx } = this._processInputParams(input);
  12449. const lazySchema = this._def.getter();
  12450. return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  12451. }
  12452. }
  12453. exports.ZodLazy = ZodLazy;
  12454. ZodLazy.create = (getter, params) => {
  12455. return new ZodLazy({
  12456. getter: getter,
  12457. typeName: ZodFirstPartyTypeKind.ZodLazy,
  12458. ...processCreateParams(params),
  12459. });
  12460. };
  12461. class ZodLiteral extends ZodType {
  12462. _parse(input) {
  12463. if (input.data !== this._def.value) {
  12464. const ctx = this._getOrReturnCtx(input);
  12465. (0, parseUtil_1.addIssueToContext)(ctx, {
  12466. received: ctx.data,
  12467. code: ZodError_1.ZodIssueCode.invalid_literal,
  12468. expected: this._def.value,
  12469. });
  12470. return parseUtil_1.INVALID;
  12471. }
  12472. return { status: "valid", value: input.data };
  12473. }
  12474. get value() {
  12475. return this._def.value;
  12476. }
  12477. }
  12478. exports.ZodLiteral = ZodLiteral;
  12479. ZodLiteral.create = (value, params) => {
  12480. return new ZodLiteral({
  12481. value: value,
  12482. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  12483. ...processCreateParams(params),
  12484. });
  12485. };
  12486. function createZodEnum(values, params) {
  12487. return new ZodEnum({
  12488. values,
  12489. typeName: ZodFirstPartyTypeKind.ZodEnum,
  12490. ...processCreateParams(params),
  12491. });
  12492. }
  12493. class ZodEnum extends ZodType {
  12494. _parse(input) {
  12495. if (typeof input.data !== "string") {
  12496. const ctx = this._getOrReturnCtx(input);
  12497. const expectedValues = this._def.values;
  12498. (0, parseUtil_1.addIssueToContext)(ctx, {
  12499. expected: util_1.util.joinValues(expectedValues),
  12500. received: ctx.parsedType,
  12501. code: ZodError_1.ZodIssueCode.invalid_type,
  12502. });
  12503. return parseUtil_1.INVALID;
  12504. }
  12505. if (this._def.values.indexOf(input.data) === -1) {
  12506. const ctx = this._getOrReturnCtx(input);
  12507. const expectedValues = this._def.values;
  12508. (0, parseUtil_1.addIssueToContext)(ctx, {
  12509. received: ctx.data,
  12510. code: ZodError_1.ZodIssueCode.invalid_enum_value,
  12511. options: expectedValues,
  12512. });
  12513. return parseUtil_1.INVALID;
  12514. }
  12515. return (0, parseUtil_1.OK)(input.data);
  12516. }
  12517. get options() {
  12518. return this._def.values;
  12519. }
  12520. get enum() {
  12521. const enumValues = {};
  12522. for (const val of this._def.values) {
  12523. enumValues[val] = val;
  12524. }
  12525. return enumValues;
  12526. }
  12527. get Values() {
  12528. const enumValues = {};
  12529. for (const val of this._def.values) {
  12530. enumValues[val] = val;
  12531. }
  12532. return enumValues;
  12533. }
  12534. get Enum() {
  12535. const enumValues = {};
  12536. for (const val of this._def.values) {
  12537. enumValues[val] = val;
  12538. }
  12539. return enumValues;
  12540. }
  12541. extract(values) {
  12542. return ZodEnum.create(values);
  12543. }
  12544. exclude(values) {
  12545. return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
  12546. }
  12547. }
  12548. exports.ZodEnum = ZodEnum;
  12549. ZodEnum.create = createZodEnum;
  12550. class ZodNativeEnum extends ZodType {
  12551. _parse(input) {
  12552. const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values);
  12553. const ctx = this._getOrReturnCtx(input);
  12554. if (ctx.parsedType !== util_1.ZodParsedType.string &&
  12555. ctx.parsedType !== util_1.ZodParsedType.number) {
  12556. const expectedValues = util_1.util.objectValues(nativeEnumValues);
  12557. (0, parseUtil_1.addIssueToContext)(ctx, {
  12558. expected: util_1.util.joinValues(expectedValues),
  12559. received: ctx.parsedType,
  12560. code: ZodError_1.ZodIssueCode.invalid_type,
  12561. });
  12562. return parseUtil_1.INVALID;
  12563. }
  12564. if (nativeEnumValues.indexOf(input.data) === -1) {
  12565. const expectedValues = util_1.util.objectValues(nativeEnumValues);
  12566. (0, parseUtil_1.addIssueToContext)(ctx, {
  12567. received: ctx.data,
  12568. code: ZodError_1.ZodIssueCode.invalid_enum_value,
  12569. options: expectedValues,
  12570. });
  12571. return parseUtil_1.INVALID;
  12572. }
  12573. return (0, parseUtil_1.OK)(input.data);
  12574. }
  12575. get enum() {
  12576. return this._def.values;
  12577. }
  12578. }
  12579. exports.ZodNativeEnum = ZodNativeEnum;
  12580. ZodNativeEnum.create = (values, params) => {
  12581. return new ZodNativeEnum({
  12582. values: values,
  12583. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  12584. ...processCreateParams(params),
  12585. });
  12586. };
  12587. class ZodPromise extends ZodType {
  12588. unwrap() {
  12589. return this._def.type;
  12590. }
  12591. _parse(input) {
  12592. const { ctx } = this._processInputParams(input);
  12593. if (ctx.parsedType !== util_1.ZodParsedType.promise &&
  12594. ctx.common.async === false) {
  12595. (0, parseUtil_1.addIssueToContext)(ctx, {
  12596. code: ZodError_1.ZodIssueCode.invalid_type,
  12597. expected: util_1.ZodParsedType.promise,
  12598. received: ctx.parsedType,
  12599. });
  12600. return parseUtil_1.INVALID;
  12601. }
  12602. const promisified = ctx.parsedType === util_1.ZodParsedType.promise
  12603. ? ctx.data
  12604. : Promise.resolve(ctx.data);
  12605. return (0, parseUtil_1.OK)(promisified.then((data) => {
  12606. return this._def.type.parseAsync(data, {
  12607. path: ctx.path,
  12608. errorMap: ctx.common.contextualErrorMap,
  12609. });
  12610. }));
  12611. }
  12612. }
  12613. exports.ZodPromise = ZodPromise;
  12614. ZodPromise.create = (schema, params) => {
  12615. return new ZodPromise({
  12616. type: schema,
  12617. typeName: ZodFirstPartyTypeKind.ZodPromise,
  12618. ...processCreateParams(params),
  12619. });
  12620. };
  12621. class ZodEffects extends ZodType {
  12622. innerType() {
  12623. return this._def.schema;
  12624. }
  12625. sourceType() {
  12626. return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
  12627. ? this._def.schema.sourceType()
  12628. : this._def.schema;
  12629. }
  12630. _parse(input) {
  12631. const { status, ctx } = this._processInputParams(input);
  12632. const effect = this._def.effect || null;
  12633. const checkCtx = {
  12634. addIssue: (arg) => {
  12635. (0, parseUtil_1.addIssueToContext)(ctx, arg);
  12636. if (arg.fatal) {
  12637. status.abort();
  12638. }
  12639. else {
  12640. status.dirty();
  12641. }
  12642. },
  12643. get path() {
  12644. return ctx.path;
  12645. },
  12646. };
  12647. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
  12648. if (effect.type === "preprocess") {
  12649. const processed = effect.transform(ctx.data, checkCtx);
  12650. if (ctx.common.issues.length) {
  12651. return {
  12652. status: "dirty",
  12653. value: ctx.data,
  12654. };
  12655. }
  12656. if (ctx.common.async) {
  12657. return Promise.resolve(processed).then((processed) => {
  12658. return this._def.schema._parseAsync({
  12659. data: processed,
  12660. path: ctx.path,
  12661. parent: ctx,
  12662. });
  12663. });
  12664. }
  12665. else {
  12666. return this._def.schema._parseSync({
  12667. data: processed,
  12668. path: ctx.path,
  12669. parent: ctx,
  12670. });
  12671. }
  12672. }
  12673. if (effect.type === "refinement") {
  12674. const executeRefinement = (acc
  12675. // effect: RefinementEffect<any>
  12676. ) => {
  12677. const result = effect.refinement(acc, checkCtx);
  12678. if (ctx.common.async) {
  12679. return Promise.resolve(result);
  12680. }
  12681. if (result instanceof Promise) {
  12682. throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
  12683. }
  12684. return acc;
  12685. };
  12686. if (ctx.common.async === false) {
  12687. const inner = this._def.schema._parseSync({
  12688. data: ctx.data,
  12689. path: ctx.path,
  12690. parent: ctx,
  12691. });
  12692. if (inner.status === "aborted")
  12693. return parseUtil_1.INVALID;
  12694. if (inner.status === "dirty")
  12695. status.dirty();
  12696. // return value is ignored
  12697. executeRefinement(inner.value);
  12698. return { status: status.value, value: inner.value };
  12699. }
  12700. else {
  12701. return this._def.schema
  12702. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  12703. .then((inner) => {
  12704. if (inner.status === "aborted")
  12705. return parseUtil_1.INVALID;
  12706. if (inner.status === "dirty")
  12707. status.dirty();
  12708. return executeRefinement(inner.value).then(() => {
  12709. return { status: status.value, value: inner.value };
  12710. });
  12711. });
  12712. }
  12713. }
  12714. if (effect.type === "transform") {
  12715. if (ctx.common.async === false) {
  12716. const base = this._def.schema._parseSync({
  12717. data: ctx.data,
  12718. path: ctx.path,
  12719. parent: ctx,
  12720. });
  12721. if (!(0, parseUtil_1.isValid)(base))
  12722. return base;
  12723. const result = effect.transform(base.value, checkCtx);
  12724. if (result instanceof Promise) {
  12725. throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
  12726. }
  12727. return { status: status.value, value: result };
  12728. }
  12729. else {
  12730. return this._def.schema
  12731. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  12732. .then((base) => {
  12733. if (!(0, parseUtil_1.isValid)(base))
  12734. return base;
  12735. return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
  12736. });
  12737. }
  12738. }
  12739. util_1.util.assertNever(effect);
  12740. }
  12741. }
  12742. exports.ZodEffects = ZodEffects;
  12743. exports.ZodTransformer = ZodEffects;
  12744. ZodEffects.create = (schema, effect, params) => {
  12745. return new ZodEffects({
  12746. schema,
  12747. typeName: ZodFirstPartyTypeKind.ZodEffects,
  12748. effect,
  12749. ...processCreateParams(params),
  12750. });
  12751. };
  12752. ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  12753. return new ZodEffects({
  12754. schema,
  12755. effect: { type: "preprocess", transform: preprocess },
  12756. typeName: ZodFirstPartyTypeKind.ZodEffects,
  12757. ...processCreateParams(params),
  12758. });
  12759. };
  12760. class ZodOptional extends ZodType {
  12761. _parse(input) {
  12762. const parsedType = this._getType(input);
  12763. if (parsedType === util_1.ZodParsedType.undefined) {
  12764. return (0, parseUtil_1.OK)(undefined);
  12765. }
  12766. return this._def.innerType._parse(input);
  12767. }
  12768. unwrap() {
  12769. return this._def.innerType;
  12770. }
  12771. }
  12772. exports.ZodOptional = ZodOptional;
  12773. ZodOptional.create = (type, params) => {
  12774. return new ZodOptional({
  12775. innerType: type,
  12776. typeName: ZodFirstPartyTypeKind.ZodOptional,
  12777. ...processCreateParams(params),
  12778. });
  12779. };
  12780. class ZodNullable extends ZodType {
  12781. _parse(input) {
  12782. const parsedType = this._getType(input);
  12783. if (parsedType === util_1.ZodParsedType.null) {
  12784. return (0, parseUtil_1.OK)(null);
  12785. }
  12786. return this._def.innerType._parse(input);
  12787. }
  12788. unwrap() {
  12789. return this._def.innerType;
  12790. }
  12791. }
  12792. exports.ZodNullable = ZodNullable;
  12793. ZodNullable.create = (type, params) => {
  12794. return new ZodNullable({
  12795. innerType: type,
  12796. typeName: ZodFirstPartyTypeKind.ZodNullable,
  12797. ...processCreateParams(params),
  12798. });
  12799. };
  12800. class ZodDefault extends ZodType {
  12801. _parse(input) {
  12802. const { ctx } = this._processInputParams(input);
  12803. let data = ctx.data;
  12804. if (ctx.parsedType === util_1.ZodParsedType.undefined) {
  12805. data = this._def.defaultValue();
  12806. }
  12807. return this._def.innerType._parse({
  12808. data,
  12809. path: ctx.path,
  12810. parent: ctx,
  12811. });
  12812. }
  12813. removeDefault() {
  12814. return this._def.innerType;
  12815. }
  12816. }
  12817. exports.ZodDefault = ZodDefault;
  12818. ZodDefault.create = (type, params) => {
  12819. return new ZodDefault({
  12820. innerType: type,
  12821. typeName: ZodFirstPartyTypeKind.ZodDefault,
  12822. defaultValue: typeof params.default === "function"
  12823. ? params.default
  12824. : () => params.default,
  12825. ...processCreateParams(params),
  12826. });
  12827. };
  12828. class ZodCatch extends ZodType {
  12829. _parse(input) {
  12830. const { ctx } = this._processInputParams(input);
  12831. // newCtx is used to not collect issues from inner types in ctx
  12832. const newCtx = {
  12833. ...ctx,
  12834. common: {
  12835. ...ctx.common,
  12836. issues: [],
  12837. },
  12838. };
  12839. const result = this._def.innerType._parse({
  12840. data: newCtx.data,
  12841. path: newCtx.path,
  12842. parent: {
  12843. ...newCtx,
  12844. },
  12845. });
  12846. if ((0, parseUtil_1.isAsync)(result)) {
  12847. return result.then((result) => {
  12848. return {
  12849. status: "valid",
  12850. value: result.status === "valid"
  12851. ? result.value
  12852. : this._def.catchValue({
  12853. get error() {
  12854. return new ZodError_1.ZodError(newCtx.common.issues);
  12855. },
  12856. input: newCtx.data,
  12857. }),
  12858. };
  12859. });
  12860. }
  12861. else {
  12862. return {
  12863. status: "valid",
  12864. value: result.status === "valid"
  12865. ? result.value
  12866. : this._def.catchValue({
  12867. get error() {
  12868. return new ZodError_1.ZodError(newCtx.common.issues);
  12869. },
  12870. input: newCtx.data,
  12871. }),
  12872. };
  12873. }
  12874. }
  12875. removeCatch() {
  12876. return this._def.innerType;
  12877. }
  12878. }
  12879. exports.ZodCatch = ZodCatch;
  12880. ZodCatch.create = (type, params) => {
  12881. return new ZodCatch({
  12882. innerType: type,
  12883. typeName: ZodFirstPartyTypeKind.ZodCatch,
  12884. catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
  12885. ...processCreateParams(params),
  12886. });
  12887. };
  12888. class ZodNaN extends ZodType {
  12889. _parse(input) {
  12890. const parsedType = this._getType(input);
  12891. if (parsedType !== util_1.ZodParsedType.nan) {
  12892. const ctx = this._getOrReturnCtx(input);
  12893. (0, parseUtil_1.addIssueToContext)(ctx, {
  12894. code: ZodError_1.ZodIssueCode.invalid_type,
  12895. expected: util_1.ZodParsedType.nan,
  12896. received: ctx.parsedType,
  12897. });
  12898. return parseUtil_1.INVALID;
  12899. }
  12900. return { status: "valid", value: input.data };
  12901. }
  12902. }
  12903. exports.ZodNaN = ZodNaN;
  12904. ZodNaN.create = (params) => {
  12905. return new ZodNaN({
  12906. typeName: ZodFirstPartyTypeKind.ZodNaN,
  12907. ...processCreateParams(params),
  12908. });
  12909. };
  12910. exports.BRAND = Symbol("zod_brand");
  12911. class ZodBranded extends ZodType {
  12912. _parse(input) {
  12913. const { ctx } = this._processInputParams(input);
  12914. const data = ctx.data;
  12915. return this._def.type._parse({
  12916. data,
  12917. path: ctx.path,
  12918. parent: ctx,
  12919. });
  12920. }
  12921. unwrap() {
  12922. return this._def.type;
  12923. }
  12924. }
  12925. exports.ZodBranded = ZodBranded;
  12926. class ZodPipeline extends ZodType {
  12927. _parse(input) {
  12928. const { status, ctx } = this._processInputParams(input);
  12929. if (ctx.common.async) {
  12930. const handleAsync = async () => {
  12931. const inResult = await this._def.in._parseAsync({
  12932. data: ctx.data,
  12933. path: ctx.path,
  12934. parent: ctx,
  12935. });
  12936. if (inResult.status === "aborted")
  12937. return parseUtil_1.INVALID;
  12938. if (inResult.status === "dirty") {
  12939. status.dirty();
  12940. return (0, parseUtil_1.DIRTY)(inResult.value);
  12941. }
  12942. else {
  12943. return this._def.out._parseAsync({
  12944. data: inResult.value,
  12945. path: ctx.path,
  12946. parent: ctx,
  12947. });
  12948. }
  12949. };
  12950. return handleAsync();
  12951. }
  12952. else {
  12953. const inResult = this._def.in._parseSync({
  12954. data: ctx.data,
  12955. path: ctx.path,
  12956. parent: ctx,
  12957. });
  12958. if (inResult.status === "aborted")
  12959. return parseUtil_1.INVALID;
  12960. if (inResult.status === "dirty") {
  12961. status.dirty();
  12962. return {
  12963. status: "dirty",
  12964. value: inResult.value,
  12965. };
  12966. }
  12967. else {
  12968. return this._def.out._parseSync({
  12969. data: inResult.value,
  12970. path: ctx.path,
  12971. parent: ctx,
  12972. });
  12973. }
  12974. }
  12975. }
  12976. static create(a, b) {
  12977. return new ZodPipeline({
  12978. in: a,
  12979. out: b,
  12980. typeName: ZodFirstPartyTypeKind.ZodPipeline,
  12981. });
  12982. }
  12983. }
  12984. exports.ZodPipeline = ZodPipeline;
  12985. class ZodReadonly extends ZodType {
  12986. _parse(input) {
  12987. const result = this._def.innerType._parse(input);
  12988. if ((0, parseUtil_1.isValid)(result)) {
  12989. result.value = Object.freeze(result.value);
  12990. }
  12991. return result;
  12992. }
  12993. }
  12994. exports.ZodReadonly = ZodReadonly;
  12995. ZodReadonly.create = (type, params) => {
  12996. return new ZodReadonly({
  12997. innerType: type,
  12998. typeName: ZodFirstPartyTypeKind.ZodReadonly,
  12999. ...processCreateParams(params),
  13000. });
  13001. };
  13002. const custom = (check, params = {},
  13003. /**
  13004. * @deprecated
  13005. *
  13006. * Pass `fatal` into the params object instead:
  13007. *
  13008. * ```ts
  13009. * z.string().custom((val) => val.length > 5, { fatal: false })
  13010. * ```
  13011. *
  13012. */
  13013. fatal) => {
  13014. if (check)
  13015. return ZodAny.create().superRefine((data, ctx) => {
  13016. var _a, _b;
  13017. if (!check(data)) {
  13018. const p = typeof params === "function"
  13019. ? params(data)
  13020. : typeof params === "string"
  13021. ? { message: params }
  13022. : params;
  13023. const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
  13024. const p2 = typeof p === "string" ? { message: p } : p;
  13025. ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
  13026. }
  13027. });
  13028. return ZodAny.create();
  13029. };
  13030. exports.custom = custom;
  13031. exports.late = {
  13032. object: ZodObject.lazycreate,
  13033. };
  13034. var ZodFirstPartyTypeKind;
  13035. (function (ZodFirstPartyTypeKind) {
  13036. ZodFirstPartyTypeKind["ZodString"] = "ZodString";
  13037. ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
  13038. ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
  13039. ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
  13040. ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
  13041. ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
  13042. ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
  13043. ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
  13044. ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
  13045. ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
  13046. ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
  13047. ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
  13048. ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
  13049. ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
  13050. ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
  13051. ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
  13052. ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  13053. ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
  13054. ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
  13055. ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
  13056. ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
  13057. ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
  13058. ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
  13059. ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
  13060. ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
  13061. ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
  13062. ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
  13063. ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
  13064. ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
  13065. ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
  13066. ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
  13067. ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
  13068. ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
  13069. ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
  13070. ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
  13071. ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
  13072. })(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
  13073. const instanceOfType = (
  13074. // const instanceOfType = <T extends new (...args: any[]) => any>(
  13075. cls, params = {
  13076. message: `Input not instance of ${cls.name}`,
  13077. }) => (0, exports.custom)((data) => data instanceof cls, params);
  13078. exports.instanceof = instanceOfType;
  13079. const stringType = ZodString.create;
  13080. exports.string = stringType;
  13081. const numberType = ZodNumber.create;
  13082. exports.number = numberType;
  13083. const nanType = ZodNaN.create;
  13084. exports.nan = nanType;
  13085. const bigIntType = ZodBigInt.create;
  13086. exports.bigint = bigIntType;
  13087. const booleanType = ZodBoolean.create;
  13088. exports.boolean = booleanType;
  13089. const dateType = ZodDate.create;
  13090. exports.date = dateType;
  13091. const symbolType = ZodSymbol.create;
  13092. exports.symbol = symbolType;
  13093. const undefinedType = ZodUndefined.create;
  13094. exports.undefined = undefinedType;
  13095. const nullType = ZodNull.create;
  13096. exports.null = nullType;
  13097. const anyType = ZodAny.create;
  13098. exports.any = anyType;
  13099. const unknownType = ZodUnknown.create;
  13100. exports.unknown = unknownType;
  13101. const neverType = ZodNever.create;
  13102. exports.never = neverType;
  13103. const voidType = ZodVoid.create;
  13104. exports.void = voidType;
  13105. const arrayType = ZodArray.create;
  13106. exports.array = arrayType;
  13107. const objectType = ZodObject.create;
  13108. exports.object = objectType;
  13109. const strictObjectType = ZodObject.strictCreate;
  13110. exports.strictObject = strictObjectType;
  13111. const unionType = ZodUnion.create;
  13112. exports.union = unionType;
  13113. const discriminatedUnionType = ZodDiscriminatedUnion.create;
  13114. exports.discriminatedUnion = discriminatedUnionType;
  13115. const intersectionType = ZodIntersection.create;
  13116. exports.intersection = intersectionType;
  13117. const tupleType = ZodTuple.create;
  13118. exports.tuple = tupleType;
  13119. const recordType = ZodRecord.create;
  13120. exports.record = recordType;
  13121. const mapType = ZodMap.create;
  13122. exports.map = mapType;
  13123. const setType = ZodSet.create;
  13124. exports.set = setType;
  13125. const functionType = ZodFunction.create;
  13126. exports.function = functionType;
  13127. const lazyType = ZodLazy.create;
  13128. exports.lazy = lazyType;
  13129. const literalType = ZodLiteral.create;
  13130. exports.literal = literalType;
  13131. const enumType = ZodEnum.create;
  13132. exports.enum = enumType;
  13133. const nativeEnumType = ZodNativeEnum.create;
  13134. exports.nativeEnum = nativeEnumType;
  13135. const promiseType = ZodPromise.create;
  13136. exports.promise = promiseType;
  13137. const effectsType = ZodEffects.create;
  13138. exports.effect = effectsType;
  13139. exports.transformer = effectsType;
  13140. const optionalType = ZodOptional.create;
  13141. exports.optional = optionalType;
  13142. const nullableType = ZodNullable.create;
  13143. exports.nullable = nullableType;
  13144. const preprocessType = ZodEffects.createWithPreprocess;
  13145. exports.preprocess = preprocessType;
  13146. const pipelineType = ZodPipeline.create;
  13147. exports.pipeline = pipelineType;
  13148. const ostring = () => stringType().optional();
  13149. exports.ostring = ostring;
  13150. const onumber = () => numberType().optional();
  13151. exports.onumber = onumber;
  13152. const oboolean = () => booleanType().optional();
  13153. exports.oboolean = oboolean;
  13154. exports.coerce = {
  13155. string: ((arg) => ZodString.create({ ...arg, coerce: true })),
  13156. number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
  13157. boolean: ((arg) => ZodBoolean.create({
  13158. ...arg,
  13159. coerce: true,
  13160. })),
  13161. bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
  13162. date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
  13163. };
  13164. exports.NEVER = parseUtil_1.INVALID;
  13165. } (types));
  13166. (function (exports) {
  13167. var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  13168. if (k2 === undefined) k2 = k;
  13169. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  13170. }) : (function(o, m, k, k2) {
  13171. if (k2 === undefined) k2 = k;
  13172. o[k2] = m[k];
  13173. }));
  13174. var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
  13175. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  13176. };
  13177. Object.defineProperty(exports, "__esModule", { value: true });
  13178. __exportStar(errors, exports);
  13179. __exportStar(parseUtil, exports);
  13180. __exportStar(typeAliases, exports);
  13181. __exportStar(util, exports);
  13182. __exportStar(types, exports);
  13183. __exportStar(ZodError$1, exports);
  13184. } (external));
  13185. (function (exports) {
  13186. var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  13187. if (k2 === undefined) k2 = k;
  13188. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  13189. }) : (function(o, m, k, k2) {
  13190. if (k2 === undefined) k2 = k;
  13191. o[k2] = m[k];
  13192. }));
  13193. var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
  13194. Object.defineProperty(o, "default", { enumerable: true, value: v });
  13195. }) : function(o, v) {
  13196. o["default"] = v;
  13197. });
  13198. var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
  13199. if (mod && mod.__esModule) return mod;
  13200. var result = {};
  13201. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  13202. __setModuleDefault(result, mod);
  13203. return result;
  13204. };
  13205. var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
  13206. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  13207. };
  13208. Object.defineProperty(exports, "__esModule", { value: true });
  13209. exports.z = void 0;
  13210. const z = __importStar(external);
  13211. exports.z = z;
  13212. __exportStar(external, exports);
  13213. exports.default = z;
  13214. } (lib));
  13215. var webdriverBidiPermissions = {};
  13216. /**
  13217. * Copyright 2024 Google LLC.
  13218. * Copyright (c) Microsoft Corporation.
  13219. *
  13220. * Licensed under the Apache License, Version 2.0 (the "License");
  13221. * you may not use this file except in compliance with the License.
  13222. * You may obtain a copy of the License at
  13223. *
  13224. * http://www.apache.org/licenses/LICENSE-2.0
  13225. *
  13226. * Unless required by applicable law or agreed to in writing, software
  13227. * distributed under the License is distributed on an "AS IS" BASIS,
  13228. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13229. * See the License for the specific language governing permissions and
  13230. * limitations under the License.
  13231. */
  13232. var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  13233. return (mod && mod.__esModule) ? mod : { "default": mod };
  13234. };
  13235. Object.defineProperty(webdriverBidiPermissions, "__esModule", { value: true });
  13236. webdriverBidiPermissions.Permissions = webdriverBidiPermissions.PermissionsCommandSchema = void 0;
  13237. /**
  13238. * THIS FILE IS AUTOGENERATED by cddlconv 0.1.5.
  13239. * Run `node tools/generate-bidi-types.mjs` to regenerate.
  13240. * @see https://github.com/w3c/webdriver-bidi/blob/master/index.bs
  13241. */
  13242. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  13243. // @ts-nocheck Some types may be circular.
  13244. const zod_1$1 = __importDefault(lib);
  13245. webdriverBidiPermissions.PermissionsCommandSchema = zod_1$1.default.lazy(() => Permissions$1.SetPermissionSchema);
  13246. var Permissions$1;
  13247. (function (Permissions) {
  13248. Permissions.PermissionDescriptorSchema = zod_1$1.default.lazy(() => zod_1$1.default.object({
  13249. name: zod_1$1.default.string(),
  13250. }));
  13251. })(Permissions$1 || (webdriverBidiPermissions.Permissions = Permissions$1 = {}));
  13252. (function (Permissions) {
  13253. Permissions.PermissionStateSchema = zod_1$1.default.lazy(() => zod_1$1.default.enum(['granted', 'denied', 'prompt']));
  13254. })(Permissions$1 || (webdriverBidiPermissions.Permissions = Permissions$1 = {}));
  13255. (function (Permissions) {
  13256. Permissions.SetPermissionSchema = zod_1$1.default.lazy(() => zod_1$1.default.object({
  13257. method: zod_1$1.default.literal('permissions.setPermission'),
  13258. params: Permissions.SetPermissionParametersSchema,
  13259. }));
  13260. })(Permissions$1 || (webdriverBidiPermissions.Permissions = Permissions$1 = {}));
  13261. (function (Permissions) {
  13262. Permissions.SetPermissionParametersSchema = zod_1$1.default.lazy(() => zod_1$1.default.object({
  13263. descriptor: Permissions.PermissionDescriptorSchema,
  13264. state: Permissions.PermissionStateSchema,
  13265. origin: zod_1$1.default.string(),
  13266. userContext: zod_1$1.default.string().optional(),
  13267. }));
  13268. })(Permissions$1 || (webdriverBidiPermissions.Permissions = Permissions$1 = {}));
  13269. var webdriverBidi = {};
  13270. (function (exports) {
  13271. /**
  13272. * Copyright 2024 Google LLC.
  13273. * Copyright (c) Microsoft Corporation.
  13274. *
  13275. * Licensed under the Apache License, Version 2.0 (the "License");
  13276. * you may not use this file except in compliance with the License.
  13277. * You may obtain a copy of the License at
  13278. *
  13279. * http://www.apache.org/licenses/LICENSE-2.0
  13280. *
  13281. * Unless required by applicable law or agreed to in writing, software
  13282. * distributed under the License is distributed on an "AS IS" BASIS,
  13283. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13284. * See the License for the specific language governing permissions and
  13285. * limitations under the License.
  13286. */
  13287. var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  13288. return (mod && mod.__esModule) ? mod : { "default": mod };
  13289. };
  13290. Object.defineProperty(exports, "__esModule", { value: true });
  13291. exports.Input = exports.InputCommandSchema = exports.Log = exports.LogEventSchema = exports.Storage = exports.StorageResultSchema = exports.StorageCommandSchema = exports.Script = exports.ScriptResultSchema = exports.ScriptCommandSchema = exports.ScriptEventSchema = exports.Network = exports.NetworkResultSchema = exports.NetworkEventSchema = exports.NetworkCommandSchema = exports.BrowsingContext = exports.BrowsingContextResultSchema = exports.BrowsingContextEventSchema = exports.BrowsingContextCommandSchema = exports.Browser = exports.BrowserResultSchema = exports.BrowserCommandSchema = exports.SessionResultSchema = exports.Session = exports.SessionCommandSchema = exports.ErrorCodeSchema = exports.JsUintSchema = exports.JsIntSchema = exports.ExtensibleSchema = exports.EmptyResultSchema = exports.ErrorResponseSchema = exports.MessageSchema = exports.EmptyParamsSchema = exports.ResultDataSchema = exports.CommandDataSchema = exports.EventDataSchema = exports.CommandResponseSchema = exports.CommandSchema = exports.EventSchema = void 0;
  13292. /**
  13293. * THIS FILE IS AUTOGENERATED by cddlconv 0.1.5.
  13294. * Run `node tools/generate-bidi-types.mjs` to regenerate.
  13295. * @see https://github.com/w3c/webdriver-bidi/blob/master/index.bs
  13296. */
  13297. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  13298. // @ts-nocheck Some types may be circular.
  13299. const zod_1 = __importDefault(lib);
  13300. exports.EventSchema = zod_1.default.lazy(() => zod_1.default
  13301. .object({
  13302. type: zod_1.default.literal('event'),
  13303. })
  13304. .and(exports.EventDataSchema)
  13305. .and(exports.ExtensibleSchema));
  13306. exports.CommandSchema = zod_1.default.lazy(() => zod_1.default
  13307. .object({
  13308. id: exports.JsUintSchema,
  13309. })
  13310. .and(exports.CommandDataSchema)
  13311. .and(exports.ExtensibleSchema));
  13312. exports.CommandResponseSchema = zod_1.default.lazy(() => zod_1.default
  13313. .object({
  13314. type: zod_1.default.literal('success'),
  13315. id: exports.JsUintSchema,
  13316. result: exports.ResultDataSchema,
  13317. })
  13318. .and(exports.ExtensibleSchema));
  13319. exports.EventDataSchema = zod_1.default.lazy(() => zod_1.default.union([
  13320. exports.BrowsingContextEventSchema,
  13321. exports.LogEventSchema,
  13322. exports.NetworkEventSchema,
  13323. exports.ScriptEventSchema,
  13324. ]));
  13325. exports.CommandDataSchema = zod_1.default.lazy(() => zod_1.default.union([
  13326. exports.BrowserCommandSchema,
  13327. exports.BrowsingContextCommandSchema,
  13328. exports.InputCommandSchema,
  13329. exports.NetworkCommandSchema,
  13330. exports.ScriptCommandSchema,
  13331. exports.SessionCommandSchema,
  13332. exports.StorageCommandSchema,
  13333. ]));
  13334. exports.ResultDataSchema = zod_1.default.lazy(() => zod_1.default.union([
  13335. exports.BrowsingContextResultSchema,
  13336. exports.EmptyResultSchema,
  13337. exports.NetworkResultSchema,
  13338. exports.ScriptResultSchema,
  13339. exports.SessionResultSchema,
  13340. exports.StorageResultSchema,
  13341. ]));
  13342. exports.EmptyParamsSchema = zod_1.default.lazy(() => exports.ExtensibleSchema);
  13343. exports.MessageSchema = zod_1.default.lazy(() => zod_1.default.union([exports.CommandResponseSchema, exports.ErrorResponseSchema, exports.EventSchema]));
  13344. exports.ErrorResponseSchema = zod_1.default.lazy(() => zod_1.default
  13345. .object({
  13346. type: zod_1.default.literal('error'),
  13347. id: zod_1.default.union([exports.JsUintSchema, zod_1.default.null()]),
  13348. error: exports.ErrorCodeSchema,
  13349. message: zod_1.default.string(),
  13350. stacktrace: zod_1.default.string().optional(),
  13351. })
  13352. .and(exports.ExtensibleSchema));
  13353. exports.EmptyResultSchema = zod_1.default.lazy(() => exports.ExtensibleSchema);
  13354. exports.ExtensibleSchema = zod_1.default.lazy(() => zod_1.default.record(zod_1.default.string(), zod_1.default.any()));
  13355. exports.JsIntSchema = zod_1.default
  13356. .number()
  13357. .int()
  13358. .gte(-9007199254740991)
  13359. .lte(9007199254740991);
  13360. exports.JsUintSchema = zod_1.default
  13361. .number()
  13362. .int()
  13363. .nonnegative()
  13364. .gte(0)
  13365. .lte(9007199254740991);
  13366. exports.ErrorCodeSchema = zod_1.default.lazy(() => zod_1.default.enum([
  13367. 'invalid argument',
  13368. 'invalid selector',
  13369. 'invalid session id',
  13370. 'move target out of bounds',
  13371. 'no such alert',
  13372. 'no such element',
  13373. 'no such frame',
  13374. 'no such handle',
  13375. 'no such history entry',
  13376. 'no such intercept',
  13377. 'no such node',
  13378. 'no such request',
  13379. 'no such script',
  13380. 'no such storage partition',
  13381. 'no such user context',
  13382. 'session not created',
  13383. 'unable to capture screen',
  13384. 'unable to close browser',
  13385. 'unable to set cookie',
  13386. 'unable to set file input',
  13387. 'underspecified storage partition',
  13388. 'unknown command',
  13389. 'unknown error',
  13390. 'unsupported operation',
  13391. ]));
  13392. exports.SessionCommandSchema = zod_1.default.lazy(() => zod_1.default.union([
  13393. Session.EndSchema,
  13394. Session.NewSchema,
  13395. Session.StatusSchema,
  13396. Session.SubscribeSchema,
  13397. Session.UnsubscribeSchema,
  13398. ]));
  13399. var Session;
  13400. (function (Session) {
  13401. Session.ProxyConfigurationSchema = zod_1.default.lazy(() => zod_1.default.union([
  13402. Session.AutodetectProxyConfigurationSchema,
  13403. Session.DirectProxyConfigurationSchema,
  13404. Session.ManualProxyConfigurationSchema,
  13405. Session.PacProxyConfigurationSchema,
  13406. Session.SystemProxyConfigurationSchema,
  13407. zod_1.default.object({}),
  13408. ]));
  13409. })(Session || (exports.Session = Session = {}));
  13410. exports.SessionResultSchema = zod_1.default.lazy(() => zod_1.default.union([Session.NewResultSchema, Session.StatusResultSchema]));
  13411. (function (Session) {
  13412. Session.CapabilitiesRequestSchema = zod_1.default.lazy(() => zod_1.default.object({
  13413. alwaysMatch: Session.CapabilityRequestSchema.optional(),
  13414. firstMatch: zod_1.default.array(Session.CapabilityRequestSchema).optional(),
  13415. }));
  13416. })(Session || (exports.Session = Session = {}));
  13417. (function (Session) {
  13418. Session.CapabilityRequestSchema = zod_1.default.lazy(() => zod_1.default
  13419. .object({
  13420. acceptInsecureCerts: zod_1.default.boolean().optional(),
  13421. browserName: zod_1.default.string().optional(),
  13422. browserVersion: zod_1.default.string().optional(),
  13423. platformName: zod_1.default.string().optional(),
  13424. proxy: Session.ProxyConfigurationSchema.optional(),
  13425. webSocketUrl: zod_1.default.boolean().optional(),
  13426. })
  13427. .and(exports.ExtensibleSchema));
  13428. })(Session || (exports.Session = Session = {}));
  13429. (function (Session) {
  13430. Session.AutodetectProxyConfigurationSchema = zod_1.default.lazy(() => zod_1.default
  13431. .object({
  13432. proxyType: zod_1.default.literal('autodetect'),
  13433. })
  13434. .and(exports.ExtensibleSchema));
  13435. })(Session || (exports.Session = Session = {}));
  13436. (function (Session) {
  13437. Session.DirectProxyConfigurationSchema = zod_1.default.lazy(() => zod_1.default
  13438. .object({
  13439. proxyType: zod_1.default.literal('direct'),
  13440. })
  13441. .and(exports.ExtensibleSchema));
  13442. })(Session || (exports.Session = Session = {}));
  13443. (function (Session) {
  13444. Session.ManualProxyConfigurationSchema = zod_1.default.lazy(() => zod_1.default
  13445. .object({
  13446. proxyType: zod_1.default.literal('manual'),
  13447. ftpProxy: zod_1.default.string().optional(),
  13448. httpProxy: zod_1.default.string().optional(),
  13449. sslProxy: zod_1.default.string().optional(),
  13450. })
  13451. .and(Session.SocksProxyConfigurationSchema.or(zod_1.default.object({})))
  13452. .and(zod_1.default.object({
  13453. noProxy: zod_1.default.array(zod_1.default.string()).optional(),
  13454. }))
  13455. .and(exports.ExtensibleSchema));
  13456. })(Session || (exports.Session = Session = {}));
  13457. (function (Session) {
  13458. Session.SocksProxyConfigurationSchema = zod_1.default.lazy(() => zod_1.default.object({
  13459. socksProxy: zod_1.default.string(),
  13460. socksVersion: zod_1.default.number().int().nonnegative().gte(0).lte(255),
  13461. }));
  13462. })(Session || (exports.Session = Session = {}));
  13463. (function (Session) {
  13464. Session.PacProxyConfigurationSchema = zod_1.default.lazy(() => zod_1.default
  13465. .object({
  13466. proxyType: zod_1.default.literal('pac'),
  13467. proxyAutoconfigUrl: zod_1.default.string(),
  13468. })
  13469. .and(exports.ExtensibleSchema));
  13470. })(Session || (exports.Session = Session = {}));
  13471. (function (Session) {
  13472. Session.SystemProxyConfigurationSchema = zod_1.default.lazy(() => zod_1.default
  13473. .object({
  13474. proxyType: zod_1.default.literal('system'),
  13475. })
  13476. .and(exports.ExtensibleSchema));
  13477. })(Session || (exports.Session = Session = {}));
  13478. (function (Session) {
  13479. Session.SubscriptionRequestSchema = zod_1.default.lazy(() => zod_1.default.object({
  13480. events: zod_1.default.array(zod_1.default.string()).min(1),
  13481. contexts: zod_1.default
  13482. .array(BrowsingContext.BrowsingContextSchema)
  13483. .min(1)
  13484. .optional(),
  13485. }));
  13486. })(Session || (exports.Session = Session = {}));
  13487. (function (Session) {
  13488. Session.StatusSchema = zod_1.default.lazy(() => zod_1.default.object({
  13489. method: zod_1.default.literal('session.status'),
  13490. params: exports.EmptyParamsSchema,
  13491. }));
  13492. })(Session || (exports.Session = Session = {}));
  13493. (function (Session) {
  13494. Session.StatusResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13495. ready: zod_1.default.boolean(),
  13496. message: zod_1.default.string(),
  13497. }));
  13498. })(Session || (exports.Session = Session = {}));
  13499. (function (Session) {
  13500. Session.NewSchema = zod_1.default.lazy(() => zod_1.default.object({
  13501. method: zod_1.default.literal('session.new'),
  13502. params: Session.NewParametersSchema,
  13503. }));
  13504. })(Session || (exports.Session = Session = {}));
  13505. (function (Session) {
  13506. Session.NewParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13507. capabilities: Session.CapabilitiesRequestSchema,
  13508. }));
  13509. })(Session || (exports.Session = Session = {}));
  13510. (function (Session) {
  13511. Session.NewResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13512. sessionId: zod_1.default.string(),
  13513. capabilities: zod_1.default
  13514. .object({
  13515. acceptInsecureCerts: zod_1.default.boolean(),
  13516. browserName: zod_1.default.string(),
  13517. browserVersion: zod_1.default.string(),
  13518. platformName: zod_1.default.string(),
  13519. setWindowRect: zod_1.default.boolean(),
  13520. userAgent: zod_1.default.string(),
  13521. proxy: Session.ProxyConfigurationSchema.optional(),
  13522. webSocketUrl: zod_1.default.string().optional(),
  13523. })
  13524. .and(exports.ExtensibleSchema),
  13525. }));
  13526. })(Session || (exports.Session = Session = {}));
  13527. (function (Session) {
  13528. Session.EndSchema = zod_1.default.lazy(() => zod_1.default.object({
  13529. method: zod_1.default.literal('session.end'),
  13530. params: exports.EmptyParamsSchema,
  13531. }));
  13532. })(Session || (exports.Session = Session = {}));
  13533. (function (Session) {
  13534. Session.SubscribeSchema = zod_1.default.lazy(() => zod_1.default.object({
  13535. method: zod_1.default.literal('session.subscribe'),
  13536. params: Session.SubscriptionRequestSchema,
  13537. }));
  13538. })(Session || (exports.Session = Session = {}));
  13539. (function (Session) {
  13540. Session.UnsubscribeSchema = zod_1.default.lazy(() => zod_1.default.object({
  13541. method: zod_1.default.literal('session.unsubscribe'),
  13542. params: Session.SubscriptionRequestSchema,
  13543. }));
  13544. })(Session || (exports.Session = Session = {}));
  13545. exports.BrowserCommandSchema = zod_1.default.lazy(() => zod_1.default.union([
  13546. Browser.CloseSchema,
  13547. Browser.CreateUserContextSchema,
  13548. Browser.GetUserContextsSchema,
  13549. Browser.RemoveUserContextSchema,
  13550. ]));
  13551. exports.BrowserResultSchema = zod_1.default.lazy(() => zod_1.default.union([
  13552. Browser.CreateUserContextResultSchema,
  13553. Browser.GetUserContextsResultSchema,
  13554. ]));
  13555. var Browser;
  13556. (function (Browser) {
  13557. Browser.UserContextSchema = zod_1.default.lazy(() => zod_1.default.string());
  13558. })(Browser || (exports.Browser = Browser = {}));
  13559. (function (Browser) {
  13560. Browser.UserContextInfoSchema = zod_1.default.lazy(() => zod_1.default.object({
  13561. userContext: Browser.UserContextSchema,
  13562. }));
  13563. })(Browser || (exports.Browser = Browser = {}));
  13564. (function (Browser) {
  13565. Browser.CloseSchema = zod_1.default.lazy(() => zod_1.default.object({
  13566. method: zod_1.default.literal('browser.close'),
  13567. params: exports.EmptyParamsSchema,
  13568. }));
  13569. })(Browser || (exports.Browser = Browser = {}));
  13570. (function (Browser) {
  13571. Browser.CreateUserContextSchema = zod_1.default.lazy(() => zod_1.default.object({
  13572. method: zod_1.default.literal('browser.createUserContext'),
  13573. params: exports.EmptyParamsSchema,
  13574. }));
  13575. })(Browser || (exports.Browser = Browser = {}));
  13576. (function (Browser) {
  13577. Browser.CreateUserContextResultSchema = zod_1.default.lazy(() => Browser.UserContextInfoSchema);
  13578. })(Browser || (exports.Browser = Browser = {}));
  13579. (function (Browser) {
  13580. Browser.GetUserContextsSchema = zod_1.default.lazy(() => zod_1.default.object({
  13581. method: zod_1.default.literal('browser.getUserContexts'),
  13582. params: exports.EmptyParamsSchema,
  13583. }));
  13584. })(Browser || (exports.Browser = Browser = {}));
  13585. (function (Browser) {
  13586. Browser.GetUserContextsResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13587. userContexts: zod_1.default.array(Browser.UserContextInfoSchema).min(1),
  13588. }));
  13589. })(Browser || (exports.Browser = Browser = {}));
  13590. (function (Browser) {
  13591. Browser.RemoveUserContextSchema = zod_1.default.lazy(() => zod_1.default.object({
  13592. method: zod_1.default.literal('browser.removeUserContext'),
  13593. params: Browser.RemoveUserContextParametersSchema,
  13594. }));
  13595. })(Browser || (exports.Browser = Browser = {}));
  13596. (function (Browser) {
  13597. Browser.RemoveUserContextParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13598. userContext: Browser.UserContextSchema,
  13599. }));
  13600. })(Browser || (exports.Browser = Browser = {}));
  13601. exports.BrowsingContextCommandSchema = zod_1.default.lazy(() => zod_1.default.union([
  13602. BrowsingContext.ActivateSchema,
  13603. BrowsingContext.CaptureScreenshotSchema,
  13604. BrowsingContext.CloseSchema,
  13605. BrowsingContext.CreateSchema,
  13606. BrowsingContext.GetTreeSchema,
  13607. BrowsingContext.HandleUserPromptSchema,
  13608. BrowsingContext.LocateNodesSchema,
  13609. BrowsingContext.NavigateSchema,
  13610. BrowsingContext.PrintSchema,
  13611. BrowsingContext.ReloadSchema,
  13612. BrowsingContext.SetViewportSchema,
  13613. BrowsingContext.TraverseHistorySchema,
  13614. ]));
  13615. exports.BrowsingContextEventSchema = zod_1.default.lazy(() => zod_1.default.union([
  13616. BrowsingContext.ContextCreatedSchema,
  13617. BrowsingContext.ContextDestroyedSchema,
  13618. BrowsingContext.DomContentLoadedSchema,
  13619. BrowsingContext.DownloadWillBeginSchema,
  13620. BrowsingContext.FragmentNavigatedSchema,
  13621. BrowsingContext.LoadSchema,
  13622. BrowsingContext.NavigationAbortedSchema,
  13623. BrowsingContext.NavigationFailedSchema,
  13624. BrowsingContext.NavigationStartedSchema,
  13625. BrowsingContext.UserPromptClosedSchema,
  13626. BrowsingContext.UserPromptOpenedSchema,
  13627. ]));
  13628. exports.BrowsingContextResultSchema = zod_1.default.lazy(() => zod_1.default.union([
  13629. BrowsingContext.CaptureScreenshotResultSchema,
  13630. BrowsingContext.CreateResultSchema,
  13631. BrowsingContext.GetTreeResultSchema,
  13632. BrowsingContext.LocateNodesResultSchema,
  13633. BrowsingContext.NavigateResultSchema,
  13634. BrowsingContext.PrintResultSchema,
  13635. BrowsingContext.TraverseHistoryResultSchema,
  13636. ]));
  13637. var BrowsingContext;
  13638. (function (BrowsingContext) {
  13639. BrowsingContext.BrowsingContextSchema = zod_1.default.lazy(() => zod_1.default.string());
  13640. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13641. (function (BrowsingContext) {
  13642. BrowsingContext.InfoListSchema = zod_1.default.lazy(() => zod_1.default.array(BrowsingContext.InfoSchema));
  13643. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13644. (function (BrowsingContext) {
  13645. BrowsingContext.InfoSchema = zod_1.default.lazy(() => zod_1.default.object({
  13646. children: zod_1.default.union([BrowsingContext.InfoListSchema, zod_1.default.null()]),
  13647. context: BrowsingContext.BrowsingContextSchema,
  13648. url: zod_1.default.string(),
  13649. userContext: Browser.UserContextSchema,
  13650. parent: zod_1.default
  13651. .union([BrowsingContext.BrowsingContextSchema, zod_1.default.null()])
  13652. .optional(),
  13653. }));
  13654. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13655. (function (BrowsingContext) {
  13656. BrowsingContext.LocatorSchema = zod_1.default.lazy(() => zod_1.default.union([
  13657. BrowsingContext.CssLocatorSchema,
  13658. BrowsingContext.InnerTextLocatorSchema,
  13659. BrowsingContext.XPathLocatorSchema,
  13660. ]));
  13661. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13662. (function (BrowsingContext) {
  13663. BrowsingContext.CssLocatorSchema = zod_1.default.lazy(() => zod_1.default.object({
  13664. type: zod_1.default.literal('css'),
  13665. value: zod_1.default.string(),
  13666. }));
  13667. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13668. (function (BrowsingContext) {
  13669. BrowsingContext.InnerTextLocatorSchema = zod_1.default.lazy(() => zod_1.default.object({
  13670. type: zod_1.default.literal('innerText'),
  13671. value: zod_1.default.string(),
  13672. ignoreCase: zod_1.default.boolean().optional(),
  13673. matchType: zod_1.default.enum(['full', 'partial']).optional(),
  13674. maxDepth: exports.JsUintSchema.optional(),
  13675. }));
  13676. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13677. (function (BrowsingContext) {
  13678. BrowsingContext.XPathLocatorSchema = zod_1.default.lazy(() => zod_1.default.object({
  13679. type: zod_1.default.literal('xpath'),
  13680. value: zod_1.default.string(),
  13681. }));
  13682. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13683. (function (BrowsingContext) {
  13684. BrowsingContext.NavigationSchema = zod_1.default.lazy(() => zod_1.default.string());
  13685. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13686. (function (BrowsingContext) {
  13687. BrowsingContext.NavigationInfoSchema = zod_1.default.lazy(() => zod_1.default.object({
  13688. context: BrowsingContext.BrowsingContextSchema,
  13689. navigation: zod_1.default.union([BrowsingContext.NavigationSchema, zod_1.default.null()]),
  13690. timestamp: exports.JsUintSchema,
  13691. url: zod_1.default.string(),
  13692. }));
  13693. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13694. (function (BrowsingContext) {
  13695. BrowsingContext.ReadinessStateSchema = zod_1.default.lazy(() => zod_1.default.enum(['none', 'interactive', 'complete']));
  13696. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13697. (function (BrowsingContext) {
  13698. BrowsingContext.ActivateSchema = zod_1.default.lazy(() => zod_1.default.object({
  13699. method: zod_1.default.literal('browsingContext.activate'),
  13700. params: BrowsingContext.ActivateParametersSchema,
  13701. }));
  13702. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13703. (function (BrowsingContext) {
  13704. BrowsingContext.ActivateParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13705. context: BrowsingContext.BrowsingContextSchema,
  13706. }));
  13707. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13708. (function (BrowsingContext) {
  13709. BrowsingContext.CaptureScreenshotParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13710. context: BrowsingContext.BrowsingContextSchema,
  13711. origin: zod_1.default.enum(['viewport', 'document']).default('viewport').optional(),
  13712. format: BrowsingContext.ImageFormatSchema.optional(),
  13713. clip: BrowsingContext.ClipRectangleSchema.optional(),
  13714. }));
  13715. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13716. (function (BrowsingContext) {
  13717. BrowsingContext.CaptureScreenshotSchema = zod_1.default.lazy(() => zod_1.default.object({
  13718. method: zod_1.default.literal('browsingContext.captureScreenshot'),
  13719. params: BrowsingContext.CaptureScreenshotParametersSchema,
  13720. }));
  13721. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13722. (function (BrowsingContext) {
  13723. BrowsingContext.ImageFormatSchema = zod_1.default.lazy(() => zod_1.default.object({
  13724. type: zod_1.default.string(),
  13725. quality: zod_1.default.number().gte(0).lte(1).optional(),
  13726. }));
  13727. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13728. (function (BrowsingContext) {
  13729. BrowsingContext.ClipRectangleSchema = zod_1.default.lazy(() => zod_1.default.union([
  13730. BrowsingContext.BoxClipRectangleSchema,
  13731. BrowsingContext.ElementClipRectangleSchema,
  13732. ]));
  13733. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13734. (function (BrowsingContext) {
  13735. BrowsingContext.ElementClipRectangleSchema = zod_1.default.lazy(() => zod_1.default.object({
  13736. type: zod_1.default.literal('element'),
  13737. element: Script.SharedReferenceSchema,
  13738. }));
  13739. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13740. (function (BrowsingContext) {
  13741. BrowsingContext.BoxClipRectangleSchema = zod_1.default.lazy(() => zod_1.default.object({
  13742. type: zod_1.default.literal('box'),
  13743. x: zod_1.default.number(),
  13744. y: zod_1.default.number(),
  13745. width: zod_1.default.number(),
  13746. height: zod_1.default.number(),
  13747. }));
  13748. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13749. (function (BrowsingContext) {
  13750. BrowsingContext.CaptureScreenshotResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13751. data: zod_1.default.string(),
  13752. }));
  13753. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13754. (function (BrowsingContext) {
  13755. BrowsingContext.CloseSchema = zod_1.default.lazy(() => zod_1.default.object({
  13756. method: zod_1.default.literal('browsingContext.close'),
  13757. params: BrowsingContext.CloseParametersSchema,
  13758. }));
  13759. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13760. (function (BrowsingContext) {
  13761. BrowsingContext.CloseParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13762. context: BrowsingContext.BrowsingContextSchema,
  13763. promptUnload: zod_1.default.boolean().default(false).optional(),
  13764. }));
  13765. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13766. (function (BrowsingContext) {
  13767. BrowsingContext.CreateSchema = zod_1.default.lazy(() => zod_1.default.object({
  13768. method: zod_1.default.literal('browsingContext.create'),
  13769. params: BrowsingContext.CreateParametersSchema,
  13770. }));
  13771. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13772. (function (BrowsingContext) {
  13773. BrowsingContext.CreateTypeSchema = zod_1.default.lazy(() => zod_1.default.enum(['tab', 'window']));
  13774. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13775. (function (BrowsingContext) {
  13776. BrowsingContext.CreateParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13777. type: BrowsingContext.CreateTypeSchema,
  13778. referenceContext: BrowsingContext.BrowsingContextSchema.optional(),
  13779. background: zod_1.default.boolean().default(false).optional(),
  13780. userContext: Browser.UserContextSchema.optional(),
  13781. }));
  13782. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13783. (function (BrowsingContext) {
  13784. BrowsingContext.CreateResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13785. context: BrowsingContext.BrowsingContextSchema,
  13786. }));
  13787. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13788. (function (BrowsingContext) {
  13789. BrowsingContext.GetTreeSchema = zod_1.default.lazy(() => zod_1.default.object({
  13790. method: zod_1.default.literal('browsingContext.getTree'),
  13791. params: BrowsingContext.GetTreeParametersSchema,
  13792. }));
  13793. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13794. (function (BrowsingContext) {
  13795. BrowsingContext.GetTreeParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13796. maxDepth: exports.JsUintSchema.optional(),
  13797. root: BrowsingContext.BrowsingContextSchema.optional(),
  13798. }));
  13799. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13800. (function (BrowsingContext) {
  13801. BrowsingContext.GetTreeResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13802. contexts: BrowsingContext.InfoListSchema,
  13803. }));
  13804. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13805. (function (BrowsingContext) {
  13806. BrowsingContext.HandleUserPromptSchema = zod_1.default.lazy(() => zod_1.default.object({
  13807. method: zod_1.default.literal('browsingContext.handleUserPrompt'),
  13808. params: BrowsingContext.HandleUserPromptParametersSchema,
  13809. }));
  13810. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13811. (function (BrowsingContext) {
  13812. BrowsingContext.HandleUserPromptParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13813. context: BrowsingContext.BrowsingContextSchema,
  13814. accept: zod_1.default.boolean().optional(),
  13815. userText: zod_1.default.string().optional(),
  13816. }));
  13817. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13818. (function (BrowsingContext) {
  13819. BrowsingContext.LocateNodesParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13820. context: BrowsingContext.BrowsingContextSchema,
  13821. locator: BrowsingContext.LocatorSchema,
  13822. maxNodeCount: exports.JsUintSchema.gte(1).optional(),
  13823. serializationOptions: Script.SerializationOptionsSchema.optional(),
  13824. startNodes: zod_1.default.array(Script.SharedReferenceSchema).min(1).optional(),
  13825. }));
  13826. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13827. (function (BrowsingContext) {
  13828. BrowsingContext.LocateNodesSchema = zod_1.default.lazy(() => zod_1.default.object({
  13829. method: zod_1.default.literal('browsingContext.locateNodes'),
  13830. params: BrowsingContext.LocateNodesParametersSchema,
  13831. }));
  13832. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13833. (function (BrowsingContext) {
  13834. BrowsingContext.LocateNodesResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13835. nodes: zod_1.default.array(Script.NodeRemoteValueSchema),
  13836. }));
  13837. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13838. (function (BrowsingContext) {
  13839. BrowsingContext.NavigateSchema = zod_1.default.lazy(() => zod_1.default.object({
  13840. method: zod_1.default.literal('browsingContext.navigate'),
  13841. params: BrowsingContext.NavigateParametersSchema,
  13842. }));
  13843. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13844. (function (BrowsingContext) {
  13845. BrowsingContext.NavigateParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13846. context: BrowsingContext.BrowsingContextSchema,
  13847. url: zod_1.default.string(),
  13848. wait: BrowsingContext.ReadinessStateSchema.optional(),
  13849. }));
  13850. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13851. (function (BrowsingContext) {
  13852. BrowsingContext.NavigateResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13853. navigation: zod_1.default.union([BrowsingContext.NavigationSchema, zod_1.default.null()]),
  13854. url: zod_1.default.string(),
  13855. }));
  13856. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13857. (function (BrowsingContext) {
  13858. BrowsingContext.PrintSchema = zod_1.default.lazy(() => zod_1.default.object({
  13859. method: zod_1.default.literal('browsingContext.print'),
  13860. params: BrowsingContext.PrintParametersSchema,
  13861. }));
  13862. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13863. (function (BrowsingContext) {
  13864. BrowsingContext.PrintParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13865. context: BrowsingContext.BrowsingContextSchema,
  13866. background: zod_1.default.boolean().default(false).optional(),
  13867. margin: BrowsingContext.PrintMarginParametersSchema.optional(),
  13868. orientation: zod_1.default
  13869. .enum(['portrait', 'landscape'])
  13870. .default('portrait')
  13871. .optional(),
  13872. page: BrowsingContext.PrintPageParametersSchema.optional(),
  13873. pageRanges: zod_1.default.array(zod_1.default.union([exports.JsUintSchema, zod_1.default.string()])).optional(),
  13874. scale: zod_1.default.number().gte(0.1).lte(2).default(1).optional(),
  13875. shrinkToFit: zod_1.default.boolean().default(true).optional(),
  13876. }));
  13877. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13878. (function (BrowsingContext) {
  13879. BrowsingContext.PrintMarginParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13880. bottom: zod_1.default.number().gte(0).default(1).optional(),
  13881. left: zod_1.default.number().gte(0).default(1).optional(),
  13882. right: zod_1.default.number().gte(0).default(1).optional(),
  13883. top: zod_1.default.number().gte(0).default(1).optional(),
  13884. }));
  13885. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13886. (function (BrowsingContext) {
  13887. BrowsingContext.PrintPageParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13888. height: zod_1.default.number().gte(0.0352).default(27.94).optional(),
  13889. width: zod_1.default.number().gte(0.0352).default(21.59).optional(),
  13890. }));
  13891. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13892. (function (BrowsingContext) {
  13893. BrowsingContext.PrintResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  13894. data: zod_1.default.string(),
  13895. }));
  13896. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13897. (function (BrowsingContext) {
  13898. BrowsingContext.ReloadSchema = zod_1.default.lazy(() => zod_1.default.object({
  13899. method: zod_1.default.literal('browsingContext.reload'),
  13900. params: BrowsingContext.ReloadParametersSchema,
  13901. }));
  13902. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13903. (function (BrowsingContext) {
  13904. BrowsingContext.ReloadParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13905. context: BrowsingContext.BrowsingContextSchema,
  13906. ignoreCache: zod_1.default.boolean().optional(),
  13907. wait: BrowsingContext.ReadinessStateSchema.optional(),
  13908. }));
  13909. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13910. (function (BrowsingContext) {
  13911. BrowsingContext.SetViewportSchema = zod_1.default.lazy(() => zod_1.default.object({
  13912. method: zod_1.default.literal('browsingContext.setViewport'),
  13913. params: BrowsingContext.SetViewportParametersSchema,
  13914. }));
  13915. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13916. (function (BrowsingContext) {
  13917. BrowsingContext.SetViewportParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13918. context: BrowsingContext.BrowsingContextSchema,
  13919. viewport: zod_1.default.union([BrowsingContext.ViewportSchema, zod_1.default.null()]).optional(),
  13920. devicePixelRatio: zod_1.default.union([zod_1.default.number().gt(0), zod_1.default.null()]).optional(),
  13921. }));
  13922. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13923. (function (BrowsingContext) {
  13924. BrowsingContext.ViewportSchema = zod_1.default.lazy(() => zod_1.default.object({
  13925. width: exports.JsUintSchema,
  13926. height: exports.JsUintSchema,
  13927. }));
  13928. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13929. (function (BrowsingContext) {
  13930. BrowsingContext.TraverseHistorySchema = zod_1.default.lazy(() => zod_1.default.object({
  13931. method: zod_1.default.literal('browsingContext.traverseHistory'),
  13932. params: BrowsingContext.TraverseHistoryParametersSchema,
  13933. }));
  13934. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13935. (function (BrowsingContext) {
  13936. BrowsingContext.TraverseHistoryParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  13937. context: BrowsingContext.BrowsingContextSchema,
  13938. delta: exports.JsIntSchema,
  13939. }));
  13940. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13941. (function (BrowsingContext) {
  13942. BrowsingContext.TraverseHistoryResultSchema = zod_1.default.lazy(() => zod_1.default.object({}));
  13943. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13944. (function (BrowsingContext) {
  13945. BrowsingContext.ContextCreatedSchema = zod_1.default.lazy(() => zod_1.default.object({
  13946. method: zod_1.default.literal('browsingContext.contextCreated'),
  13947. params: BrowsingContext.InfoSchema,
  13948. }));
  13949. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13950. (function (BrowsingContext) {
  13951. BrowsingContext.ContextDestroyedSchema = zod_1.default.lazy(() => zod_1.default.object({
  13952. method: zod_1.default.literal('browsingContext.contextDestroyed'),
  13953. params: BrowsingContext.InfoSchema,
  13954. }));
  13955. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13956. (function (BrowsingContext) {
  13957. BrowsingContext.NavigationStartedSchema = zod_1.default.lazy(() => zod_1.default.object({
  13958. method: zod_1.default.literal('browsingContext.navigationStarted'),
  13959. params: BrowsingContext.NavigationInfoSchema,
  13960. }));
  13961. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13962. (function (BrowsingContext) {
  13963. BrowsingContext.FragmentNavigatedSchema = zod_1.default.lazy(() => zod_1.default.object({
  13964. method: zod_1.default.literal('browsingContext.fragmentNavigated'),
  13965. params: BrowsingContext.NavigationInfoSchema,
  13966. }));
  13967. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13968. (function (BrowsingContext) {
  13969. BrowsingContext.DomContentLoadedSchema = zod_1.default.lazy(() => zod_1.default.object({
  13970. method: zod_1.default.literal('browsingContext.domContentLoaded'),
  13971. params: BrowsingContext.NavigationInfoSchema,
  13972. }));
  13973. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13974. (function (BrowsingContext) {
  13975. BrowsingContext.LoadSchema = zod_1.default.lazy(() => zod_1.default.object({
  13976. method: zod_1.default.literal('browsingContext.load'),
  13977. params: BrowsingContext.NavigationInfoSchema,
  13978. }));
  13979. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13980. (function (BrowsingContext) {
  13981. BrowsingContext.DownloadWillBeginSchema = zod_1.default.lazy(() => zod_1.default.object({
  13982. method: zod_1.default.literal('browsingContext.downloadWillBegin'),
  13983. params: BrowsingContext.NavigationInfoSchema,
  13984. }));
  13985. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13986. (function (BrowsingContext) {
  13987. BrowsingContext.NavigationAbortedSchema = zod_1.default.lazy(() => zod_1.default.object({
  13988. method: zod_1.default.literal('browsingContext.navigationAborted'),
  13989. params: BrowsingContext.NavigationInfoSchema,
  13990. }));
  13991. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13992. (function (BrowsingContext) {
  13993. BrowsingContext.NavigationFailedSchema = zod_1.default.lazy(() => zod_1.default.object({
  13994. method: zod_1.default.literal('browsingContext.navigationFailed'),
  13995. params: BrowsingContext.NavigationInfoSchema,
  13996. }));
  13997. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  13998. (function (BrowsingContext) {
  13999. BrowsingContext.UserPromptClosedSchema = zod_1.default.lazy(() => zod_1.default.object({
  14000. method: zod_1.default.literal('browsingContext.userPromptClosed'),
  14001. params: BrowsingContext.UserPromptClosedParametersSchema,
  14002. }));
  14003. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  14004. (function (BrowsingContext) {
  14005. BrowsingContext.UserPromptClosedParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14006. context: BrowsingContext.BrowsingContextSchema,
  14007. accepted: zod_1.default.boolean(),
  14008. userText: zod_1.default.string().optional(),
  14009. }));
  14010. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  14011. (function (BrowsingContext) {
  14012. BrowsingContext.UserPromptOpenedSchema = zod_1.default.lazy(() => zod_1.default.object({
  14013. method: zod_1.default.literal('browsingContext.userPromptOpened'),
  14014. params: BrowsingContext.UserPromptOpenedParametersSchema,
  14015. }));
  14016. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  14017. (function (BrowsingContext) {
  14018. BrowsingContext.UserPromptOpenedParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14019. context: BrowsingContext.BrowsingContextSchema,
  14020. type: zod_1.default.enum(['alert', 'confirm', 'prompt', 'beforeunload']),
  14021. message: zod_1.default.string(),
  14022. defaultValue: zod_1.default.string().optional(),
  14023. }));
  14024. })(BrowsingContext || (exports.BrowsingContext = BrowsingContext = {}));
  14025. exports.NetworkCommandSchema = zod_1.default.lazy(() => zod_1.default.union([
  14026. Network.AddInterceptSchema,
  14027. Network.ContinueRequestSchema,
  14028. Network.ContinueResponseSchema,
  14029. Network.ContinueWithAuthSchema,
  14030. Network.FailRequestSchema,
  14031. Network.ProvideResponseSchema,
  14032. Network.RemoveInterceptSchema,
  14033. ]));
  14034. exports.NetworkEventSchema = zod_1.default.lazy(() => zod_1.default.union([
  14035. Network.AuthRequiredSchema,
  14036. Network.BeforeRequestSentSchema,
  14037. Network.FetchErrorSchema,
  14038. Network.ResponseCompletedSchema,
  14039. Network.ResponseStartedSchema,
  14040. ]));
  14041. exports.NetworkResultSchema = zod_1.default.lazy(() => Network.AddInterceptResultSchema);
  14042. var Network;
  14043. (function (Network) {
  14044. Network.AuthChallengeSchema = zod_1.default.lazy(() => zod_1.default.object({
  14045. scheme: zod_1.default.string(),
  14046. realm: zod_1.default.string(),
  14047. }));
  14048. })(Network || (exports.Network = Network = {}));
  14049. (function (Network) {
  14050. Network.AuthCredentialsSchema = zod_1.default.lazy(() => zod_1.default.object({
  14051. type: zod_1.default.literal('password'),
  14052. username: zod_1.default.string(),
  14053. password: zod_1.default.string(),
  14054. }));
  14055. })(Network || (exports.Network = Network = {}));
  14056. (function (Network) {
  14057. Network.BaseParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14058. context: zod_1.default.union([BrowsingContext.BrowsingContextSchema, zod_1.default.null()]),
  14059. isBlocked: zod_1.default.boolean(),
  14060. navigation: zod_1.default.union([BrowsingContext.NavigationSchema, zod_1.default.null()]),
  14061. redirectCount: exports.JsUintSchema,
  14062. request: Network.RequestDataSchema,
  14063. timestamp: exports.JsUintSchema,
  14064. intercepts: zod_1.default.array(Network.InterceptSchema).min(1).optional(),
  14065. }));
  14066. })(Network || (exports.Network = Network = {}));
  14067. (function (Network) {
  14068. Network.BytesValueSchema = zod_1.default.lazy(() => zod_1.default.union([Network.StringValueSchema, Network.Base64ValueSchema]));
  14069. })(Network || (exports.Network = Network = {}));
  14070. (function (Network) {
  14071. Network.StringValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14072. type: zod_1.default.literal('string'),
  14073. value: zod_1.default.string(),
  14074. }));
  14075. })(Network || (exports.Network = Network = {}));
  14076. (function (Network) {
  14077. Network.Base64ValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14078. type: zod_1.default.literal('base64'),
  14079. value: zod_1.default.string(),
  14080. }));
  14081. })(Network || (exports.Network = Network = {}));
  14082. (function (Network) {
  14083. Network.SameSiteSchema = zod_1.default.lazy(() => zod_1.default.enum(['strict', 'lax', 'none']));
  14084. })(Network || (exports.Network = Network = {}));
  14085. (function (Network) {
  14086. Network.CookieSchema = zod_1.default.lazy(() => zod_1.default
  14087. .object({
  14088. name: zod_1.default.string(),
  14089. value: Network.BytesValueSchema,
  14090. domain: zod_1.default.string(),
  14091. path: zod_1.default.string(),
  14092. size: exports.JsUintSchema,
  14093. httpOnly: zod_1.default.boolean(),
  14094. secure: zod_1.default.boolean(),
  14095. sameSite: Network.SameSiteSchema,
  14096. expiry: exports.JsUintSchema.optional(),
  14097. })
  14098. .and(exports.ExtensibleSchema));
  14099. })(Network || (exports.Network = Network = {}));
  14100. (function (Network) {
  14101. Network.CookieHeaderSchema = zod_1.default.lazy(() => zod_1.default.object({
  14102. name: zod_1.default.string(),
  14103. value: Network.BytesValueSchema,
  14104. }));
  14105. })(Network || (exports.Network = Network = {}));
  14106. (function (Network) {
  14107. Network.FetchTimingInfoSchema = zod_1.default.lazy(() => zod_1.default.object({
  14108. timeOrigin: zod_1.default.number(),
  14109. requestTime: zod_1.default.number(),
  14110. redirectStart: zod_1.default.number(),
  14111. redirectEnd: zod_1.default.number(),
  14112. fetchStart: zod_1.default.number(),
  14113. dnsStart: zod_1.default.number(),
  14114. dnsEnd: zod_1.default.number(),
  14115. connectStart: zod_1.default.number(),
  14116. connectEnd: zod_1.default.number(),
  14117. tlsStart: zod_1.default.number(),
  14118. requestStart: zod_1.default.number(),
  14119. responseStart: zod_1.default.number(),
  14120. responseEnd: zod_1.default.number(),
  14121. }));
  14122. })(Network || (exports.Network = Network = {}));
  14123. (function (Network) {
  14124. Network.HeaderSchema = zod_1.default.lazy(() => zod_1.default.object({
  14125. name: zod_1.default.string(),
  14126. value: Network.BytesValueSchema,
  14127. }));
  14128. })(Network || (exports.Network = Network = {}));
  14129. (function (Network) {
  14130. Network.InitiatorSchema = zod_1.default.lazy(() => zod_1.default.object({
  14131. type: zod_1.default.enum(['parser', 'script', 'preflight', 'other']),
  14132. columnNumber: exports.JsUintSchema.optional(),
  14133. lineNumber: exports.JsUintSchema.optional(),
  14134. stackTrace: Script.StackTraceSchema.optional(),
  14135. request: Network.RequestSchema.optional(),
  14136. }));
  14137. })(Network || (exports.Network = Network = {}));
  14138. (function (Network) {
  14139. Network.InterceptSchema = zod_1.default.lazy(() => zod_1.default.string());
  14140. })(Network || (exports.Network = Network = {}));
  14141. (function (Network) {
  14142. Network.RequestSchema = zod_1.default.lazy(() => zod_1.default.string());
  14143. })(Network || (exports.Network = Network = {}));
  14144. (function (Network) {
  14145. Network.RequestDataSchema = zod_1.default.lazy(() => zod_1.default.object({
  14146. request: Network.RequestSchema,
  14147. url: zod_1.default.string(),
  14148. method: zod_1.default.string(),
  14149. headers: zod_1.default.array(Network.HeaderSchema),
  14150. cookies: zod_1.default.array(Network.CookieSchema),
  14151. headersSize: exports.JsUintSchema,
  14152. bodySize: zod_1.default.union([exports.JsUintSchema, zod_1.default.null()]),
  14153. timings: Network.FetchTimingInfoSchema,
  14154. }));
  14155. })(Network || (exports.Network = Network = {}));
  14156. (function (Network) {
  14157. Network.ResponseContentSchema = zod_1.default.lazy(() => zod_1.default.object({
  14158. size: exports.JsUintSchema,
  14159. }));
  14160. })(Network || (exports.Network = Network = {}));
  14161. (function (Network) {
  14162. Network.ResponseDataSchema = zod_1.default.lazy(() => zod_1.default.object({
  14163. url: zod_1.default.string(),
  14164. protocol: zod_1.default.string(),
  14165. status: exports.JsUintSchema,
  14166. statusText: zod_1.default.string(),
  14167. fromCache: zod_1.default.boolean(),
  14168. headers: zod_1.default.array(Network.HeaderSchema),
  14169. mimeType: zod_1.default.string(),
  14170. bytesReceived: exports.JsUintSchema,
  14171. headersSize: zod_1.default.union([exports.JsUintSchema, zod_1.default.null()]),
  14172. bodySize: zod_1.default.union([exports.JsUintSchema, zod_1.default.null()]),
  14173. content: Network.ResponseContentSchema,
  14174. authChallenges: zod_1.default.array(Network.AuthChallengeSchema).optional(),
  14175. }));
  14176. })(Network || (exports.Network = Network = {}));
  14177. (function (Network) {
  14178. Network.SetCookieHeaderSchema = zod_1.default.lazy(() => zod_1.default.object({
  14179. name: zod_1.default.string(),
  14180. value: Network.BytesValueSchema,
  14181. domain: zod_1.default.string().optional(),
  14182. httpOnly: zod_1.default.boolean().optional(),
  14183. expiry: zod_1.default.string().optional(),
  14184. maxAge: exports.JsIntSchema.optional(),
  14185. path: zod_1.default.string().optional(),
  14186. sameSite: Network.SameSiteSchema.optional(),
  14187. secure: zod_1.default.boolean().optional(),
  14188. }));
  14189. })(Network || (exports.Network = Network = {}));
  14190. (function (Network) {
  14191. Network.UrlPatternSchema = zod_1.default.lazy(() => zod_1.default.union([Network.UrlPatternPatternSchema, Network.UrlPatternStringSchema]));
  14192. })(Network || (exports.Network = Network = {}));
  14193. (function (Network) {
  14194. Network.UrlPatternPatternSchema = zod_1.default.lazy(() => zod_1.default.object({
  14195. type: zod_1.default.literal('pattern'),
  14196. protocol: zod_1.default.string().optional(),
  14197. hostname: zod_1.default.string().optional(),
  14198. port: zod_1.default.string().optional(),
  14199. pathname: zod_1.default.string().optional(),
  14200. search: zod_1.default.string().optional(),
  14201. }));
  14202. })(Network || (exports.Network = Network = {}));
  14203. (function (Network) {
  14204. Network.UrlPatternStringSchema = zod_1.default.lazy(() => zod_1.default.object({
  14205. type: zod_1.default.literal('string'),
  14206. pattern: zod_1.default.string(),
  14207. }));
  14208. })(Network || (exports.Network = Network = {}));
  14209. (function (Network) {
  14210. Network.AddInterceptParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14211. phases: zod_1.default.array(Network.InterceptPhaseSchema).min(1),
  14212. contexts: zod_1.default
  14213. .array(BrowsingContext.BrowsingContextSchema)
  14214. .min(1)
  14215. .optional(),
  14216. urlPatterns: zod_1.default.array(Network.UrlPatternSchema).optional(),
  14217. }));
  14218. })(Network || (exports.Network = Network = {}));
  14219. (function (Network) {
  14220. Network.AddInterceptSchema = zod_1.default.lazy(() => zod_1.default.object({
  14221. method: zod_1.default.literal('network.addIntercept'),
  14222. params: Network.AddInterceptParametersSchema,
  14223. }));
  14224. })(Network || (exports.Network = Network = {}));
  14225. (function (Network) {
  14226. Network.InterceptPhaseSchema = zod_1.default.lazy(() => zod_1.default.enum(['beforeRequestSent', 'responseStarted', 'authRequired']));
  14227. })(Network || (exports.Network = Network = {}));
  14228. (function (Network) {
  14229. Network.AddInterceptResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  14230. intercept: Network.InterceptSchema,
  14231. }));
  14232. })(Network || (exports.Network = Network = {}));
  14233. (function (Network) {
  14234. Network.ContinueRequestSchema = zod_1.default.lazy(() => zod_1.default.object({
  14235. method: zod_1.default.literal('network.continueRequest'),
  14236. params: Network.ContinueRequestParametersSchema,
  14237. }));
  14238. })(Network || (exports.Network = Network = {}));
  14239. (function (Network) {
  14240. Network.ContinueRequestParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14241. request: Network.RequestSchema,
  14242. body: Network.BytesValueSchema.optional(),
  14243. cookies: zod_1.default.array(Network.CookieHeaderSchema).optional(),
  14244. headers: zod_1.default.array(Network.HeaderSchema).optional(),
  14245. method: zod_1.default.string().optional(),
  14246. url: zod_1.default.string().optional(),
  14247. }));
  14248. })(Network || (exports.Network = Network = {}));
  14249. (function (Network) {
  14250. Network.ContinueResponseSchema = zod_1.default.lazy(() => zod_1.default.object({
  14251. method: zod_1.default.literal('network.continueResponse'),
  14252. params: Network.ContinueResponseParametersSchema,
  14253. }));
  14254. })(Network || (exports.Network = Network = {}));
  14255. (function (Network) {
  14256. Network.ContinueResponseParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14257. request: Network.RequestSchema,
  14258. cookies: zod_1.default.array(Network.SetCookieHeaderSchema).optional(),
  14259. credentials: Network.AuthCredentialsSchema.optional(),
  14260. headers: zod_1.default.array(Network.HeaderSchema).optional(),
  14261. reasonPhrase: zod_1.default.string().optional(),
  14262. statusCode: exports.JsUintSchema.optional(),
  14263. }));
  14264. })(Network || (exports.Network = Network = {}));
  14265. (function (Network) {
  14266. Network.ContinueWithAuthSchema = zod_1.default.lazy(() => zod_1.default.object({
  14267. method: zod_1.default.literal('network.continueWithAuth'),
  14268. params: Network.ContinueWithAuthParametersSchema,
  14269. }));
  14270. })(Network || (exports.Network = Network = {}));
  14271. (function (Network) {
  14272. Network.ContinueWithAuthParametersSchema = zod_1.default.lazy(() => zod_1.default
  14273. .object({
  14274. request: Network.RequestSchema,
  14275. })
  14276. .and(zod_1.default.union([
  14277. Network.ContinueWithAuthCredentialsSchema,
  14278. Network.ContinueWithAuthNoCredentialsSchema,
  14279. ])));
  14280. })(Network || (exports.Network = Network = {}));
  14281. (function (Network) {
  14282. Network.ContinueWithAuthCredentialsSchema = zod_1.default.lazy(() => zod_1.default.object({
  14283. action: zod_1.default.literal('provideCredentials'),
  14284. credentials: Network.AuthCredentialsSchema,
  14285. }));
  14286. })(Network || (exports.Network = Network = {}));
  14287. (function (Network) {
  14288. Network.ContinueWithAuthNoCredentialsSchema = zod_1.default.lazy(() => zod_1.default.object({
  14289. action: zod_1.default.enum(['default', 'cancel']),
  14290. }));
  14291. })(Network || (exports.Network = Network = {}));
  14292. (function (Network) {
  14293. Network.FailRequestSchema = zod_1.default.lazy(() => zod_1.default.object({
  14294. method: zod_1.default.literal('network.failRequest'),
  14295. params: Network.FailRequestParametersSchema,
  14296. }));
  14297. })(Network || (exports.Network = Network = {}));
  14298. (function (Network) {
  14299. Network.FailRequestParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14300. request: Network.RequestSchema,
  14301. }));
  14302. })(Network || (exports.Network = Network = {}));
  14303. (function (Network) {
  14304. Network.ProvideResponseSchema = zod_1.default.lazy(() => zod_1.default.object({
  14305. method: zod_1.default.literal('network.provideResponse'),
  14306. params: Network.ProvideResponseParametersSchema,
  14307. }));
  14308. })(Network || (exports.Network = Network = {}));
  14309. (function (Network) {
  14310. Network.ProvideResponseParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14311. request: Network.RequestSchema,
  14312. body: Network.BytesValueSchema.optional(),
  14313. cookies: zod_1.default.array(Network.SetCookieHeaderSchema).optional(),
  14314. headers: zod_1.default.array(Network.HeaderSchema).optional(),
  14315. reasonPhrase: zod_1.default.string().optional(),
  14316. statusCode: exports.JsUintSchema.optional(),
  14317. }));
  14318. })(Network || (exports.Network = Network = {}));
  14319. (function (Network) {
  14320. Network.RemoveInterceptSchema = zod_1.default.lazy(() => zod_1.default.object({
  14321. method: zod_1.default.literal('network.removeIntercept'),
  14322. params: Network.RemoveInterceptParametersSchema,
  14323. }));
  14324. })(Network || (exports.Network = Network = {}));
  14325. (function (Network) {
  14326. Network.RemoveInterceptParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14327. intercept: Network.InterceptSchema,
  14328. }));
  14329. })(Network || (exports.Network = Network = {}));
  14330. exports.ScriptEventSchema = zod_1.default.lazy(() => zod_1.default.union([
  14331. Script.MessageSchema,
  14332. Script.RealmCreatedSchema,
  14333. Script.RealmDestroyedSchema,
  14334. ]));
  14335. (function (Network) {
  14336. Network.AuthRequiredParametersSchema = zod_1.default.lazy(() => Network.BaseParametersSchema.and(zod_1.default.object({
  14337. response: Network.ResponseDataSchema,
  14338. })));
  14339. })(Network || (exports.Network = Network = {}));
  14340. (function (Network) {
  14341. Network.BeforeRequestSentParametersSchema = zod_1.default.lazy(() => Network.BaseParametersSchema.and(zod_1.default.object({
  14342. initiator: Network.InitiatorSchema,
  14343. })));
  14344. })(Network || (exports.Network = Network = {}));
  14345. (function (Network) {
  14346. Network.FetchErrorParametersSchema = zod_1.default.lazy(() => Network.BaseParametersSchema.and(zod_1.default.object({
  14347. errorText: zod_1.default.string(),
  14348. })));
  14349. })(Network || (exports.Network = Network = {}));
  14350. (function (Network) {
  14351. Network.ResponseCompletedParametersSchema = zod_1.default.lazy(() => Network.BaseParametersSchema.and(zod_1.default.object({
  14352. response: Network.ResponseDataSchema,
  14353. })));
  14354. })(Network || (exports.Network = Network = {}));
  14355. (function (Network) {
  14356. Network.ResponseStartedParametersSchema = zod_1.default.lazy(() => Network.BaseParametersSchema.and(zod_1.default.object({
  14357. response: Network.ResponseDataSchema,
  14358. })));
  14359. })(Network || (exports.Network = Network = {}));
  14360. exports.ScriptCommandSchema = zod_1.default.lazy(() => zod_1.default.union([
  14361. Script.AddPreloadScriptSchema,
  14362. Script.CallFunctionSchema,
  14363. Script.DisownSchema,
  14364. Script.EvaluateSchema,
  14365. Script.GetRealmsSchema,
  14366. Script.RemovePreloadScriptSchema,
  14367. ]));
  14368. exports.ScriptResultSchema = zod_1.default.lazy(() => zod_1.default.union([
  14369. Script.AddPreloadScriptResultSchema,
  14370. Script.EvaluateResultSchema,
  14371. Script.GetRealmsResultSchema,
  14372. ]));
  14373. (function (Network) {
  14374. Network.AuthRequiredSchema = zod_1.default.lazy(() => zod_1.default.object({
  14375. method: zod_1.default.literal('network.authRequired'),
  14376. params: Network.AuthRequiredParametersSchema,
  14377. }));
  14378. })(Network || (exports.Network = Network = {}));
  14379. (function (Network) {
  14380. Network.BeforeRequestSentSchema = zod_1.default.lazy(() => zod_1.default.object({
  14381. method: zod_1.default.literal('network.beforeRequestSent'),
  14382. params: Network.BeforeRequestSentParametersSchema,
  14383. }));
  14384. })(Network || (exports.Network = Network = {}));
  14385. (function (Network) {
  14386. Network.FetchErrorSchema = zod_1.default.lazy(() => zod_1.default.object({
  14387. method: zod_1.default.literal('network.fetchError'),
  14388. params: Network.FetchErrorParametersSchema,
  14389. }));
  14390. })(Network || (exports.Network = Network = {}));
  14391. (function (Network) {
  14392. Network.ResponseCompletedSchema = zod_1.default.lazy(() => zod_1.default.object({
  14393. method: zod_1.default.literal('network.responseCompleted'),
  14394. params: Network.ResponseCompletedParametersSchema,
  14395. }));
  14396. })(Network || (exports.Network = Network = {}));
  14397. (function (Network) {
  14398. Network.ResponseStartedSchema = zod_1.default.lazy(() => zod_1.default.object({
  14399. method: zod_1.default.literal('network.responseStarted'),
  14400. params: Network.ResponseStartedParametersSchema,
  14401. }));
  14402. })(Network || (exports.Network = Network = {}));
  14403. var Script;
  14404. (function (Script) {
  14405. Script.ChannelSchema = zod_1.default.lazy(() => zod_1.default.string());
  14406. })(Script || (exports.Script = Script = {}));
  14407. (function (Script) {
  14408. Script.EvaluateResultSuccessSchema = zod_1.default.lazy(() => zod_1.default.object({
  14409. type: zod_1.default.literal('success'),
  14410. result: Script.RemoteValueSchema,
  14411. realm: Script.RealmSchema,
  14412. }));
  14413. })(Script || (exports.Script = Script = {}));
  14414. (function (Script) {
  14415. Script.ExceptionDetailsSchema = zod_1.default.lazy(() => zod_1.default.object({
  14416. columnNumber: exports.JsUintSchema,
  14417. exception: Script.RemoteValueSchema,
  14418. lineNumber: exports.JsUintSchema,
  14419. stackTrace: Script.StackTraceSchema,
  14420. text: zod_1.default.string(),
  14421. }));
  14422. })(Script || (exports.Script = Script = {}));
  14423. (function (Script) {
  14424. Script.ChannelValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14425. type: zod_1.default.literal('channel'),
  14426. value: Script.ChannelPropertiesSchema,
  14427. }));
  14428. })(Script || (exports.Script = Script = {}));
  14429. (function (Script) {
  14430. Script.ChannelPropertiesSchema = zod_1.default.lazy(() => zod_1.default.object({
  14431. channel: Script.ChannelSchema,
  14432. serializationOptions: Script.SerializationOptionsSchema.optional(),
  14433. ownership: Script.ResultOwnershipSchema.optional(),
  14434. }));
  14435. })(Script || (exports.Script = Script = {}));
  14436. (function (Script) {
  14437. Script.EvaluateResultSchema = zod_1.default.lazy(() => zod_1.default.union([
  14438. Script.EvaluateResultSuccessSchema,
  14439. Script.EvaluateResultExceptionSchema,
  14440. ]));
  14441. })(Script || (exports.Script = Script = {}));
  14442. (function (Script) {
  14443. Script.EvaluateResultExceptionSchema = zod_1.default.lazy(() => zod_1.default.object({
  14444. type: zod_1.default.literal('exception'),
  14445. exceptionDetails: Script.ExceptionDetailsSchema,
  14446. realm: Script.RealmSchema,
  14447. }));
  14448. })(Script || (exports.Script = Script = {}));
  14449. (function (Script) {
  14450. Script.HandleSchema = zod_1.default.lazy(() => zod_1.default.string());
  14451. })(Script || (exports.Script = Script = {}));
  14452. (function (Script) {
  14453. Script.InternalIdSchema = zod_1.default.lazy(() => zod_1.default.string());
  14454. })(Script || (exports.Script = Script = {}));
  14455. (function (Script) {
  14456. Script.ListLocalValueSchema = zod_1.default.lazy(() => zod_1.default.array(Script.LocalValueSchema));
  14457. })(Script || (exports.Script = Script = {}));
  14458. (function (Script) {
  14459. Script.LocalValueSchema = zod_1.default.lazy(() => zod_1.default.union([
  14460. Script.RemoteReferenceSchema,
  14461. Script.PrimitiveProtocolValueSchema,
  14462. Script.ChannelValueSchema,
  14463. Script.ArrayLocalValueSchema,
  14464. Script.DateLocalValueSchema,
  14465. Script.MapLocalValueSchema,
  14466. Script.ObjectLocalValueSchema,
  14467. Script.RegExpLocalValueSchema,
  14468. Script.SetLocalValueSchema,
  14469. ]));
  14470. })(Script || (exports.Script = Script = {}));
  14471. (function (Script) {
  14472. Script.ArrayLocalValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14473. type: zod_1.default.literal('array'),
  14474. value: Script.ListLocalValueSchema,
  14475. }));
  14476. })(Script || (exports.Script = Script = {}));
  14477. (function (Script) {
  14478. Script.DateLocalValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14479. type: zod_1.default.literal('date'),
  14480. value: zod_1.default.string(),
  14481. }));
  14482. })(Script || (exports.Script = Script = {}));
  14483. (function (Script) {
  14484. Script.MappingLocalValueSchema = zod_1.default.lazy(() => zod_1.default.array(zod_1.default.tuple([
  14485. zod_1.default.union([Script.LocalValueSchema, zod_1.default.string()]),
  14486. Script.LocalValueSchema,
  14487. ])));
  14488. })(Script || (exports.Script = Script = {}));
  14489. (function (Script) {
  14490. Script.MapLocalValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14491. type: zod_1.default.literal('map'),
  14492. value: Script.MappingLocalValueSchema,
  14493. }));
  14494. })(Script || (exports.Script = Script = {}));
  14495. (function (Script) {
  14496. Script.ObjectLocalValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14497. type: zod_1.default.literal('object'),
  14498. value: Script.MappingLocalValueSchema,
  14499. }));
  14500. })(Script || (exports.Script = Script = {}));
  14501. (function (Script) {
  14502. Script.RegExpValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14503. pattern: zod_1.default.string(),
  14504. flags: zod_1.default.string().optional(),
  14505. }));
  14506. })(Script || (exports.Script = Script = {}));
  14507. (function (Script) {
  14508. Script.RegExpLocalValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14509. type: zod_1.default.literal('regexp'),
  14510. value: Script.RegExpValueSchema,
  14511. }));
  14512. })(Script || (exports.Script = Script = {}));
  14513. (function (Script) {
  14514. Script.SetLocalValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14515. type: zod_1.default.literal('set'),
  14516. value: Script.ListLocalValueSchema,
  14517. }));
  14518. })(Script || (exports.Script = Script = {}));
  14519. (function (Script) {
  14520. Script.PreloadScriptSchema = zod_1.default.lazy(() => zod_1.default.string());
  14521. })(Script || (exports.Script = Script = {}));
  14522. (function (Script) {
  14523. Script.RealmSchema = zod_1.default.lazy(() => zod_1.default.string());
  14524. })(Script || (exports.Script = Script = {}));
  14525. (function (Script) {
  14526. Script.PrimitiveProtocolValueSchema = zod_1.default.lazy(() => zod_1.default.union([
  14527. Script.UndefinedValueSchema,
  14528. Script.NullValueSchema,
  14529. Script.StringValueSchema,
  14530. Script.NumberValueSchema,
  14531. Script.BooleanValueSchema,
  14532. Script.BigIntValueSchema,
  14533. ]));
  14534. })(Script || (exports.Script = Script = {}));
  14535. (function (Script) {
  14536. Script.UndefinedValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14537. type: zod_1.default.literal('undefined'),
  14538. }));
  14539. })(Script || (exports.Script = Script = {}));
  14540. (function (Script) {
  14541. Script.NullValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14542. type: zod_1.default.literal('null'),
  14543. }));
  14544. })(Script || (exports.Script = Script = {}));
  14545. (function (Script) {
  14546. Script.StringValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14547. type: zod_1.default.literal('string'),
  14548. value: zod_1.default.string(),
  14549. }));
  14550. })(Script || (exports.Script = Script = {}));
  14551. (function (Script) {
  14552. Script.SpecialNumberSchema = zod_1.default.lazy(() => zod_1.default.enum(['NaN', '-0', 'Infinity', '-Infinity']));
  14553. })(Script || (exports.Script = Script = {}));
  14554. (function (Script) {
  14555. Script.NumberValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14556. type: zod_1.default.literal('number'),
  14557. value: zod_1.default.union([zod_1.default.number(), Script.SpecialNumberSchema]),
  14558. }));
  14559. })(Script || (exports.Script = Script = {}));
  14560. (function (Script) {
  14561. Script.BooleanValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14562. type: zod_1.default.literal('boolean'),
  14563. value: zod_1.default.boolean(),
  14564. }));
  14565. })(Script || (exports.Script = Script = {}));
  14566. (function (Script) {
  14567. Script.BigIntValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14568. type: zod_1.default.literal('bigint'),
  14569. value: zod_1.default.string(),
  14570. }));
  14571. })(Script || (exports.Script = Script = {}));
  14572. (function (Script) {
  14573. Script.RealmInfoSchema = zod_1.default.lazy(() => zod_1.default.union([
  14574. Script.WindowRealmInfoSchema,
  14575. Script.DedicatedWorkerRealmInfoSchema,
  14576. Script.SharedWorkerRealmInfoSchema,
  14577. Script.ServiceWorkerRealmInfoSchema,
  14578. Script.WorkerRealmInfoSchema,
  14579. Script.PaintWorkletRealmInfoSchema,
  14580. Script.AudioWorkletRealmInfoSchema,
  14581. Script.WorkletRealmInfoSchema,
  14582. ]));
  14583. })(Script || (exports.Script = Script = {}));
  14584. (function (Script) {
  14585. Script.BaseRealmInfoSchema = zod_1.default.lazy(() => zod_1.default.object({
  14586. realm: Script.RealmSchema,
  14587. origin: zod_1.default.string(),
  14588. }));
  14589. })(Script || (exports.Script = Script = {}));
  14590. (function (Script) {
  14591. Script.WindowRealmInfoSchema = zod_1.default.lazy(() => Script.BaseRealmInfoSchema.and(zod_1.default.object({
  14592. type: zod_1.default.literal('window'),
  14593. context: BrowsingContext.BrowsingContextSchema,
  14594. sandbox: zod_1.default.string().optional(),
  14595. })));
  14596. })(Script || (exports.Script = Script = {}));
  14597. (function (Script) {
  14598. Script.DedicatedWorkerRealmInfoSchema = zod_1.default.lazy(() => Script.BaseRealmInfoSchema.and(zod_1.default.object({
  14599. type: zod_1.default.literal('dedicated-worker'),
  14600. owners: zod_1.default.tuple([Script.RealmSchema]),
  14601. })));
  14602. })(Script || (exports.Script = Script = {}));
  14603. (function (Script) {
  14604. Script.SharedWorkerRealmInfoSchema = zod_1.default.lazy(() => Script.BaseRealmInfoSchema.and(zod_1.default.object({
  14605. type: zod_1.default.literal('shared-worker'),
  14606. })));
  14607. })(Script || (exports.Script = Script = {}));
  14608. (function (Script) {
  14609. Script.ServiceWorkerRealmInfoSchema = zod_1.default.lazy(() => Script.BaseRealmInfoSchema.and(zod_1.default.object({
  14610. type: zod_1.default.literal('service-worker'),
  14611. })));
  14612. })(Script || (exports.Script = Script = {}));
  14613. (function (Script) {
  14614. Script.WorkerRealmInfoSchema = zod_1.default.lazy(() => Script.BaseRealmInfoSchema.and(zod_1.default.object({
  14615. type: zod_1.default.literal('worker'),
  14616. })));
  14617. })(Script || (exports.Script = Script = {}));
  14618. (function (Script) {
  14619. Script.PaintWorkletRealmInfoSchema = zod_1.default.lazy(() => Script.BaseRealmInfoSchema.and(zod_1.default.object({
  14620. type: zod_1.default.literal('paint-worklet'),
  14621. })));
  14622. })(Script || (exports.Script = Script = {}));
  14623. (function (Script) {
  14624. Script.AudioWorkletRealmInfoSchema = zod_1.default.lazy(() => Script.BaseRealmInfoSchema.and(zod_1.default.object({
  14625. type: zod_1.default.literal('audio-worklet'),
  14626. })));
  14627. })(Script || (exports.Script = Script = {}));
  14628. (function (Script) {
  14629. Script.WorkletRealmInfoSchema = zod_1.default.lazy(() => Script.BaseRealmInfoSchema.and(zod_1.default.object({
  14630. type: zod_1.default.literal('worklet'),
  14631. })));
  14632. })(Script || (exports.Script = Script = {}));
  14633. (function (Script) {
  14634. Script.RealmTypeSchema = zod_1.default.lazy(() => zod_1.default.enum([
  14635. 'window',
  14636. 'dedicated-worker',
  14637. 'shared-worker',
  14638. 'service-worker',
  14639. 'worker',
  14640. 'paint-worklet',
  14641. 'audio-worklet',
  14642. 'worklet',
  14643. ]));
  14644. })(Script || (exports.Script = Script = {}));
  14645. (function (Script) {
  14646. Script.ListRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.array(Script.RemoteValueSchema));
  14647. })(Script || (exports.Script = Script = {}));
  14648. (function (Script) {
  14649. Script.MappingRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.array(zod_1.default.tuple([
  14650. zod_1.default.union([Script.RemoteValueSchema, zod_1.default.string()]),
  14651. Script.RemoteValueSchema,
  14652. ])));
  14653. })(Script || (exports.Script = Script = {}));
  14654. (function (Script) {
  14655. Script.RemoteValueSchema = zod_1.default.lazy(() => zod_1.default.union([
  14656. Script.PrimitiveProtocolValueSchema,
  14657. Script.SymbolRemoteValueSchema,
  14658. Script.ArrayRemoteValueSchema,
  14659. Script.ObjectRemoteValueSchema,
  14660. Script.FunctionRemoteValueSchema,
  14661. Script.RegExpRemoteValueSchema,
  14662. Script.DateRemoteValueSchema,
  14663. Script.MapRemoteValueSchema,
  14664. Script.SetRemoteValueSchema,
  14665. Script.WeakMapRemoteValueSchema,
  14666. Script.WeakSetRemoteValueSchema,
  14667. Script.GeneratorRemoteValueSchema,
  14668. Script.ErrorRemoteValueSchema,
  14669. Script.ProxyRemoteValueSchema,
  14670. Script.PromiseRemoteValueSchema,
  14671. Script.TypedArrayRemoteValueSchema,
  14672. Script.ArrayBufferRemoteValueSchema,
  14673. Script.NodeListRemoteValueSchema,
  14674. Script.HtmlCollectionRemoteValueSchema,
  14675. Script.NodeRemoteValueSchema,
  14676. Script.WindowProxyRemoteValueSchema,
  14677. ]));
  14678. })(Script || (exports.Script = Script = {}));
  14679. (function (Script) {
  14680. Script.RemoteReferenceSchema = zod_1.default.lazy(() => zod_1.default.union([Script.SharedReferenceSchema, Script.RemoteObjectReferenceSchema]));
  14681. })(Script || (exports.Script = Script = {}));
  14682. (function (Script) {
  14683. Script.SharedReferenceSchema = zod_1.default.lazy(() => zod_1.default
  14684. .object({
  14685. sharedId: Script.SharedIdSchema,
  14686. handle: Script.HandleSchema.optional(),
  14687. })
  14688. .and(exports.ExtensibleSchema));
  14689. })(Script || (exports.Script = Script = {}));
  14690. (function (Script) {
  14691. Script.RemoteObjectReferenceSchema = zod_1.default.lazy(() => zod_1.default
  14692. .object({
  14693. handle: Script.HandleSchema,
  14694. sharedId: Script.SharedIdSchema.optional(),
  14695. })
  14696. .and(exports.ExtensibleSchema));
  14697. })(Script || (exports.Script = Script = {}));
  14698. (function (Script) {
  14699. Script.SymbolRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14700. type: zod_1.default.literal('symbol'),
  14701. handle: Script.HandleSchema.optional(),
  14702. internalId: Script.InternalIdSchema.optional(),
  14703. }));
  14704. })(Script || (exports.Script = Script = {}));
  14705. (function (Script) {
  14706. Script.ArrayRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14707. type: zod_1.default.literal('array'),
  14708. handle: Script.HandleSchema.optional(),
  14709. internalId: Script.InternalIdSchema.optional(),
  14710. value: Script.ListRemoteValueSchema.optional(),
  14711. }));
  14712. })(Script || (exports.Script = Script = {}));
  14713. (function (Script) {
  14714. Script.ObjectRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14715. type: zod_1.default.literal('object'),
  14716. handle: Script.HandleSchema.optional(),
  14717. internalId: Script.InternalIdSchema.optional(),
  14718. value: Script.MappingRemoteValueSchema.optional(),
  14719. }));
  14720. })(Script || (exports.Script = Script = {}));
  14721. (function (Script) {
  14722. Script.FunctionRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14723. type: zod_1.default.literal('function'),
  14724. handle: Script.HandleSchema.optional(),
  14725. internalId: Script.InternalIdSchema.optional(),
  14726. }));
  14727. })(Script || (exports.Script = Script = {}));
  14728. (function (Script) {
  14729. Script.RegExpRemoteValueSchema = zod_1.default.lazy(() => zod_1.default
  14730. .object({
  14731. handle: Script.HandleSchema.optional(),
  14732. internalId: Script.InternalIdSchema.optional(),
  14733. })
  14734. .and(Script.RegExpLocalValueSchema));
  14735. })(Script || (exports.Script = Script = {}));
  14736. (function (Script) {
  14737. Script.DateRemoteValueSchema = zod_1.default.lazy(() => zod_1.default
  14738. .object({
  14739. handle: Script.HandleSchema.optional(),
  14740. internalId: Script.InternalIdSchema.optional(),
  14741. })
  14742. .and(Script.DateLocalValueSchema));
  14743. })(Script || (exports.Script = Script = {}));
  14744. (function (Script) {
  14745. Script.MapRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14746. type: zod_1.default.literal('map'),
  14747. handle: Script.HandleSchema.optional(),
  14748. internalId: Script.InternalIdSchema.optional(),
  14749. value: Script.MappingRemoteValueSchema.optional(),
  14750. }));
  14751. })(Script || (exports.Script = Script = {}));
  14752. (function (Script) {
  14753. Script.SetRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14754. type: zod_1.default.literal('set'),
  14755. handle: Script.HandleSchema.optional(),
  14756. internalId: Script.InternalIdSchema.optional(),
  14757. value: Script.ListRemoteValueSchema.optional(),
  14758. }));
  14759. })(Script || (exports.Script = Script = {}));
  14760. (function (Script) {
  14761. Script.WeakMapRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14762. type: zod_1.default.literal('weakmap'),
  14763. handle: Script.HandleSchema.optional(),
  14764. internalId: Script.InternalIdSchema.optional(),
  14765. }));
  14766. })(Script || (exports.Script = Script = {}));
  14767. (function (Script) {
  14768. Script.WeakSetRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14769. type: zod_1.default.literal('weakset'),
  14770. handle: Script.HandleSchema.optional(),
  14771. internalId: Script.InternalIdSchema.optional(),
  14772. }));
  14773. })(Script || (exports.Script = Script = {}));
  14774. (function (Script) {
  14775. Script.GeneratorRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14776. type: zod_1.default.literal('generator'),
  14777. handle: Script.HandleSchema.optional(),
  14778. internalId: Script.InternalIdSchema.optional(),
  14779. }));
  14780. })(Script || (exports.Script = Script = {}));
  14781. (function (Script) {
  14782. Script.ErrorRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14783. type: zod_1.default.literal('error'),
  14784. handle: Script.HandleSchema.optional(),
  14785. internalId: Script.InternalIdSchema.optional(),
  14786. }));
  14787. })(Script || (exports.Script = Script = {}));
  14788. (function (Script) {
  14789. Script.ProxyRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14790. type: zod_1.default.literal('proxy'),
  14791. handle: Script.HandleSchema.optional(),
  14792. internalId: Script.InternalIdSchema.optional(),
  14793. }));
  14794. })(Script || (exports.Script = Script = {}));
  14795. (function (Script) {
  14796. Script.PromiseRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14797. type: zod_1.default.literal('promise'),
  14798. handle: Script.HandleSchema.optional(),
  14799. internalId: Script.InternalIdSchema.optional(),
  14800. }));
  14801. })(Script || (exports.Script = Script = {}));
  14802. (function (Script) {
  14803. Script.TypedArrayRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14804. type: zod_1.default.literal('typedarray'),
  14805. handle: Script.HandleSchema.optional(),
  14806. internalId: Script.InternalIdSchema.optional(),
  14807. }));
  14808. })(Script || (exports.Script = Script = {}));
  14809. (function (Script) {
  14810. Script.ArrayBufferRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14811. type: zod_1.default.literal('arraybuffer'),
  14812. handle: Script.HandleSchema.optional(),
  14813. internalId: Script.InternalIdSchema.optional(),
  14814. }));
  14815. })(Script || (exports.Script = Script = {}));
  14816. (function (Script) {
  14817. Script.NodeListRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14818. type: zod_1.default.literal('nodelist'),
  14819. handle: Script.HandleSchema.optional(),
  14820. internalId: Script.InternalIdSchema.optional(),
  14821. value: Script.ListRemoteValueSchema.optional(),
  14822. }));
  14823. })(Script || (exports.Script = Script = {}));
  14824. (function (Script) {
  14825. Script.HtmlCollectionRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14826. type: zod_1.default.literal('htmlcollection'),
  14827. handle: Script.HandleSchema.optional(),
  14828. internalId: Script.InternalIdSchema.optional(),
  14829. value: Script.ListRemoteValueSchema.optional(),
  14830. }));
  14831. })(Script || (exports.Script = Script = {}));
  14832. (function (Script) {
  14833. Script.NodeRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14834. type: zod_1.default.literal('node'),
  14835. sharedId: Script.SharedIdSchema.optional(),
  14836. handle: Script.HandleSchema.optional(),
  14837. internalId: Script.InternalIdSchema.optional(),
  14838. value: Script.NodePropertiesSchema.optional(),
  14839. }));
  14840. })(Script || (exports.Script = Script = {}));
  14841. (function (Script) {
  14842. Script.NodePropertiesSchema = zod_1.default.lazy(() => zod_1.default.object({
  14843. nodeType: exports.JsUintSchema,
  14844. childNodeCount: exports.JsUintSchema,
  14845. attributes: zod_1.default.record(zod_1.default.string(), zod_1.default.string()).optional(),
  14846. children: zod_1.default.array(Script.NodeRemoteValueSchema).optional(),
  14847. localName: zod_1.default.string().optional(),
  14848. mode: zod_1.default.enum(['open', 'closed']).optional(),
  14849. namespaceURI: zod_1.default.string().optional(),
  14850. nodeValue: zod_1.default.string().optional(),
  14851. shadowRoot: zod_1.default.union([Script.NodeRemoteValueSchema, zod_1.default.null()]).optional(),
  14852. }));
  14853. })(Script || (exports.Script = Script = {}));
  14854. (function (Script) {
  14855. Script.WindowProxyRemoteValueSchema = zod_1.default.lazy(() => zod_1.default.object({
  14856. type: zod_1.default.literal('window'),
  14857. value: Script.WindowProxyPropertiesSchema,
  14858. handle: Script.HandleSchema.optional(),
  14859. internalId: Script.InternalIdSchema.optional(),
  14860. }));
  14861. })(Script || (exports.Script = Script = {}));
  14862. (function (Script) {
  14863. Script.WindowProxyPropertiesSchema = zod_1.default.lazy(() => zod_1.default.object({
  14864. context: BrowsingContext.BrowsingContextSchema,
  14865. }));
  14866. })(Script || (exports.Script = Script = {}));
  14867. (function (Script) {
  14868. Script.ResultOwnershipSchema = zod_1.default.lazy(() => zod_1.default.enum(['root', 'none']));
  14869. })(Script || (exports.Script = Script = {}));
  14870. (function (Script) {
  14871. Script.SerializationOptionsSchema = zod_1.default.lazy(() => zod_1.default.object({
  14872. maxDomDepth: zod_1.default.union([exports.JsUintSchema, zod_1.default.null()]).default(0).optional(),
  14873. maxObjectDepth: zod_1.default
  14874. .union([exports.JsUintSchema, zod_1.default.null()])
  14875. .default(null)
  14876. .optional(),
  14877. includeShadowTree: zod_1.default
  14878. .enum(['none', 'open', 'all'])
  14879. .default('none')
  14880. .optional(),
  14881. }));
  14882. })(Script || (exports.Script = Script = {}));
  14883. (function (Script) {
  14884. Script.SharedIdSchema = zod_1.default.lazy(() => zod_1.default.string());
  14885. })(Script || (exports.Script = Script = {}));
  14886. (function (Script) {
  14887. Script.StackFrameSchema = zod_1.default.lazy(() => zod_1.default.object({
  14888. columnNumber: exports.JsUintSchema,
  14889. functionName: zod_1.default.string(),
  14890. lineNumber: exports.JsUintSchema,
  14891. url: zod_1.default.string(),
  14892. }));
  14893. })(Script || (exports.Script = Script = {}));
  14894. (function (Script) {
  14895. Script.StackTraceSchema = zod_1.default.lazy(() => zod_1.default.object({
  14896. callFrames: zod_1.default.array(Script.StackFrameSchema),
  14897. }));
  14898. })(Script || (exports.Script = Script = {}));
  14899. (function (Script) {
  14900. Script.SourceSchema = zod_1.default.lazy(() => zod_1.default.object({
  14901. realm: Script.RealmSchema,
  14902. context: BrowsingContext.BrowsingContextSchema.optional(),
  14903. }));
  14904. })(Script || (exports.Script = Script = {}));
  14905. (function (Script) {
  14906. Script.RealmTargetSchema = zod_1.default.lazy(() => zod_1.default.object({
  14907. realm: Script.RealmSchema,
  14908. }));
  14909. })(Script || (exports.Script = Script = {}));
  14910. (function (Script) {
  14911. Script.ContextTargetSchema = zod_1.default.lazy(() => zod_1.default.object({
  14912. context: BrowsingContext.BrowsingContextSchema,
  14913. sandbox: zod_1.default.string().optional(),
  14914. }));
  14915. })(Script || (exports.Script = Script = {}));
  14916. (function (Script) {
  14917. Script.TargetSchema = zod_1.default.lazy(() => zod_1.default.union([Script.ContextTargetSchema, Script.RealmTargetSchema]));
  14918. })(Script || (exports.Script = Script = {}));
  14919. (function (Script) {
  14920. Script.AddPreloadScriptSchema = zod_1.default.lazy(() => zod_1.default.object({
  14921. method: zod_1.default.literal('script.addPreloadScript'),
  14922. params: Script.AddPreloadScriptParametersSchema,
  14923. }));
  14924. })(Script || (exports.Script = Script = {}));
  14925. (function (Script) {
  14926. Script.AddPreloadScriptParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14927. functionDeclaration: zod_1.default.string(),
  14928. arguments: zod_1.default.array(Script.ChannelValueSchema).optional(),
  14929. contexts: zod_1.default
  14930. .array(BrowsingContext.BrowsingContextSchema)
  14931. .min(1)
  14932. .optional(),
  14933. sandbox: zod_1.default.string().optional(),
  14934. }));
  14935. })(Script || (exports.Script = Script = {}));
  14936. (function (Script) {
  14937. Script.AddPreloadScriptResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  14938. script: Script.PreloadScriptSchema,
  14939. }));
  14940. })(Script || (exports.Script = Script = {}));
  14941. (function (Script) {
  14942. Script.DisownSchema = zod_1.default.lazy(() => zod_1.default.object({
  14943. method: zod_1.default.literal('script.disown'),
  14944. params: Script.DisownParametersSchema,
  14945. }));
  14946. })(Script || (exports.Script = Script = {}));
  14947. (function (Script) {
  14948. Script.DisownParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14949. handles: zod_1.default.array(Script.HandleSchema),
  14950. target: Script.TargetSchema,
  14951. }));
  14952. })(Script || (exports.Script = Script = {}));
  14953. (function (Script) {
  14954. Script.CallFunctionParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14955. functionDeclaration: zod_1.default.string(),
  14956. awaitPromise: zod_1.default.boolean(),
  14957. target: Script.TargetSchema,
  14958. arguments: zod_1.default.array(Script.LocalValueSchema).optional(),
  14959. resultOwnership: Script.ResultOwnershipSchema.optional(),
  14960. serializationOptions: Script.SerializationOptionsSchema.optional(),
  14961. this: Script.LocalValueSchema.optional(),
  14962. userActivation: zod_1.default.boolean().default(false).optional(),
  14963. }));
  14964. })(Script || (exports.Script = Script = {}));
  14965. (function (Script) {
  14966. Script.CallFunctionSchema = zod_1.default.lazy(() => zod_1.default.object({
  14967. method: zod_1.default.literal('script.callFunction'),
  14968. params: Script.CallFunctionParametersSchema,
  14969. }));
  14970. })(Script || (exports.Script = Script = {}));
  14971. (function (Script) {
  14972. Script.EvaluateSchema = zod_1.default.lazy(() => zod_1.default.object({
  14973. method: zod_1.default.literal('script.evaluate'),
  14974. params: Script.EvaluateParametersSchema,
  14975. }));
  14976. })(Script || (exports.Script = Script = {}));
  14977. (function (Script) {
  14978. Script.EvaluateParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14979. expression: zod_1.default.string(),
  14980. target: Script.TargetSchema,
  14981. awaitPromise: zod_1.default.boolean(),
  14982. resultOwnership: Script.ResultOwnershipSchema.optional(),
  14983. serializationOptions: Script.SerializationOptionsSchema.optional(),
  14984. userActivation: zod_1.default.boolean().default(false).optional(),
  14985. }));
  14986. })(Script || (exports.Script = Script = {}));
  14987. (function (Script) {
  14988. Script.GetRealmsSchema = zod_1.default.lazy(() => zod_1.default.object({
  14989. method: zod_1.default.literal('script.getRealms'),
  14990. params: Script.GetRealmsParametersSchema,
  14991. }));
  14992. })(Script || (exports.Script = Script = {}));
  14993. (function (Script) {
  14994. Script.GetRealmsParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  14995. context: BrowsingContext.BrowsingContextSchema.optional(),
  14996. type: Script.RealmTypeSchema.optional(),
  14997. }));
  14998. })(Script || (exports.Script = Script = {}));
  14999. (function (Script) {
  15000. Script.GetRealmsResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  15001. realms: zod_1.default.array(Script.RealmInfoSchema),
  15002. }));
  15003. })(Script || (exports.Script = Script = {}));
  15004. (function (Script) {
  15005. Script.RemovePreloadScriptSchema = zod_1.default.lazy(() => zod_1.default.object({
  15006. method: zod_1.default.literal('script.removePreloadScript'),
  15007. params: Script.RemovePreloadScriptParametersSchema,
  15008. }));
  15009. })(Script || (exports.Script = Script = {}));
  15010. (function (Script) {
  15011. Script.RemovePreloadScriptParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15012. script: Script.PreloadScriptSchema,
  15013. }));
  15014. })(Script || (exports.Script = Script = {}));
  15015. (function (Script) {
  15016. Script.MessageParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15017. channel: Script.ChannelSchema,
  15018. data: Script.RemoteValueSchema,
  15019. source: Script.SourceSchema,
  15020. }));
  15021. })(Script || (exports.Script = Script = {}));
  15022. (function (Script) {
  15023. Script.RealmCreatedSchema = zod_1.default.lazy(() => zod_1.default.object({
  15024. method: zod_1.default.literal('script.realmCreated'),
  15025. params: Script.RealmInfoSchema,
  15026. }));
  15027. })(Script || (exports.Script = Script = {}));
  15028. (function (Script) {
  15029. Script.MessageSchema = zod_1.default.lazy(() => zod_1.default.object({
  15030. method: zod_1.default.literal('script.message'),
  15031. params: Script.MessageParametersSchema,
  15032. }));
  15033. })(Script || (exports.Script = Script = {}));
  15034. (function (Script) {
  15035. Script.RealmDestroyedSchema = zod_1.default.lazy(() => zod_1.default.object({
  15036. method: zod_1.default.literal('script.realmDestroyed'),
  15037. params: Script.RealmDestroyedParametersSchema,
  15038. }));
  15039. })(Script || (exports.Script = Script = {}));
  15040. (function (Script) {
  15041. Script.RealmDestroyedParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15042. realm: Script.RealmSchema,
  15043. }));
  15044. })(Script || (exports.Script = Script = {}));
  15045. exports.StorageCommandSchema = zod_1.default.lazy(() => zod_1.default.union([
  15046. Storage.DeleteCookiesSchema,
  15047. Storage.GetCookiesSchema,
  15048. Storage.SetCookieSchema,
  15049. ]));
  15050. exports.StorageResultSchema = zod_1.default.lazy(() => zod_1.default.union([
  15051. Storage.DeleteCookiesResultSchema,
  15052. Storage.GetCookiesResultSchema,
  15053. Storage.SetCookieResultSchema,
  15054. ]));
  15055. var Storage;
  15056. (function (Storage) {
  15057. Storage.PartitionKeySchema = zod_1.default.lazy(() => zod_1.default
  15058. .object({
  15059. userContext: zod_1.default.string().optional(),
  15060. sourceOrigin: zod_1.default.string().optional(),
  15061. })
  15062. .and(exports.ExtensibleSchema));
  15063. })(Storage || (exports.Storage = Storage = {}));
  15064. (function (Storage) {
  15065. Storage.GetCookiesSchema = zod_1.default.lazy(() => zod_1.default.object({
  15066. method: zod_1.default.literal('storage.getCookies'),
  15067. params: Storage.GetCookiesParametersSchema,
  15068. }));
  15069. })(Storage || (exports.Storage = Storage = {}));
  15070. (function (Storage) {
  15071. Storage.CookieFilterSchema = zod_1.default.lazy(() => zod_1.default
  15072. .object({
  15073. name: zod_1.default.string().optional(),
  15074. value: Network.BytesValueSchema.optional(),
  15075. domain: zod_1.default.string().optional(),
  15076. path: zod_1.default.string().optional(),
  15077. size: exports.JsUintSchema.optional(),
  15078. httpOnly: zod_1.default.boolean().optional(),
  15079. secure: zod_1.default.boolean().optional(),
  15080. sameSite: Network.SameSiteSchema.optional(),
  15081. expiry: exports.JsUintSchema.optional(),
  15082. })
  15083. .and(exports.ExtensibleSchema));
  15084. })(Storage || (exports.Storage = Storage = {}));
  15085. (function (Storage) {
  15086. Storage.BrowsingContextPartitionDescriptorSchema = zod_1.default.lazy(() => zod_1.default.object({
  15087. type: zod_1.default.literal('context'),
  15088. context: BrowsingContext.BrowsingContextSchema,
  15089. }));
  15090. })(Storage || (exports.Storage = Storage = {}));
  15091. (function (Storage) {
  15092. Storage.StorageKeyPartitionDescriptorSchema = zod_1.default.lazy(() => zod_1.default
  15093. .object({
  15094. type: zod_1.default.literal('storageKey'),
  15095. userContext: zod_1.default.string().optional(),
  15096. sourceOrigin: zod_1.default.string().optional(),
  15097. })
  15098. .and(exports.ExtensibleSchema));
  15099. })(Storage || (exports.Storage = Storage = {}));
  15100. (function (Storage) {
  15101. Storage.PartitionDescriptorSchema = zod_1.default.lazy(() => zod_1.default.union([
  15102. Storage.BrowsingContextPartitionDescriptorSchema,
  15103. Storage.StorageKeyPartitionDescriptorSchema,
  15104. ]));
  15105. })(Storage || (exports.Storage = Storage = {}));
  15106. (function (Storage) {
  15107. Storage.GetCookiesParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15108. filter: Storage.CookieFilterSchema.optional(),
  15109. partition: Storage.PartitionDescriptorSchema.optional(),
  15110. }));
  15111. })(Storage || (exports.Storage = Storage = {}));
  15112. (function (Storage) {
  15113. Storage.GetCookiesResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  15114. cookies: zod_1.default.array(Network.CookieSchema),
  15115. partitionKey: Storage.PartitionKeySchema,
  15116. }));
  15117. })(Storage || (exports.Storage = Storage = {}));
  15118. (function (Storage) {
  15119. Storage.SetCookieSchema = zod_1.default.lazy(() => zod_1.default.object({
  15120. method: zod_1.default.literal('storage.setCookie'),
  15121. params: Storage.SetCookieParametersSchema,
  15122. }));
  15123. })(Storage || (exports.Storage = Storage = {}));
  15124. (function (Storage) {
  15125. Storage.PartialCookieSchema = zod_1.default.lazy(() => zod_1.default
  15126. .object({
  15127. name: zod_1.default.string(),
  15128. value: Network.BytesValueSchema,
  15129. domain: zod_1.default.string(),
  15130. path: zod_1.default.string().optional(),
  15131. httpOnly: zod_1.default.boolean().optional(),
  15132. secure: zod_1.default.boolean().optional(),
  15133. sameSite: Network.SameSiteSchema.optional(),
  15134. expiry: exports.JsUintSchema.optional(),
  15135. })
  15136. .and(exports.ExtensibleSchema));
  15137. })(Storage || (exports.Storage = Storage = {}));
  15138. (function (Storage) {
  15139. Storage.SetCookieParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15140. cookie: Storage.PartialCookieSchema,
  15141. partition: Storage.PartitionDescriptorSchema.optional(),
  15142. }));
  15143. })(Storage || (exports.Storage = Storage = {}));
  15144. (function (Storage) {
  15145. Storage.SetCookieResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  15146. partitionKey: Storage.PartitionKeySchema,
  15147. }));
  15148. })(Storage || (exports.Storage = Storage = {}));
  15149. (function (Storage) {
  15150. Storage.DeleteCookiesSchema = zod_1.default.lazy(() => zod_1.default.object({
  15151. method: zod_1.default.literal('storage.deleteCookies'),
  15152. params: Storage.DeleteCookiesParametersSchema,
  15153. }));
  15154. })(Storage || (exports.Storage = Storage = {}));
  15155. (function (Storage) {
  15156. Storage.DeleteCookiesParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15157. filter: Storage.CookieFilterSchema.optional(),
  15158. partition: Storage.PartitionDescriptorSchema.optional(),
  15159. }));
  15160. })(Storage || (exports.Storage = Storage = {}));
  15161. (function (Storage) {
  15162. Storage.DeleteCookiesResultSchema = zod_1.default.lazy(() => zod_1.default.object({
  15163. partitionKey: Storage.PartitionKeySchema,
  15164. }));
  15165. })(Storage || (exports.Storage = Storage = {}));
  15166. exports.LogEventSchema = zod_1.default.lazy(() => Log.EntryAddedSchema);
  15167. var Log;
  15168. (function (Log) {
  15169. Log.LevelSchema = zod_1.default.lazy(() => zod_1.default.enum(['debug', 'info', 'warn', 'error']));
  15170. })(Log || (exports.Log = Log = {}));
  15171. (function (Log) {
  15172. Log.EntrySchema = zod_1.default.lazy(() => zod_1.default.union([
  15173. Log.GenericLogEntrySchema,
  15174. Log.ConsoleLogEntrySchema,
  15175. Log.JavascriptLogEntrySchema,
  15176. ]));
  15177. })(Log || (exports.Log = Log = {}));
  15178. (function (Log) {
  15179. Log.BaseLogEntrySchema = zod_1.default.lazy(() => zod_1.default.object({
  15180. level: Log.LevelSchema,
  15181. source: Script.SourceSchema,
  15182. text: zod_1.default.union([zod_1.default.string(), zod_1.default.null()]),
  15183. timestamp: exports.JsUintSchema,
  15184. stackTrace: Script.StackTraceSchema.optional(),
  15185. }));
  15186. })(Log || (exports.Log = Log = {}));
  15187. (function (Log) {
  15188. Log.GenericLogEntrySchema = zod_1.default.lazy(() => Log.BaseLogEntrySchema.and(zod_1.default.object({
  15189. type: zod_1.default.string(),
  15190. })));
  15191. })(Log || (exports.Log = Log = {}));
  15192. (function (Log) {
  15193. Log.ConsoleLogEntrySchema = zod_1.default.lazy(() => Log.BaseLogEntrySchema.and(zod_1.default.object({
  15194. type: zod_1.default.literal('console'),
  15195. method: zod_1.default.string(),
  15196. args: zod_1.default.array(Script.RemoteValueSchema),
  15197. })));
  15198. })(Log || (exports.Log = Log = {}));
  15199. (function (Log) {
  15200. Log.JavascriptLogEntrySchema = zod_1.default.lazy(() => Log.BaseLogEntrySchema.and(zod_1.default.object({
  15201. type: zod_1.default.literal('javascript'),
  15202. })));
  15203. })(Log || (exports.Log = Log = {}));
  15204. (function (Log) {
  15205. Log.EntryAddedSchema = zod_1.default.lazy(() => zod_1.default.object({
  15206. method: zod_1.default.literal('log.entryAdded'),
  15207. params: Log.EntrySchema,
  15208. }));
  15209. })(Log || (exports.Log = Log = {}));
  15210. exports.InputCommandSchema = zod_1.default.lazy(() => zod_1.default.union([
  15211. Input.PerformActionsSchema,
  15212. Input.ReleaseActionsSchema,
  15213. Input.SetFilesSchema,
  15214. ]));
  15215. var Input;
  15216. (function (Input) {
  15217. Input.ElementOriginSchema = zod_1.default.lazy(() => zod_1.default.object({
  15218. type: zod_1.default.literal('element'),
  15219. element: Script.SharedReferenceSchema,
  15220. }));
  15221. })(Input || (exports.Input = Input = {}));
  15222. (function (Input) {
  15223. Input.PerformActionsParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15224. context: BrowsingContext.BrowsingContextSchema,
  15225. actions: zod_1.default.array(Input.SourceActionsSchema),
  15226. }));
  15227. })(Input || (exports.Input = Input = {}));
  15228. (function (Input) {
  15229. Input.NoneSourceActionsSchema = zod_1.default.lazy(() => zod_1.default.object({
  15230. type: zod_1.default.literal('none'),
  15231. id: zod_1.default.string(),
  15232. actions: zod_1.default.array(Input.NoneSourceActionSchema),
  15233. }));
  15234. })(Input || (exports.Input = Input = {}));
  15235. (function (Input) {
  15236. Input.KeySourceActionsSchema = zod_1.default.lazy(() => zod_1.default.object({
  15237. type: zod_1.default.literal('key'),
  15238. id: zod_1.default.string(),
  15239. actions: zod_1.default.array(Input.KeySourceActionSchema),
  15240. }));
  15241. })(Input || (exports.Input = Input = {}));
  15242. (function (Input) {
  15243. Input.PointerSourceActionsSchema = zod_1.default.lazy(() => zod_1.default.object({
  15244. type: zod_1.default.literal('pointer'),
  15245. id: zod_1.default.string(),
  15246. parameters: Input.PointerParametersSchema.optional(),
  15247. actions: zod_1.default.array(Input.PointerSourceActionSchema),
  15248. }));
  15249. })(Input || (exports.Input = Input = {}));
  15250. (function (Input) {
  15251. Input.PerformActionsSchema = zod_1.default.lazy(() => zod_1.default.object({
  15252. method: zod_1.default.literal('input.performActions'),
  15253. params: Input.PerformActionsParametersSchema,
  15254. }));
  15255. })(Input || (exports.Input = Input = {}));
  15256. (function (Input) {
  15257. Input.SourceActionsSchema = zod_1.default.lazy(() => zod_1.default.union([
  15258. Input.NoneSourceActionsSchema,
  15259. Input.KeySourceActionsSchema,
  15260. Input.PointerSourceActionsSchema,
  15261. Input.WheelSourceActionsSchema,
  15262. ]));
  15263. })(Input || (exports.Input = Input = {}));
  15264. (function (Input) {
  15265. Input.NoneSourceActionSchema = zod_1.default.lazy(() => Input.PauseActionSchema);
  15266. })(Input || (exports.Input = Input = {}));
  15267. (function (Input) {
  15268. Input.KeySourceActionSchema = zod_1.default.lazy(() => zod_1.default.union([
  15269. Input.PauseActionSchema,
  15270. Input.KeyDownActionSchema,
  15271. Input.KeyUpActionSchema,
  15272. ]));
  15273. })(Input || (exports.Input = Input = {}));
  15274. (function (Input) {
  15275. Input.PointerTypeSchema = zod_1.default.lazy(() => zod_1.default.enum(['mouse', 'pen', 'touch']));
  15276. })(Input || (exports.Input = Input = {}));
  15277. (function (Input) {
  15278. Input.PointerParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15279. pointerType: Input.PointerTypeSchema.default('mouse').optional(),
  15280. }));
  15281. })(Input || (exports.Input = Input = {}));
  15282. (function (Input) {
  15283. Input.WheelSourceActionsSchema = zod_1.default.lazy(() => zod_1.default.object({
  15284. type: zod_1.default.literal('wheel'),
  15285. id: zod_1.default.string(),
  15286. actions: zod_1.default.array(Input.WheelSourceActionSchema),
  15287. }));
  15288. })(Input || (exports.Input = Input = {}));
  15289. (function (Input) {
  15290. Input.PointerSourceActionSchema = zod_1.default.lazy(() => zod_1.default.union([
  15291. Input.PauseActionSchema,
  15292. Input.PointerDownActionSchema,
  15293. Input.PointerUpActionSchema,
  15294. Input.PointerMoveActionSchema,
  15295. ]));
  15296. })(Input || (exports.Input = Input = {}));
  15297. (function (Input) {
  15298. Input.WheelSourceActionSchema = zod_1.default.lazy(() => zod_1.default.union([Input.PauseActionSchema, Input.WheelScrollActionSchema]));
  15299. })(Input || (exports.Input = Input = {}));
  15300. (function (Input) {
  15301. Input.PauseActionSchema = zod_1.default.lazy(() => zod_1.default.object({
  15302. type: zod_1.default.literal('pause'),
  15303. duration: exports.JsUintSchema.optional(),
  15304. }));
  15305. })(Input || (exports.Input = Input = {}));
  15306. (function (Input) {
  15307. Input.KeyDownActionSchema = zod_1.default.lazy(() => zod_1.default.object({
  15308. type: zod_1.default.literal('keyDown'),
  15309. value: zod_1.default.string(),
  15310. }));
  15311. })(Input || (exports.Input = Input = {}));
  15312. (function (Input) {
  15313. Input.KeyUpActionSchema = zod_1.default.lazy(() => zod_1.default.object({
  15314. type: zod_1.default.literal('keyUp'),
  15315. value: zod_1.default.string(),
  15316. }));
  15317. })(Input || (exports.Input = Input = {}));
  15318. (function (Input) {
  15319. Input.PointerUpActionSchema = zod_1.default.lazy(() => zod_1.default.object({
  15320. type: zod_1.default.literal('pointerUp'),
  15321. button: exports.JsUintSchema,
  15322. }));
  15323. })(Input || (exports.Input = Input = {}));
  15324. (function (Input) {
  15325. Input.PointerDownActionSchema = zod_1.default.lazy(() => zod_1.default
  15326. .object({
  15327. type: zod_1.default.literal('pointerDown'),
  15328. button: exports.JsUintSchema,
  15329. })
  15330. .and(Input.PointerCommonPropertiesSchema));
  15331. })(Input || (exports.Input = Input = {}));
  15332. (function (Input) {
  15333. Input.PointerMoveActionSchema = zod_1.default.lazy(() => zod_1.default
  15334. .object({
  15335. type: zod_1.default.literal('pointerMove'),
  15336. x: exports.JsIntSchema,
  15337. y: exports.JsIntSchema,
  15338. duration: exports.JsUintSchema.optional(),
  15339. origin: Input.OriginSchema.optional(),
  15340. })
  15341. .and(Input.PointerCommonPropertiesSchema));
  15342. })(Input || (exports.Input = Input = {}));
  15343. (function (Input) {
  15344. Input.WheelScrollActionSchema = zod_1.default.lazy(() => zod_1.default.object({
  15345. type: zod_1.default.literal('scroll'),
  15346. x: exports.JsIntSchema,
  15347. y: exports.JsIntSchema,
  15348. deltaX: exports.JsIntSchema,
  15349. deltaY: exports.JsIntSchema,
  15350. duration: exports.JsUintSchema.optional(),
  15351. origin: Input.OriginSchema.default('viewport').optional(),
  15352. }));
  15353. })(Input || (exports.Input = Input = {}));
  15354. (function (Input) {
  15355. Input.PointerCommonPropertiesSchema = zod_1.default.lazy(() => zod_1.default.object({
  15356. width: exports.JsUintSchema.default(1).optional(),
  15357. height: exports.JsUintSchema.default(1).optional(),
  15358. pressure: zod_1.default.number().default(0).optional(),
  15359. tangentialPressure: zod_1.default.number().default(0).optional(),
  15360. twist: zod_1.default
  15361. .number()
  15362. .int()
  15363. .nonnegative()
  15364. .gte(0)
  15365. .lte(359)
  15366. .default(0)
  15367. .optional(),
  15368. altitudeAngle: zod_1.default
  15369. .number()
  15370. .gte(0)
  15371. .lte(1.5707963267948966)
  15372. .default(0)
  15373. .optional(),
  15374. azimuthAngle: zod_1.default
  15375. .number()
  15376. .gte(0)
  15377. .lte(6.283185307179586)
  15378. .default(0)
  15379. .optional(),
  15380. }));
  15381. })(Input || (exports.Input = Input = {}));
  15382. (function (Input) {
  15383. Input.OriginSchema = zod_1.default.lazy(() => zod_1.default.union([
  15384. zod_1.default.literal('viewport'),
  15385. zod_1.default.literal('pointer'),
  15386. Input.ElementOriginSchema,
  15387. ]));
  15388. })(Input || (exports.Input = Input = {}));
  15389. (function (Input) {
  15390. Input.ReleaseActionsSchema = zod_1.default.lazy(() => zod_1.default.object({
  15391. method: zod_1.default.literal('input.releaseActions'),
  15392. params: Input.ReleaseActionsParametersSchema,
  15393. }));
  15394. })(Input || (exports.Input = Input = {}));
  15395. (function (Input) {
  15396. Input.ReleaseActionsParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15397. context: BrowsingContext.BrowsingContextSchema,
  15398. }));
  15399. })(Input || (exports.Input = Input = {}));
  15400. (function (Input) {
  15401. Input.SetFilesSchema = zod_1.default.lazy(() => zod_1.default.object({
  15402. method: zod_1.default.literal('input.setFiles'),
  15403. params: Input.SetFilesParametersSchema,
  15404. }));
  15405. })(Input || (exports.Input = Input = {}));
  15406. (function (Input) {
  15407. Input.SetFilesParametersSchema = zod_1.default.lazy(() => zod_1.default.object({
  15408. context: BrowsingContext.BrowsingContextSchema,
  15409. element: Script.SharedReferenceSchema,
  15410. files: zod_1.default.array(zod_1.default.string()),
  15411. }));
  15412. })(Input || (exports.Input = Input = {}));
  15413. } (webdriverBidi));
  15414. /**
  15415. * Copyright 2022 Google LLC.
  15416. * Copyright (c) Microsoft Corporation.
  15417. *
  15418. * Licensed under the Apache License, Version 2.0 (the "License");
  15419. * you may not use this file except in compliance with the License.
  15420. * You may obtain a copy of the License at
  15421. *
  15422. * http://www.apache.org/licenses/LICENSE-2.0
  15423. *
  15424. * Unless required by applicable law or agreed to in writing, software
  15425. * distributed under the License is distributed on an "AS IS" BASIS,
  15426. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15427. * See the License for the specific language governing permissions and
  15428. * limitations under the License.
  15429. */
  15430. var __createBinding$1 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  15431. if (k2 === undefined) k2 = k;
  15432. var desc = Object.getOwnPropertyDescriptor(m, k);
  15433. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  15434. desc = { enumerable: true, get: function() { return m[k]; } };
  15435. }
  15436. Object.defineProperty(o, k2, desc);
  15437. }) : (function(o, m, k, k2) {
  15438. if (k2 === undefined) k2 = k;
  15439. o[k2] = m[k];
  15440. }));
  15441. var __setModuleDefault$1 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
  15442. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15443. }) : function(o, v) {
  15444. o["default"] = v;
  15445. });
  15446. var __importStar$1 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
  15447. if (mod && mod.__esModule) return mod;
  15448. var result = {};
  15449. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$1(result, mod, k);
  15450. __setModuleDefault$1(result, mod);
  15451. return result;
  15452. };
  15453. Object.defineProperty(protocolParser, "__esModule", { value: true });
  15454. protocolParser.Permissions = protocolParser.Cdp = protocolParser.Storage = protocolParser.Input = protocolParser.Session = protocolParser.BrowsingContext = protocolParser.Script = protocolParser.Network = protocolParser.Browser = protocolParser.parseObject = void 0;
  15455. /**
  15456. * @fileoverview Provides parsing and validator for WebDriver BiDi protocol.
  15457. * Parser types should match the `../protocol` types.
  15458. */
  15459. const zod_1 = lib;
  15460. const protocol_js_1 = protocol;
  15461. const WebDriverBidiPermissions = __importStar$1(webdriverBidiPermissions);
  15462. const WebDriverBidi = __importStar$1(webdriverBidi);
  15463. function parseObject(obj, schema) {
  15464. const parseResult = schema.safeParse(obj);
  15465. if (parseResult.success) {
  15466. return parseResult.data;
  15467. }
  15468. const errorMessage = parseResult.error.errors
  15469. .map((e) => `${e.message} in ` +
  15470. `${e.path.map((p) => JSON.stringify(p)).join('/')}.`)
  15471. .join(' ');
  15472. throw new protocol_js_1.InvalidArgumentException(errorMessage);
  15473. }
  15474. protocolParser.parseObject = parseObject;
  15475. /** @see https://w3c.github.io/webdriver-bidi/#module-browser */
  15476. var Browser;
  15477. (function (Browser) {
  15478. function parseRemoveUserContextParams(params) {
  15479. return parseObject(params, WebDriverBidi.Browser.RemoveUserContextParametersSchema);
  15480. }
  15481. Browser.parseRemoveUserContextParams = parseRemoveUserContextParams;
  15482. })(Browser || (protocolParser.Browser = Browser = {}));
  15483. /** @see https://w3c.github.io/webdriver-bidi/#module-network */
  15484. var Network;
  15485. (function (Network) {
  15486. function parseAddInterceptParameters(params) {
  15487. // Work around of `cddlconv` https://github.com/google/cddlconv/issues/19.
  15488. return parseObject(params, WebDriverBidi.Network.AddInterceptParametersSchema);
  15489. }
  15490. Network.parseAddInterceptParameters = parseAddInterceptParameters;
  15491. function parseContinueRequestParameters(params) {
  15492. return parseObject(params, WebDriverBidi.Network.ContinueRequestParametersSchema);
  15493. }
  15494. Network.parseContinueRequestParameters = parseContinueRequestParameters;
  15495. function parseContinueResponseParameters(params) {
  15496. // TODO: remove cast after https://github.com/google/cddlconv/issues/19 is fixed.
  15497. return parseObject(params, WebDriverBidi.Network.ContinueResponseParametersSchema);
  15498. }
  15499. Network.parseContinueResponseParameters = parseContinueResponseParameters;
  15500. function parseContinueWithAuthParameters(params) {
  15501. return parseObject(params, WebDriverBidi.Network.ContinueWithAuthParametersSchema);
  15502. }
  15503. Network.parseContinueWithAuthParameters = parseContinueWithAuthParameters;
  15504. function parseFailRequestParameters(params) {
  15505. return parseObject(params, WebDriverBidi.Network.FailRequestParametersSchema);
  15506. }
  15507. Network.parseFailRequestParameters = parseFailRequestParameters;
  15508. function parseProvideResponseParameters(params) {
  15509. // TODO: remove cast after https://github.com/google/cddlconv/issues/19 is fixed.
  15510. return parseObject(params, WebDriverBidi.Network.ProvideResponseParametersSchema);
  15511. }
  15512. Network.parseProvideResponseParameters = parseProvideResponseParameters;
  15513. function parseRemoveInterceptParameters(params) {
  15514. return parseObject(params, WebDriverBidi.Network.RemoveInterceptParametersSchema);
  15515. }
  15516. Network.parseRemoveInterceptParameters = parseRemoveInterceptParameters;
  15517. })(Network || (protocolParser.Network = Network = {}));
  15518. /** @see https://w3c.github.io/webdriver-bidi/#module-script */
  15519. var Script;
  15520. (function (Script) {
  15521. function parseGetRealmsParams(params) {
  15522. return parseObject(params, WebDriverBidi.Script.GetRealmsParametersSchema);
  15523. }
  15524. Script.parseGetRealmsParams = parseGetRealmsParams;
  15525. function parseEvaluateParams(params) {
  15526. return parseObject(params, WebDriverBidi.Script.EvaluateParametersSchema);
  15527. }
  15528. Script.parseEvaluateParams = parseEvaluateParams;
  15529. function parseDisownParams(params) {
  15530. return parseObject(params, WebDriverBidi.Script.DisownParametersSchema);
  15531. }
  15532. Script.parseDisownParams = parseDisownParams;
  15533. function parseAddPreloadScriptParams(params) {
  15534. return parseObject(params, WebDriverBidi.Script.AddPreloadScriptParametersSchema);
  15535. }
  15536. Script.parseAddPreloadScriptParams = parseAddPreloadScriptParams;
  15537. function parseRemovePreloadScriptParams(params) {
  15538. return parseObject(params, WebDriverBidi.Script.RemovePreloadScriptParametersSchema);
  15539. }
  15540. Script.parseRemovePreloadScriptParams = parseRemovePreloadScriptParams;
  15541. function parseCallFunctionParams(params) {
  15542. return parseObject(params, WebDriverBidi.Script.CallFunctionParametersSchema);
  15543. }
  15544. Script.parseCallFunctionParams = parseCallFunctionParams;
  15545. })(Script || (protocolParser.Script = Script = {}));
  15546. /** @see https://w3c.github.io/webdriver-bidi/#module-browsingContext */
  15547. var BrowsingContext;
  15548. (function (BrowsingContext) {
  15549. function parseActivateParams(params) {
  15550. return parseObject(params, WebDriverBidi.BrowsingContext.ActivateParametersSchema);
  15551. }
  15552. BrowsingContext.parseActivateParams = parseActivateParams;
  15553. function parseGetTreeParams(params) {
  15554. return parseObject(params, WebDriverBidi.BrowsingContext.GetTreeParametersSchema);
  15555. }
  15556. BrowsingContext.parseGetTreeParams = parseGetTreeParams;
  15557. function parseNavigateParams(params) {
  15558. return parseObject(params, WebDriverBidi.BrowsingContext.NavigateParametersSchema);
  15559. }
  15560. BrowsingContext.parseNavigateParams = parseNavigateParams;
  15561. function parseReloadParams(params) {
  15562. return parseObject(params, WebDriverBidi.BrowsingContext.ReloadParametersSchema);
  15563. }
  15564. BrowsingContext.parseReloadParams = parseReloadParams;
  15565. function parseCreateParams(params) {
  15566. return parseObject(params, WebDriverBidi.BrowsingContext.CreateParametersSchema);
  15567. }
  15568. BrowsingContext.parseCreateParams = parseCreateParams;
  15569. function parseCloseParams(params) {
  15570. return parseObject(params, WebDriverBidi.BrowsingContext.CloseParametersSchema);
  15571. }
  15572. BrowsingContext.parseCloseParams = parseCloseParams;
  15573. function parseCaptureScreenshotParams(params) {
  15574. return parseObject(params, WebDriverBidi.BrowsingContext.CaptureScreenshotParametersSchema);
  15575. }
  15576. BrowsingContext.parseCaptureScreenshotParams = parseCaptureScreenshotParams;
  15577. function parsePrintParams(params) {
  15578. return parseObject(params, WebDriverBidi.BrowsingContext.PrintParametersSchema);
  15579. }
  15580. BrowsingContext.parsePrintParams = parsePrintParams;
  15581. function parseSetViewportParams(params) {
  15582. return parseObject(params, WebDriverBidi.BrowsingContext.SetViewportParametersSchema);
  15583. }
  15584. BrowsingContext.parseSetViewportParams = parseSetViewportParams;
  15585. function parseTraverseHistoryParams(params) {
  15586. return parseObject(params, WebDriverBidi.BrowsingContext.TraverseHistoryParametersSchema);
  15587. }
  15588. BrowsingContext.parseTraverseHistoryParams = parseTraverseHistoryParams;
  15589. function parseHandleUserPromptParameters(params) {
  15590. return parseObject(params, WebDriverBidi.BrowsingContext.HandleUserPromptParametersSchema);
  15591. }
  15592. BrowsingContext.parseHandleUserPromptParameters = parseHandleUserPromptParameters;
  15593. function parseLocateNodesParams(params) {
  15594. // TODO: remove cast after https://github.com/google/cddlconv/issues/19 is fixed.
  15595. return parseObject(params, WebDriverBidi.BrowsingContext.LocateNodesParametersSchema);
  15596. }
  15597. BrowsingContext.parseLocateNodesParams = parseLocateNodesParams;
  15598. })(BrowsingContext || (protocolParser.BrowsingContext = BrowsingContext = {}));
  15599. /** @see https://w3c.github.io/webdriver-bidi/#module-session */
  15600. var Session;
  15601. (function (Session) {
  15602. function parseSubscribeParams(params) {
  15603. return parseObject(params, WebDriverBidi.Session.SubscriptionRequestSchema);
  15604. }
  15605. Session.parseSubscribeParams = parseSubscribeParams;
  15606. })(Session || (protocolParser.Session = Session = {}));
  15607. var Input;
  15608. (function (Input) {
  15609. function parsePerformActionsParams(params) {
  15610. return parseObject(params, WebDriverBidi.Input.PerformActionsParametersSchema);
  15611. }
  15612. Input.parsePerformActionsParams = parsePerformActionsParams;
  15613. function parseReleaseActionsParams(params) {
  15614. return parseObject(params, WebDriverBidi.Input.ReleaseActionsParametersSchema);
  15615. }
  15616. Input.parseReleaseActionsParams = parseReleaseActionsParams;
  15617. function parseSetFilesParams(params) {
  15618. return parseObject(params, WebDriverBidi.Input.SetFilesParametersSchema);
  15619. }
  15620. Input.parseSetFilesParams = parseSetFilesParams;
  15621. })(Input || (protocolParser.Input = Input = {}));
  15622. var Storage;
  15623. (function (Storage) {
  15624. function parseGetCookiesParams(params) {
  15625. // Work around of `cddlconv` https://github.com/google/cddlconv/issues/19.
  15626. // The generated schema `SameSiteSchema` in `src/protocol-parser/webdriver-bidi.ts` is
  15627. // of type `"none" | "strict" | "lax"` which is not assignable to generated enum
  15628. // `SameSite` in `src/protocol/webdriver-bidi.ts`.
  15629. // TODO: remove cast after https://github.com/google/cddlconv/issues/19 is fixed.
  15630. return parseObject(params, WebDriverBidi.Storage.GetCookiesParametersSchema);
  15631. }
  15632. Storage.parseGetCookiesParams = parseGetCookiesParams;
  15633. function parseSetCookieParams(params) {
  15634. // Work around of `cddlconv` https://github.com/google/cddlconv/issues/19.
  15635. // The generated schema `SameSiteSchema` in `src/protocol-parser/webdriver-bidi.ts` is
  15636. // of type `"none" | "strict" | "lax"` which is not assignable to generated enum
  15637. // `SameSite` in `src/protocol/webdriver-bidi.ts`.
  15638. // TODO: remove cast after https://github.com/google/cddlconv/issues/19 is fixed.
  15639. return parseObject(params, WebDriverBidi.Storage.SetCookieParametersSchema);
  15640. }
  15641. Storage.parseSetCookieParams = parseSetCookieParams;
  15642. function parseDeleteCookiesParams(params) {
  15643. // Work around of `cddlconv` https://github.com/google/cddlconv/issues/19.
  15644. // The generated schema `SameSiteSchema` in `src/protocol-parser/webdriver-bidi.ts` is
  15645. // of type `"none" | "strict" | "lax"` which is not assignable to generated enum
  15646. // `SameSite` in `src/protocol/webdriver-bidi.ts`.
  15647. // TODO: remove cast after https://github.com/google/cddlconv/issues/19 is fixed.
  15648. return parseObject(params, WebDriverBidi.Storage.DeleteCookiesParametersSchema);
  15649. }
  15650. Storage.parseDeleteCookiesParams = parseDeleteCookiesParams;
  15651. })(Storage || (protocolParser.Storage = Storage = {}));
  15652. var Cdp;
  15653. (function (Cdp) {
  15654. const SendCommandRequestSchema = zod_1.z.object({
  15655. // Allowing any cdpMethod, and casting to proper type later on.
  15656. method: zod_1.z.string(),
  15657. // `passthrough` allows object to have any fields.
  15658. // https://github.com/colinhacks/zod#passthrough
  15659. params: zod_1.z.object({}).passthrough().optional(),
  15660. session: zod_1.z.string().optional(),
  15661. });
  15662. const GetSessionRequestSchema = zod_1.z.object({
  15663. context: WebDriverBidi.BrowsingContext.BrowsingContextSchema,
  15664. });
  15665. const ResolveRealmRequestSchema = zod_1.z.object({
  15666. realm: WebDriverBidi.Script.RealmSchema,
  15667. });
  15668. function parseSendCommandRequest(params) {
  15669. return parseObject(params, SendCommandRequestSchema);
  15670. }
  15671. Cdp.parseSendCommandRequest = parseSendCommandRequest;
  15672. function parseGetSessionRequest(params) {
  15673. return parseObject(params, GetSessionRequestSchema);
  15674. }
  15675. Cdp.parseGetSessionRequest = parseGetSessionRequest;
  15676. function parseResolveRealmRequest(params) {
  15677. return parseObject(params, ResolveRealmRequestSchema);
  15678. }
  15679. Cdp.parseResolveRealmRequest = parseResolveRealmRequest;
  15680. })(Cdp || (protocolParser.Cdp = Cdp = {}));
  15681. var Permissions;
  15682. (function (Permissions) {
  15683. function parseSetPermissionsParams(params) {
  15684. return {
  15685. // TODO: remove once "goog:" attributes are not needed.
  15686. ...params,
  15687. ...parseObject(params, WebDriverBidiPermissions.Permissions.SetPermissionParametersSchema),
  15688. };
  15689. }
  15690. Permissions.parseSetPermissionsParams = parseSetPermissionsParams;
  15691. })(Permissions || (protocolParser.Permissions = Permissions = {}));
  15692. var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  15693. if (k2 === undefined) k2 = k;
  15694. var desc = Object.getOwnPropertyDescriptor(m, k);
  15695. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  15696. desc = { enumerable: true, get: function() { return m[k]; } };
  15697. }
  15698. Object.defineProperty(o, k2, desc);
  15699. }) : (function(o, m, k, k2) {
  15700. if (k2 === undefined) k2 = k;
  15701. o[k2] = m[k];
  15702. }));
  15703. var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
  15704. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15705. }) : function(o, v) {
  15706. o["default"] = v;
  15707. });
  15708. var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
  15709. if (mod && mod.__esModule) return mod;
  15710. var result = {};
  15711. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  15712. __setModuleDefault(result, mod);
  15713. return result;
  15714. };
  15715. Object.defineProperty(BidiParser$1, "__esModule", { value: true });
  15716. BidiParser$1.BidiParser = void 0;
  15717. const Parser = __importStar(protocolParser);
  15718. class BidiParser {
  15719. // Browser domain
  15720. // keep-sorted start block=yes
  15721. parseRemoveUserContextParams(params) {
  15722. return Parser.Browser.parseRemoveUserContextParams(params);
  15723. }
  15724. // keep-sorted end
  15725. // Browsing Context domain
  15726. // keep-sorted start block=yes
  15727. parseActivateParams(params) {
  15728. return Parser.BrowsingContext.parseActivateParams(params);
  15729. }
  15730. parseCaptureScreenshotParams(params) {
  15731. return Parser.BrowsingContext.parseCaptureScreenshotParams(params);
  15732. }
  15733. parseCloseParams(params) {
  15734. return Parser.BrowsingContext.parseCloseParams(params);
  15735. }
  15736. parseCreateParams(params) {
  15737. return Parser.BrowsingContext.parseCreateParams(params);
  15738. }
  15739. parseGetTreeParams(params) {
  15740. return Parser.BrowsingContext.parseGetTreeParams(params);
  15741. }
  15742. parseHandleUserPromptParams(params) {
  15743. return Parser.BrowsingContext.parseHandleUserPromptParameters(params);
  15744. }
  15745. parseLocateNodesParams(params) {
  15746. return Parser.BrowsingContext.parseLocateNodesParams(params);
  15747. }
  15748. parseNavigateParams(params) {
  15749. return Parser.BrowsingContext.parseNavigateParams(params);
  15750. }
  15751. parsePrintParams(params) {
  15752. return Parser.BrowsingContext.parsePrintParams(params);
  15753. }
  15754. parseReloadParams(params) {
  15755. return Parser.BrowsingContext.parseReloadParams(params);
  15756. }
  15757. parseSetViewportParams(params) {
  15758. return Parser.BrowsingContext.parseSetViewportParams(params);
  15759. }
  15760. parseTraverseHistoryParams(params) {
  15761. return Parser.BrowsingContext.parseTraverseHistoryParams(params);
  15762. }
  15763. // keep-sorted end
  15764. // CDP domain
  15765. // keep-sorted start block=yes
  15766. parseGetSessionParams(params) {
  15767. return Parser.Cdp.parseGetSessionRequest(params);
  15768. }
  15769. parseResolveRealmParams(params) {
  15770. return Parser.Cdp.parseResolveRealmRequest(params);
  15771. }
  15772. parseSendCommandParams(params) {
  15773. return Parser.Cdp.parseSendCommandRequest(params);
  15774. }
  15775. // keep-sorted end
  15776. // Input domain
  15777. // keep-sorted start block=yes
  15778. parsePerformActionsParams(params) {
  15779. return Parser.Input.parsePerformActionsParams(params);
  15780. }
  15781. parseReleaseActionsParams(params) {
  15782. return Parser.Input.parseReleaseActionsParams(params);
  15783. }
  15784. parseSetFilesParams(params) {
  15785. return Parser.Input.parseSetFilesParams(params);
  15786. }
  15787. // keep-sorted end
  15788. // Network domain
  15789. // keep-sorted start block=yes
  15790. parseAddInterceptParams(params) {
  15791. return Parser.Network.parseAddInterceptParameters(params);
  15792. }
  15793. parseContinueRequestParams(params) {
  15794. return Parser.Network.parseContinueRequestParameters(params);
  15795. }
  15796. parseContinueResponseParams(params) {
  15797. return Parser.Network.parseContinueResponseParameters(params);
  15798. }
  15799. parseContinueWithAuthParams(params) {
  15800. return Parser.Network.parseContinueWithAuthParameters(params);
  15801. }
  15802. parseFailRequestParams(params) {
  15803. return Parser.Network.parseFailRequestParameters(params);
  15804. }
  15805. parseProvideResponseParams(params) {
  15806. return Parser.Network.parseProvideResponseParameters(params);
  15807. }
  15808. parseRemoveInterceptParams(params) {
  15809. return Parser.Network.parseRemoveInterceptParameters(params);
  15810. }
  15811. // keep-sorted end
  15812. // Permissions domain
  15813. // keep-sorted start block=yes
  15814. parseSetPermissionsParams(params) {
  15815. return Parser.Permissions.parseSetPermissionsParams(params);
  15816. }
  15817. // keep-sorted end
  15818. // Script domain
  15819. // keep-sorted start block=yes
  15820. parseAddPreloadScriptParams(params) {
  15821. return Parser.Script.parseAddPreloadScriptParams(params);
  15822. }
  15823. parseCallFunctionParams(params) {
  15824. return Parser.Script.parseCallFunctionParams(params);
  15825. }
  15826. parseDisownParams(params) {
  15827. return Parser.Script.parseDisownParams(params);
  15828. }
  15829. parseEvaluateParams(params) {
  15830. return Parser.Script.parseEvaluateParams(params);
  15831. }
  15832. parseGetRealmsParams(params) {
  15833. return Parser.Script.parseGetRealmsParams(params);
  15834. }
  15835. parseRemovePreloadScriptParams(params) {
  15836. return Parser.Script.parseRemovePreloadScriptParams(params);
  15837. }
  15838. // keep-sorted end
  15839. // Session domain
  15840. // keep-sorted start block=yes
  15841. parseSubscribeParams(params) {
  15842. return Parser.Session.parseSubscribeParams(params);
  15843. }
  15844. // keep-sorted end
  15845. // Storage domain
  15846. // keep-sorted start block=yes
  15847. parseDeleteCookiesParams(params) {
  15848. return Parser.Storage.parseDeleteCookiesParams(params);
  15849. }
  15850. parseGetCookiesParams(params) {
  15851. return Parser.Storage.parseGetCookiesParams(params);
  15852. }
  15853. parseSetCookieParams(params) {
  15854. return Parser.Storage.parseSetCookieParams(params);
  15855. }
  15856. }
  15857. BidiParser$1.BidiParser = BidiParser;
  15858. var mapperTabPage = {};
  15859. Object.defineProperty(mapperTabPage, "__esModule", { value: true });
  15860. mapperTabPage.log = mapperTabPage.generatePage = void 0;
  15861. /**
  15862. * Copyright 2022 Google LLC.
  15863. * Copyright (c) Microsoft Corporation.
  15864. *
  15865. * Licensed under the Apache License, Version 2.0 (the "License");
  15866. * you may not use this file except in compliance with the License.
  15867. * You may obtain a copy of the License at
  15868. *
  15869. * http://www.apache.org/licenses/LICENSE-2.0
  15870. *
  15871. * Unless required by applicable law or agreed to in writing, software
  15872. * distributed under the License is distributed on an "AS IS" BASIS,
  15873. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15874. * See the License for the specific language governing permissions and
  15875. * limitations under the License.
  15876. */
  15877. const log_js_1$2 = log$1;
  15878. /** HTML source code for the user-facing Mapper tab. */
  15879. const mapperPageSource = '<!DOCTYPE html><title>BiDi-CDP Mapper</title><style>body{font-family: Roboto, serif; font-size: 13px; color: #202124;}.log{padding: 12px; font-family: Menlo, Consolas, Monaco, Liberation Mono, Lucida Console, monospace; font-size: 11px; line-height: 180%; background: #f1f3f4; border-radius: 4px;}.pre{overflow-wrap: break-word; padding: 10px;}.card{margin: 60px auto; padding: 2px 0; max-width: 900px; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15), 0 1px 6px rgba(0, 0, 0, 0.2); border-radius: 8px;}.divider{height: 1px; background: #f0f0f0;}.item{padding: 16px 20px;}</style><div class="card"><div class="item"><h1>BiDi-CDP Mapper is controlling this tab</h1><p>Closing or reloading it will stop the BiDi process. <a target="_blank" title="BiDi-CDP Mapper GitHub Repository" href="https://github.com/GoogleChromeLabs/chromium-bidi">Details.</a></p></div><div class="divider"></div><details id="details"><summary class="item">Debug information</summary></details></div>';
  15880. /**
  15881. * The following piece of HTML should be added to the `debug` element:
  15882. *
  15883. * <div class="divider"></div>
  15884. * <div class="item">
  15885. * <h3>${name}</h3>
  15886. * <div id="${name}_log" class="log">
  15887. */
  15888. function findOrCreateTypeLogContainer(logPrefix) {
  15889. const logType = logPrefix.split(':')[0];
  15890. const containerId = `${logType}_log`;
  15891. const existingContainer = document.getElementById(containerId);
  15892. if (existingContainer) {
  15893. return existingContainer;
  15894. }
  15895. const debugElement = document.getElementById('details');
  15896. const divider = document.createElement('div');
  15897. divider.className = 'divider';
  15898. debugElement.appendChild(divider);
  15899. const htmlItem = document.createElement('div');
  15900. htmlItem.className = 'item';
  15901. htmlItem.innerHTML = `<h3>${logType}</h3><div id="${containerId}" class="log"></div>`;
  15902. debugElement.appendChild(htmlItem);
  15903. return document.getElementById(containerId);
  15904. }
  15905. function generatePage() {
  15906. // If run not in browser (e.g. unit test), do nothing.
  15907. if (!globalThis.document.documentElement) {
  15908. return;
  15909. }
  15910. globalThis.document.documentElement.innerHTML = mapperPageSource;
  15911. // Create main log containers in proper order.
  15912. findOrCreateTypeLogContainer(log_js_1$2.LogType.debugInfo);
  15913. findOrCreateTypeLogContainer(log_js_1$2.LogType.bidi);
  15914. findOrCreateTypeLogContainer(log_js_1$2.LogType.cdp);
  15915. }
  15916. mapperTabPage.generatePage = generatePage;
  15917. function stringify(message) {
  15918. if (typeof message === 'object') {
  15919. return JSON.stringify(message, null, 2);
  15920. }
  15921. return message;
  15922. }
  15923. function log(logPrefix, ...messages) {
  15924. // If run not in browser (e.g. unit test), do nothing.
  15925. if (!globalThis.document.documentElement) {
  15926. return;
  15927. }
  15928. // Skip sending BiDi logs as they are logged once by `bidi:server:*`
  15929. if (!logPrefix.startsWith(log_js_1$2.LogType.bidi)) {
  15930. // If `sendDebugMessage` is defined, send the log message there.
  15931. globalThis.window?.sendDebugMessage?.(JSON.stringify({ logType: logPrefix, messages }));
  15932. }
  15933. const typeLogContainer = findOrCreateTypeLogContainer(logPrefix);
  15934. // This piece of HTML should be added:
  15935. // <div class="pre">...log message...</div>
  15936. const lineElement = document.createElement('div');
  15937. lineElement.className = 'pre';
  15938. lineElement.textContent = [logPrefix, ...messages].map(stringify).join(' ');
  15939. typeLogContainer.appendChild(lineElement);
  15940. if (typeLogContainer.childNodes.length > 200) {
  15941. typeLogContainer.removeChild(typeLogContainer.childNodes[0]);
  15942. }
  15943. }
  15944. mapperTabPage.log = log;
  15945. var Transport = {};
  15946. Object.defineProperty(Transport, "__esModule", { value: true });
  15947. Transport.WindowCdpTransport = Transport.WindowBidiTransport = void 0;
  15948. const log_js_1$1 = log$1;
  15949. const mapperTabPage_js_1$1 = mapperTabPage;
  15950. class WindowBidiTransport {
  15951. static LOGGER_PREFIX_RECV = `${log_js_1$1.LogType.bidi}:RECV ◂`;
  15952. static LOGGER_PREFIX_SEND = `${log_js_1$1.LogType.bidi}:SEND ▸`;
  15953. #onMessage = null;
  15954. constructor() {
  15955. window.onBidiMessage = (message) => {
  15956. (0, mapperTabPage_js_1$1.log)(WindowBidiTransport.LOGGER_PREFIX_RECV, message);
  15957. try {
  15958. const command = WindowBidiTransport.#parseBidiMessage(message);
  15959. this.#onMessage?.call(null, command);
  15960. }
  15961. catch (e) {
  15962. const error = e instanceof Error ? e : new Error(e);
  15963. // Transport-level error does not provide channel.
  15964. this.#respondWithError(message, "invalid argument" /* ErrorCode.InvalidArgument */, error, null);
  15965. }
  15966. };
  15967. }
  15968. setOnMessage(onMessage) {
  15969. this.#onMessage = onMessage;
  15970. }
  15971. sendMessage(message) {
  15972. (0, mapperTabPage_js_1$1.log)(WindowBidiTransport.LOGGER_PREFIX_SEND, message);
  15973. const json = JSON.stringify(message);
  15974. window.sendBidiResponse(json);
  15975. }
  15976. close() {
  15977. this.#onMessage = null;
  15978. window.onBidiMessage = null;
  15979. }
  15980. #respondWithError(plainCommandData, errorCode, error, channel) {
  15981. const errorResponse = WindowBidiTransport.#getErrorResponse(plainCommandData, errorCode, error);
  15982. if (channel) {
  15983. this.sendMessage({
  15984. ...errorResponse,
  15985. channel,
  15986. });
  15987. }
  15988. else {
  15989. this.sendMessage(errorResponse);
  15990. }
  15991. }
  15992. static #getJsonType(value) {
  15993. if (value === null) {
  15994. return 'null';
  15995. }
  15996. if (Array.isArray(value)) {
  15997. return 'array';
  15998. }
  15999. return typeof value;
  16000. }
  16001. static #getErrorResponse(message, errorCode, error) {
  16002. // XXX: this is bizarre per spec. We reparse the payload and
  16003. // extract the ID, regardless of what kind of value it was.
  16004. let messageId;
  16005. try {
  16006. const command = JSON.parse(message);
  16007. if (WindowBidiTransport.#getJsonType(command) === 'object' &&
  16008. 'id' in command) {
  16009. messageId = command.id;
  16010. }
  16011. }
  16012. catch { }
  16013. return {
  16014. type: 'error',
  16015. id: messageId,
  16016. error: errorCode,
  16017. message: error.message,
  16018. };
  16019. }
  16020. static #parseBidiMessage(message) {
  16021. let command;
  16022. try {
  16023. command = JSON.parse(message);
  16024. }
  16025. catch {
  16026. throw new Error('Cannot parse data as JSON');
  16027. }
  16028. const type = WindowBidiTransport.#getJsonType(command);
  16029. if (type !== 'object') {
  16030. throw new Error(`Expected JSON object but got ${type}`);
  16031. }
  16032. // Extract and validate id, method and params.
  16033. const { id, method, params } = command;
  16034. const idType = WindowBidiTransport.#getJsonType(id);
  16035. if (idType !== 'number' || !Number.isInteger(id) || id < 0) {
  16036. // TODO: should uint64_t be the upper limit?
  16037. // https://tools.ietf.org/html/rfc7049#section-2.1
  16038. throw new Error(`Expected unsigned integer but got ${idType}`);
  16039. }
  16040. const methodType = WindowBidiTransport.#getJsonType(method);
  16041. if (methodType !== 'string') {
  16042. throw new Error(`Expected string method but got ${methodType}`);
  16043. }
  16044. const paramsType = WindowBidiTransport.#getJsonType(params);
  16045. if (paramsType !== 'object') {
  16046. throw new Error(`Expected object params but got ${paramsType}`);
  16047. }
  16048. let channel = command.channel;
  16049. if (channel !== undefined) {
  16050. const channelType = WindowBidiTransport.#getJsonType(channel);
  16051. if (channelType !== 'string') {
  16052. throw new Error(`Expected string channel but got ${channelType}`);
  16053. }
  16054. // Empty string channel is considered as no channel provided.
  16055. if (channel === '') {
  16056. channel = undefined;
  16057. }
  16058. }
  16059. return { id, method, params, channel };
  16060. }
  16061. }
  16062. Transport.WindowBidiTransport = WindowBidiTransport;
  16063. class WindowCdpTransport {
  16064. #onMessage = null;
  16065. constructor() {
  16066. window.cdp.onmessage = (message) => {
  16067. this.#onMessage?.call(null, message);
  16068. };
  16069. }
  16070. setOnMessage(onMessage) {
  16071. this.#onMessage = onMessage;
  16072. }
  16073. sendMessage(message) {
  16074. window.cdp.send(message);
  16075. }
  16076. close() {
  16077. this.#onMessage = null;
  16078. window.cdp.onmessage = null;
  16079. }
  16080. }
  16081. Transport.WindowCdpTransport = WindowCdpTransport;
  16082. /**
  16083. * Copyright 2021 Google LLC.
  16084. * Copyright (c) Microsoft Corporation.
  16085. *
  16086. * Licensed under the Apache License, Version 2.0 (the "License");
  16087. * you may not use this file except in compliance with the License.
  16088. * You may obtain a copy of the License at
  16089. *
  16090. * http://www.apache.org/licenses/LICENSE-2.0
  16091. *
  16092. * Unless required by applicable law or agreed to in writing, software
  16093. * distributed under the License is distributed on an "AS IS" BASIS,
  16094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16095. * See the License for the specific language governing permissions and
  16096. * limitations under the License.
  16097. *
  16098. * @license
  16099. */
  16100. Object.defineProperty(bidiTab, "__esModule", { value: true });
  16101. const BidiMapper_js_1 = BidiMapper;
  16102. const CdpConnection_js_1 = CdpConnection;
  16103. const log_js_1 = log$1;
  16104. const BidiParser_js_1 = BidiParser$1;
  16105. const mapperTabPage_js_1 = mapperTabPage;
  16106. const Transport_js_1 = Transport;
  16107. (0, mapperTabPage_js_1.generatePage)();
  16108. const mapperTabToServerTransport = new Transport_js_1.WindowBidiTransport();
  16109. const cdpTransport = new Transport_js_1.WindowCdpTransport();
  16110. /**
  16111. * A CdpTransport implementation that uses the window.cdp bindings
  16112. * injected by Target.exposeDevToolsProtocol.
  16113. */
  16114. const cdpConnection = new CdpConnection_js_1.MapperCdpConnection(cdpTransport, mapperTabPage_js_1.log);
  16115. /**
  16116. * Launches the BiDi mapper instance.
  16117. * @param {string} selfTargetId
  16118. * @param options Mapper options. E.g. `acceptInsecureCerts`.
  16119. */
  16120. async function runMapperInstance(selfTargetId, options) {
  16121. // eslint-disable-next-line no-console
  16122. console.log('Launching Mapper instance with selfTargetId:', selfTargetId);
  16123. const bidiServer = await BidiMapper_js_1.BidiServer.createAndStart(mapperTabToServerTransport, cdpConnection,
  16124. /**
  16125. * Create a Browser CDP Session per Mapper instance.
  16126. */
  16127. await cdpConnection.createBrowserSession(), selfTargetId, options, new BidiParser_js_1.BidiParser(), mapperTabPage_js_1.log);
  16128. (0, mapperTabPage_js_1.log)(log_js_1.LogType.debugInfo, 'Mapper instance has been launched');
  16129. return bidiServer;
  16130. }
  16131. /**
  16132. * Set `window.runMapper` to a function which launches the BiDi mapper instance.
  16133. * @param selfTargetId Needed to filter out info related to BiDi target.
  16134. * @param options Mapper options. E.g. `acceptInsecureCerts`. */
  16135. window.runMapperInstance = async (selfTargetId, options) => {
  16136. await runMapperInstance(selfTargetId, options);
  16137. };
  16138. return bidiTab;
  16139. })();
  16140. //# sourceMappingURL=mapperTab.js.map